From ehamiter at gmail.com Sun Aug 1 00:40:05 2010 From: ehamiter at gmail.com (Eric Hamiter) Date: Sat, 31 Jul 2010 17:40:05 -0500 Subject: [Tutor] Writing scripts and apps for Internet consumption In-Reply-To: <4C549A11.40807@gmail.com> References: <4C549A11.40807@gmail.com> Message-ID: On Sat, Jul 31, 2010 at 4:48 PM, bob gailer wrote: > > Please post that code, and the URL you use to invoke it. > test.py: this works on my laptop but not on the server http://pastebin.com/ChjUzLRU test-working.py: this works on both laptop & server http://pastebin.com/iLNTrGdW both available for execution here: http://erichamiter.com/xkred27/ > Do you import cgi? > Yes. > > There is a companion module (cgitb) that captures exceptions and returns > the traceback to the web browser. > I tried that as well. I'm sure I'm missing something fundamental here, but that's kind of obvious since I posted I don't know what I'm doing in the first place! :) Thanks, Eric -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Aug 1 02:12:53 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 1 Aug 2010 01:12:53 +0100 Subject: [Tutor] Writing scripts and apps for Internet consumption References: Message-ID: "Eric Hamiter" wrote > the most rudimentary level of the basics. What I keep reading is how > Python > is most powerful on server side applications, in the cloud, so to > speak. The > portability of Python is also widely evangelized. I'm not sure I'd agree with that assertion. Python is a geeral purpose programming language and is equally at home on the desktop as on a server. Where it is definitely not at home is inside a web client - that territory lies with Javascript and Flash etc. > Here's my problem with this so far-- I can write a basic script, > have it > take in data, rearrange it, and spit it back out. Following along in > a book, > I can write a basic GUI or game. It's all wine and roses on my > Windows > laptop, where I have everything configured just right, with all of > the > modules in place where they need to be. Good thats as it should be. > Moving this to a server or even another computer so far has been a > seemingly > impossible task. Moving desktop applications to a server is a non trivial task in anty language, the paradigms are completely different and will usually require extensive re-engineering of your designs. The most important aspect being that server applications don't generally have a user interface - that goes on the client... > There's a lot of documentation for CGI scripting (which is > now frowned upon, with every page recommending looking into wsgi), Yes although CGI is fine for very simple apps, but ay7thing more than trivial really is better done on a web framework - but the frameworks all have a steep learning curve. A bit like learning a new GUI framework - the principles are all the same but the details are different.. > have been applications devoted to transforming scripts into Windows > executables (py2exe, etc.) but it seems like this is much more > confusing > than need be, and I can't get them to work regardless. This is a fairly complex task and personally I prefer to just install Python on the PC. After all thats what these packaging tools do under the covers, you just get a copy of python for every application instead of a single shared version... The tools make it as easy as they can but its never going to be a trivial task. > for solutions, choosing any terms like "web" or "server" point me to > massive > framework solutions like Django or Pylons, These are not massive although they are non trivial. Massive is something like Zope or Plone... But they do make web programming much much easier than basic CGI. And the more complex the application the more useful they become. > which seem extraordinarily complex for what I want. Have you considered that what you want might be more complex than you suspect? Web programming is more complex than desktop programming and combines elements of GUI design, network programming and server programming. To do it well requires a fauirly high level of skill - although there are plenty folk out there not doing it well as the number of slow and badly designed (from a users point of view) web sites testifies! > Specific examples: I have a livewires/pygame GUI game I wrote along > with > folowing the book "Python Programming for the Absolute Beginner" and > it > works great on my laptop. I tried installing Python/pygame on a work > computer and copying my scripts over, but it endlessly fails with > errors so > obtuse I can't troubleshoot. OK, providing you are just rubnning the game on the work PC in the same way that you do on the laptop it should be fairly straightforward, assuming: 1) Are they the same versions of Python/GUI? 2) Arte they installed in the same place on the two machines? 3) Are the environment variables set to the same values? If all of these is YES then we need some specific info about the errors. > I'm not even sure if I have the correct modules > installed here. Should they be under "Lib" or "libs" or "includes"? If the modules are stangard(PyGame etc) then you shouldn't need to worry about that the installers will have done that for you. You only need to put your code in a place that Python can find it. > to use py2exe fails because I can't figure out how to include > non-scripts in > the final program, like .pngs or .jpgs. Need to ask a py2exe persopn for that, but I'd get the non exe version working first that should be esier! > How would I even begin to put this on a server? I'm clueless. If its a game you need to separate out the game logic, rules etc from the GUI elelemts. The GUII elements then become a separate client program that communicates with the server via some kind of networking protocol. This is what I meant about re-engineering your app for a server. > Another program I am using on my laptop is a convenience script-- it > takes > in a text list of groceries, and spits out a formatted list based on > aisle > locations so I can get in and out of the grocery store faster. My > laptop is > the only place I can use this. I've tried using multiple CGI > examples, and > it always results in a "File Not Found" error. Not even sure how I > can debug > it. I can have the server do a simple one-line of printing "Hello > World" but > anything more complicated than that makes it implode. Again you need to design it as a cliernt server app. The client captures the user input, sends it to the server and when the server spits back the data the client reads it and formats it for the user to see. In a web context you probably need web pages for input and output. The input one will have an HTML form with a submit button. The server will need to read the data submitted by the form, perform the translations and return the data. If you use raw CGI the server will return the data as an HTML page. If you use a framework it will typically be returned as a Python dictionary, depending on the framework You will then define the output page to substitute the data into special markers (based on a templating engine). Python is a great tool for writing web server apps. But writing web server apps, even in Python, even with a framework, is much harder than writing desktop apps. > The most frustrating thing is how flippantly experienced programmers > say to > use Django for Python web apps because it's so simple to use. Simpler than CGI for non trivial apps is what they mean. > good half-day to just install it, and unless I'm writing a sample > code or if > I want to clone a newspaper service, I have absolutely no idea how I > would > use it efficiently. You need to work through the extensive tutorial documentation. Do not be misled, writing web apps is not trivial. Knowing Python is just the start. > I want to learn the basics before running off to learn a > new framework. So write a simple application using CGI. Something like an adfdress book or library system. A simple search/display/add/delete/edit type application. That will give you enough to understand what a pain CGI is and appreciate what a help the frameworks really are. > In short, is there a "simple" method for putting python scripts onto > a > server that I do not host myself? No. There are ways that are easier than others but server programming is not simple. And converting desktop apps to server apps is non trivial. Of course you can write apps that can be run on a desktop or a server as needed but they have to be built for that from the begginning. Its much easier to convert a server app to desktop use than the other way round. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Aug 1 02:20:31 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 1 Aug 2010 01:20:31 +0100 Subject: [Tutor] Python - RPG Combat System References: Message-ID: "Jason MacFiggen" wrote > and also, what can I do instead of writing print so many times? Learn about format strings and use triple quoted strings. > else: > print "Menu Selections: " > print "1 - Attack" > print "2 - Defend" > print menu1 = """ Menu Selections 1 - Attack 2 - Defend """ else: print menu1 > if choice == 1: > mo_hp = mo_hp - my_dmg > print "The Lich King is at ", mo_hp, "Hit Points" > print "You did ", my_dmg, "damage!" > print if choice == 1: mo_hp = mo_hp - my_dmg print "The Lich King is at %s Hit Points\nYou did %s damage\n" % (mo_hp, my_dmg) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sun Aug 1 02:24:08 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 1 Aug 2010 10:24:08 +1000 Subject: [Tutor] Simple Python Program In-Reply-To: <4C546CD7.5010207@gmail.com> References: <4C546CD7.5010207@gmail.com> Message-ID: <201008011024.09625.steve@pearwood.info> On Sun, 1 Aug 2010 04:35:03 am bob gailer wrote: > Continue to avoid writing functions. They are not necessary for such > a simple program. That is *terrible* advice. Absolutely awful. Functions should not be avoided unless necessary. Functions should be used unless there is a compelling reason to avoid them. This is not 1972 any more, and we're not teaching kids to write spaghetti code with BASIC and GOTO. Functions, or their object-oriented equivalent methods, are *the* single most important feature of programming. And they're simple too -- they might not be the first thing you teach an absolute newbie who has never programmed before, but they're pretty close. -- Steven D'Aprano From steve at pearwood.info Sun Aug 1 02:55:46 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 1 Aug 2010 10:55:46 +1000 Subject: [Tutor] Simple Python Program In-Reply-To: References: Message-ID: <201008011055.47334.steve@pearwood.info> Hi Jason, Let's see if we can clean up some of your program. You had this function: > def inputNames(playerOne, PlayerTwo): > p1name = raw_input("Enter your name.") > p2name = raw_input("Enter your name.") > return playerOne, playerTwo Let's write this in plain English. (1) The function takes as input a value called "playerOne", and a value called "PlayerTwo". Take careful note of the case (upper and lower) of the names, because that is important to Python. (2) It asks the user for a name, and assigns it to the variable "p1name". (3) It asks the user for a second name, and assigns it to "p2name". (4) It then ignores p1name and p2name, and does nothing with them. (5) And returns the variable playerOne and playerTwo. Take careful note that the *second* one does not match in case: it starts with a lowercase p, so you will get an error because "playerTwo" doesn't exist. Let's re-write it to work. For starters, there's no need to pass the players' names to the function which is supposed to get the players' names. Secondly, "inputNames" is such a dry, overly technical name. Let's make it simpler and friendlier: def get_names(): playerOne = raw_input("Enter the first player's name: ") playerTwo = raw_input("Enter the second player's name: ") return playerOne, playerTwo Now let's write a function to roll a single dice. Single die. Whatever. import random # We need Python's random number generator. def dice(sides=6): return random.randint(1, sides) This uses a *default value* for the number of sides. If you want to roll a ten-sided die, you call: dice(10) and it will give back a random number between 1 and 10. But if you want to roll the default six-sided die, you can leave out the 6 and just write: dice() and it will give back a random number between 1 and 10. Let's write a small program to play dice between two players. We'll make a simple dice game function that returns the name of the winning player, or the empty string in the case of a draw. def dice_game(playerOne, playerTwo): # playerOne rolls a single six-sided die. rollOne = dice() # So does playerTwo. rollTwo = dice() # The winner is the one who gets a higher number. if rollOne > rollTwo: return playerOne elif rollTwo > rollOne: return playerTwo else: # They must have rolled equal, so a draw. return "" Putting it all together, copy the lines between the ###### into a new file and save it as a Python program: ###### import random def dice(sides=6): return random.randint(1, sides) def get_names(): playerOne = raw_input("Enter the first player's name: ") playerTwo = raw_input("Enter the second player's name: ") return playerOne, playerTwo def dice_game(playerOne, playerTwo): # playerOne rolls a single six-sided die. rollOne = dice() # So does playerTwo. rollTwo = dice() # The winner is the one who gets a higher number. if rollOne > rollTwo: return playerOne elif rollTwo > rollOne: return playerTwo else: # They must have rolled equal, so a draw. return "" def displayWinner(winner): print "And the winner is: ", if winner == "": print "... the game is a draw!" else: print winner print def main(): playerOne, playerTwo = get_names() play_again = True while play_again: print "Rolling dice..." winner = dice_game(playerOne, playerTwo) displayWinner(winner) answer = raw_input("Would you like to play again? (y/n) ") play_again = answer.strip().lower() in ('y', 'yes') main() ###### Have a play around with that, and feel free to ask any questions you like. -- Steven D'Aprano From davea at ieee.org Sun Aug 1 03:34:02 2010 From: davea at ieee.org (Dave Angel) Date: Sat, 31 Jul 2010 21:34:02 -0400 Subject: [Tutor] Making a sound In-Reply-To: References: Message-ID: <4C54CF0A.5080101@ieee.org> Michael Bernhard Arp S???????????????????????????????? wrote: > Greetings, programs. > > How do I create a sound from python? I'm thinking along the line of > generating a sinus wave where I can control the frequency and duration. I > want to produce a string of sounds based on a character string. Probably not > original. :-) I don't want to save a sound to a file and play it > afterwards. Preferably it should be something from PYPI. Any suggestions? > > Thanks in advance. > > Kind regards > > Michael B. Arp S?rensen > Programmer / BOFH > > "If you want to enter my network while I'm out, you can find my SSH-key > under my mouse mat" - Michael Bernhard Arp S?rensen > > What's your platform? If you're on Windows, consider the Win32 extensions, or just get the Active Python distribution from ActiveState, which includes them, and other stuff for Windows. Anyway, then look for the winsound.PlaySound() function. DaveA From davea at ieee.org Sun Aug 1 03:52:25 2010 From: davea at ieee.org (Dave Angel) Date: Sat, 31 Jul 2010 21:52:25 -0400 Subject: [Tutor] Writing scripts and apps for Internet consumption In-Reply-To: References: <4C549A11.40807@gmail.com> Message-ID: <4C54D359.3090204@ieee.org> Eric Hamiter wrote: > On Sat, Jul 31, 2010 at 4:48 PM, bob gailer wrote: > > >> Please post that code, and the URL you use to invoke it. >> >> > > test.py: this works on my laptop but not on the server > > http://pastebin.com/ChjUzLRU > > test-working.py: this works on both laptop & server > > http://pastebin.com/iLNTrGdW > > both available for execution here: > > http://erichamiter.com/xkred27/ > > >> > Do you import cgi? >> > >> > Yes. > Not in this code, you don't. You also don't need it for this case. But I wonder if you're describing something different than what you're posting. > I can't see where you attempt to produce even the simplest of html in the http://pastebin.com/ChjUzLRU code. So why do you declare it as text/html ? DaveA From bgailer at gmail.com Sun Aug 1 04:53:31 2010 From: bgailer at gmail.com (bob gailer) Date: Sat, 31 Jul 2010 22:53:31 -0400 Subject: [Tutor] Writing scripts and apps for Internet consumption In-Reply-To: References: <4C549A11.40807@gmail.com> Message-ID: <4C54E1AB.50406@gmail.com> On 7/31/2010 6:40 PM, Eric Hamiter wrote: > On Sat, Jul 31, 2010 at 4:48 PM, bob gailer > wrote: > > > Please post that code, and the URL you use to invoke it. > > > test.py: this works on my laptop but not on the server > > http://pastebin.com/ChjUzLRU > > test-working.py: this works on both laptop & server > > http://pastebin.com/iLNTrGdW > > both available for execution here: > > http:// erichamiter.com/ > xkred27/ > > > > Do you import cgi? > > > Yes. > > > There is a companion module (cgitb) that captures exceptions and > returns the traceback to the web browser. > > > I tried that as well. I'm sure I'm missing something fundamental here, > but that's kind of obvious since I posted I don't know what I'm doing > in the first place! :) Main difference I see is lack of any html tags in test.py! Try adding 1. print "" 2. print "Publix Aide" 3. print "" 4. # the store map print statements go here 5. print "" Where is erichamiter.com/ hosted? Is there a way I could put something there? -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From ehamiter at gmail.com Sun Aug 1 05:03:37 2010 From: ehamiter at gmail.com (Eric Hamiter) Date: Sat, 31 Jul 2010 22:03:37 -0500 Subject: [Tutor] Writing scripts and apps for Internet consumption In-Reply-To: <4C54E1AB.50406@gmail.com> References: <4C549A11.40807@gmail.com> <4C54E1AB.50406@gmail.com> Message-ID: On Sat, Jul 31, 2010 at 9:53 PM, bob gailer wrote: > > Main difference I see is lack of any html tags in test.py! Try adding > > 1. print "" > 2. print "Publix Aide" > 3. print "" > 4. # the store map print statements go here > 5. print "" > > I understand that this would work-- my question was how can I get a python script to "do anything" on it? Why is it returning a 404 error? > Where is erichamiter.com/ hosted? Is > there a way I could put something there? > > A hosted server, so it's not on my local machine. Afraid I can't hand you any access directly to it, I have too much personal stuff on there at the moment. I would be more than happy to look at any code you would want to send in an email or pastebin, and I could put it up for a test. Thanks, Eric -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Aug 1 05:11:41 2010 From: bgailer at gmail.com (bob gailer) Date: Sat, 31 Jul 2010 23:11:41 -0400 Subject: [Tutor] Simple Python Program In-Reply-To: <201008011024.09625.steve@pearwood.info> References: <4C546CD7.5010207@gmail.com> <201008011024.09625.steve@pearwood.info> Message-ID: <4C54E5ED.9020302@gmail.com> On 7/31/2010 8:24 PM, Steven D'Aprano wrote: > On Sun, 1 Aug 2010 04:35:03 am bob gailer wrote: > >> Continue to avoid writing functions. They are not necessary for such >> a simple program. >> > That is *terrible* advice. Absolutely awful. > Well I disagree. I was trying to steer the OP to get the simplest possible program running, then do incremental expansion. In my understanding user defined functions serve these purposes: 1 - modularizing large programs 2 - factoring out common code 3 - providing callbacks 4 - choosing callable objects from some collection. 5 - providing a main function for the if __name__ == "__main__" idiom 6 - what else can we think of? None of these are needed in this simple case. > Functions should not be avoided unless necessary. Functions should be > used unless there is a compelling reason to avoid them. > Once the OP has succeeded in getting some program running he will experience some relief and satisfaction. Then I think it is time to add language features. But not just for the sake of using them. > This is not 1972 any more, and we're not teaching kids to write > spaghetti code with BASIC and GOTO. Functions have no relationship to avoiding spaghetti code. Python makes spaghetti code impossible since it lacks a goto or equivalent statement. > Functions, or their object-oriented > equivalent methods, are *the* single most important feature of > programming. And they're simple too Well - almost simple. Until you get into issues like global vs local names, positional vs keyword arguments, required vs optional arguments, default values (especially mutable objects), * and **, generator functions, magic methods, nested defs, decorators, .... > -- they might not be the first thing you teach an absolute newbie who has never programmed before That is what our OP appears to be. -- Bob Gailer 919-636-4239 Chapel Hill NC From steve at pearwood.info Sun Aug 1 05:28:44 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 1 Aug 2010 13:28:44 +1000 Subject: [Tutor] Python - RPG Combat System In-Reply-To: References: Message-ID: <201008011328.45175.steve@pearwood.info> On Sun, 1 Aug 2010 10:20:31 am Alan Gauld wrote: > "Jason MacFiggen" wrote > > > and also, what can I do instead of writing print so many times? > > Learn about format strings and use triple quoted strings. *slaps self in head* Doh! How could I have forgotten triple quoted strings? *slinks off in shame* -- Steven D'Aprano From bgailer at gmail.com Sun Aug 1 05:40:24 2010 From: bgailer at gmail.com (bob gailer) Date: Sat, 31 Jul 2010 23:40:24 -0400 Subject: [Tutor] Writing scripts and apps for Internet consumption In-Reply-To: References: <4C549A11.40807@gmail.com> <4C54E1AB.50406@gmail.com> Message-ID: <4C54ECA8.8040108@gmail.com> On 7/31/2010 11:03 PM, Eric Hamiter wrote: > > On Sat, Jul 31, 2010 at 9:53 PM, bob gailer > wrote: > > > Main difference I see is lack of any html tags in test.py! Try adding > > 1. > print "" > 2. > print "Publix Aide" > 3. > print "" > 4. > # the store map print statements go here > 5. > print "" > > I understand that this would work-- Did you send the altered code to the server and test it? Did it succeed or fail? What happens if you put the grocery code into test-working.py? > my question was how can I get a python script to "do anything" on it? > Why is it returning a 404 error? > > Where is erichamiter.com/ > hosted? Is there a way I could put something there? > > > A hosted server, so it's not on my local machine. Afraid I can't hand > you any access directly to it, I have too much personal stuff on there > at the moment. I would be more than happy to look at any code you > would want to send in an email or pastebin, and I could put it up for > a test. Could I have a link to the hosting service? Perhaps I could set up my own account. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Sun Aug 1 05:51:41 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Sat, 31 Jul 2010 22:51:41 -0500 Subject: [Tutor] Simple Python Program In-Reply-To: <4C54E5ED.9020302@gmail.com> References: <4C546CD7.5010207@gmail.com> <201008011024.09625.steve@pearwood.info> <4C54E5ED.9020302@gmail.com> Message-ID: <1267E71F-9A68-4501-AA68-2362BEDDF401@gmail.com> I think I agree more with bob on this one - he wasn't saying functions weren't important, just that they weren't important to this case. Sure polymorphism and inheritance and properties and generators and list comprehensions are awesome and useful, but I wouldn't suggest they are necessary for every situation. Same with Functions. That's just the trap that java fell into by making everything an object... It just adds a couple of useless lines that will just serve to confuse newbies and irritate pros. IMHO. Sent from my iPhone On Jul 31, 2010, at 10:11 PM, bob gailer wrote: > On 7/31/2010 8:24 PM, Steven D'Aprano wrote: >> On Sun, 1 Aug 2010 04:35:03 am bob gailer wrote: >> >>> Continue to avoid writing functions. They are not necessary for such >>> a simple program. >>> >> That is *terrible* advice. Absolutely awful. >> > > Well I disagree. I was trying to steer the OP to get the simplest possible program running, then do incremental expansion. > > In my understanding user defined functions serve these purposes: > 1 - modularizing large programs > 2 - factoring out common code > 3 - providing callbacks > 4 - choosing callable objects from some collection. > 5 - providing a main function for the if __name__ == "__main__" idiom > 6 - what else can we think of? > > None of these are needed in this simple case. > >> Functions should not be avoided unless necessary. Functions should be >> used unless there is a compelling reason to avoid them. >> > > Once the OP has succeeded in getting some program running he will experience some relief and satisfaction. Then I think it is time to add language features. But not just for the sake of using them. >> This is not 1972 any more, and we're not teaching kids to write >> spaghetti code with BASIC and GOTO. > > Functions have no relationship to avoiding spaghetti code. Python makes spaghetti code impossible since it lacks a goto or equivalent statement. > >> Functions, or their object-oriented >> equivalent methods, are *the* single most important feature of >> programming. And they're simple too > > Well - almost simple. Until you get into issues like global vs local names, positional vs keyword arguments, required vs optional arguments, default values (especially mutable objects), * and **, generator functions, magic methods, nested defs, decorators, .... > >> -- they might not be the first thing you teach an absolute newbie who has never programmed before > > That is what our OP appears to be. > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Sun Aug 1 07:50:13 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 1 Aug 2010 15:50:13 +1000 Subject: [Tutor] Simple Python Program In-Reply-To: <4C54E5ED.9020302@gmail.com> References: <201008011024.09625.steve@pearwood.info> <4C54E5ED.9020302@gmail.com> Message-ID: <201008011550.15749.steve@pearwood.info> On Sun, 1 Aug 2010 01:11:41 pm bob gailer wrote: > On 7/31/2010 8:24 PM, Steven D'Aprano wrote: > > On Sun, 1 Aug 2010 04:35:03 am bob gailer wrote: > >> Continue to avoid writing functions. They are not necessary for > >> such a simple program. > > > > That is *terrible* advice. Absolutely awful. > > Well I disagree. I was trying to steer the OP to get the simplest > possible program running, then do incremental expansion. In hindsight, my post was a bit harsh. I actually agreed with nearly everything else you said, which I should have said. So I would like to apologise for the way I said what I said. > In my understanding user defined functions serve these purposes: > 1 - modularizing large programs Leave out the "large", and you would be right. There is no limit to how small a program need be before using functions becomes appropriate. A one line program could be better off split into functions if the line is complex enough. > 2 - factoring out common code > 3 - providing callbacks > 4 - choosing callable objects from some collection. > 5 - providing a main function for the if __name__ == "__main__" idiom > 6 - what else can we think of? Code reuse, ease of testing, simplicity of debugging, separating the interface from the implementation, avoiding side-effects, writing self-documenting code, ease of refactoring, simplifying redesign, and probably many others. > None of these are needed in this simple case. Whether needed or not, splitting the code into small, easily testable, self-contained pieces is never a bad thing to do. Sometimes, rarely, for performance reasons you might choose to give up all those positives in order to win a bit of extra performance in a critical section of code, but that's the only reason I can think of to *actively* avoid the use of functions. (As opposed to passively avoid them because you just started programming yesterday and haven't got to "Chapter 3: Functions" yet.) > > Functions should not be avoided unless necessary. Functions should > > be used unless there is a compelling reason to avoid them. > > Once the OP has succeeded in getting some program running he will > experience some relief and satisfaction. Then I think it is time to > add language features. But not just for the sake of using them. This is an excellent point. I might take the OP many, many hours, or days, or weeks, of effort to get the entire program working. The process until that point is just frustration after frustration as things go wrong. Until the entire function is working, it's hard to see any positive progress because it's just bug after bug after bug. Or he can write one function that does one small thing, debug that, and get a sense of satisfaction that this function, at least, is working as designed, before going on to write the next function. Functions are not just for the compiler, they are for the human reader and writer too. It's easier to wrap your brain around a small, self-contained piece of code that does one thing in three or five or ten lines, than a comparatively large piece of code that requires thirty or fifty. > > This is not 1972 any more, and we're not teaching kids to write > > spaghetti code with BASIC and GOTO. > > Functions have no relationship to avoiding spaghetti code. Python > makes spaghetti code impossible since it lacks a goto or equivalent > statement. Nonsense. Procedural programming (the use of functions, procedures, or sub-routines) was created partly to avoid spaghetti code. The primary reason GOTO is to be avoided is because of the tendency to lead to spaghetti. (Technically a function call is a specialist kind of GOTO. In early BASIC, it would be like a GOSUB. But it is a structured jump, tamed and on a leash rather than running wild like GOTO.) Of course, the use of functions in and of itself does not guarantee you won't write spaghetti code. Object oriented programming sadly lends itself to class-based spaghetti (fettuccine perhaps?). But that's not likely to be a risk here. > > Functions, or their object-oriented > > equivalent methods, are *the* single most important feature of > > programming. And they're simple too > > Well - almost simple. Until you get into issues like global vs local > names, positional vs keyword arguments, required vs optional > arguments, default values (especially mutable objects), * and **, > generator functions, magic methods, nested defs, decorators, .... Of course. But apart from the distinction between local and global, everything else is optional. > > -- they might not be the first thing you teach an absolute newbie > > who has never programmed before > > That is what our OP appears to be. He's experienced enough to be attempting to write functions. I don't believe you are doing him a favour by discouraging him. -- Steven D'Aprano From huyslogic at gmail.com Sun Aug 1 09:30:57 2010 From: huyslogic at gmail.com (Huy Ton That) Date: Sun, 1 Aug 2010 03:30:57 -0400 Subject: [Tutor] Where to start with Unit Testing Message-ID: Hi all, Do any of you have any feedback, strategies and best practices related to unit testing within Python. This is a relatively new topic for me. I was thinking of starting with reading the documentation associate with the unittest module. -Huy -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sun Aug 1 10:03:10 2010 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 01 Aug 2010 09:03:10 +0100 Subject: [Tutor] Where to start with Unit Testing In-Reply-To: References: Message-ID: On 01/08/2010 08:30, Huy Ton That wrote: > Hi all, > > Do any of you have any feedback, strategies and best practices related to > unit testing within Python. This is a relatively new topic for me. I was > thinking of starting with reading the documentation associate with the > unittest module. > > -Huy > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor The documentation is a good starting point. Then see the excellent:- http://diveintopython.org/unit_testing/index.html. Also look at the actual Python test code in the Lib\test\ directory. Depending on the code that you're wanting to test you might also want to google for mock+objects, but this can wait until you've got your feet under the table. HTH. Mark Lawrence. From rdmoores at gmail.com Sun Aug 1 10:08:09 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 1 Aug 2010 01:08:09 -0700 Subject: [Tutor] problem with simple script In-Reply-To: References: Message-ID: (This repeats an earlier post of mine, and gives the correct link to the script I wrote about: . In a subsequent post I reported that I had gotten rid of the flag in a further revision: This link is correct. I apologize for the confusion. --Dick) On Wed, Jul 28, 2010 at 08:35, Richard D. Moores wrote: > Now I'll dig into all the help I received. I see an *args in Steven's > detailed reply. That'll take some reviewing to understand. Here's my slight revision of Steven's script (see my note, lines 9-14) -- revised only because I wanted it to handle the case where the user (me) entered the interval bounds in the wrong order, e.g., 10, 5 instead of 5, 10. I've also added a way ('r') for the user to choose to get another random number in the same interval without having to reenter the bounds: . Then I needed a way ('c') to choose to change the bounds after 'r' had been used. I used a flag (lines 42, 53, 55) to accomplish these additions. Was there a better way? Should I have written a couple of extra functions instead of using the flag? Are flags unpythonic? I've learned a lot from his script, and hope to learn more -- I'm still grappling with the *args of line 46. What I've learned so far: 1. To separate the front end (for the user) from the back end. See his note on line 3. 2. The use of maxsplit with str.split(). Line 29. 3. Using the return of a function to call another function. Line 38. 4. In main(), he assigns the prompt to a variable _before_ the while loop (line 41), so the assignment is done only once, rather than each time through the loop. Not a biggie in this script, but a good thing to learn, I think. So thanks, Steven! Now, on to *args! Dick From timomlists at gmail.com Sun Aug 1 10:12:32 2010 From: timomlists at gmail.com (Timo) Date: Sun, 01 Aug 2010 10:12:32 +0200 Subject: [Tutor] Writing scripts and apps for Internet consumption In-Reply-To: References: <4C549A11.40807@gmail.com> Message-ID: <4C552C70.1020007@gmail.com> On 01-08-10 00:40, Eric Hamiter wrote: > On Sat, Jul 31, 2010 at 4:48 PM, bob gailer > wrote: > > > Please post that code, and the URL you use to invoke it. > > > test.py: this works on my laptop but not on the server > > http://pastebin.com/ChjUzLRU Just a wild guess, but maybe it is failing on the following line: with open("grocery_list.txt") as grocery_list: The with statement was introduced in Python 2.5, and if I look at my own webhost, they are still with Python 2.4. Make a script that prints the Python version (with sys.version_info or sys.version for example) or ask your webhost. You can also put this on top of your script, so it shows you a nice Python traceback instead of an error: import cgitb cgitb.enable() Cheers, Timo > > test-working.py: this works on both laptop & server > > http://pastebin.com/iLNTrGdW > > both available for execution here: > > http://erichamiter.com/xkred27/ > > > Do you import cgi? > > > Yes. > > > There is a companion module (cgitb) that captures exceptions and > returns the traceback to the web browser. > > > I tried that as well. I'm sure I'm missing something fundamental here, > but that's kind of obvious since I posted I don't know what I'm doing > in the first place! :) > > Thanks, > > Eric > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From quasipedia at gmail.com Sun Aug 1 15:25:43 2010 From: quasipedia at gmail.com (Mac Ryan) Date: Sun, 01 Aug 2010 15:25:43 +0200 Subject: [Tutor] Where to start with Unit Testing In-Reply-To: References: Message-ID: <1280669143.3357.115.camel@jabbar> On Sun, 2010-08-01 at 03:30 -0400, Huy Ton That wrote: > Hi all, > > Do any of you have any feedback, strategies and best practices related > to unit testing within Python. This is a relatively new topic for me. > I was thinking of starting with reading the documentation associate > with the unittest module. My answer falls in the category "feedback" (I was also going to mention the diveintopython page, but somebody else has done that already!), so you should be aware what follows is highly subjective... JUST THINK... IN PYTHON! IMO, unit testing is really easy to pick up. It really does not amount to much more than taking note (in python) of what you are thinking when you are coding. If you are anything like me, when you code you keep on formulating "rules" in your head, in the line of "when everything works as expected, if the methods iterates four times, then this method must return X" or "when everything works as expected, if a user enter a value over 212 then the script must throw this exception", etc... * the "when everything works as expected" translates in "this test pass when..." * the "if X" translates in your test case (i.e. the scenario you are testing for) * the "then Y" translates in "the outcome of my test case must be Y" TESTING IS VALUABLE IN THE LONG RUN At times, designing and coding a test is a time-consuming activity, and if the code is particularly straightforward you might be tempted to skip the unit testing altogether. In my experience - however - unit testing is never as useful on the spot as it is three months from now, when you will have/want/choose to modify a little bit of your old code, and all of a sudden everything will break. In the latter scenario, your test suite will be an invaluable asset. FUNCTIONAL PROGRAMMING WINS The most difficult thing in writing a test, is replicating the state of the environment needed for the test to happen. This is especially (but not uniquely) true for DB-driven applications, when you might wish to perform test on methods that interact with the DB. In that case you have to create a test DB, populate it with ~credible data, etc... The most "functional" (as in functional programming, i.e. machine-state independent) is your code, the easiest is to write a test. Example: if you need to check a method that validate the postal code of an address based on the name of the city, it is easier to test a method that is invoked with "validate_postal_code(code, city)" rather than one that is invoked with "validate_postal_address(user)" and that will have to retrieve the full address of a user from a DB, and extract the city and postal address from it. MVC WINS I never test UI's. I know it is bad... but it is simply too time-consuming for me (I'll be very glad if somebody reading this will show me how one can make it snappier!). This means - at least for me - that writing tests become extremely easier for me if I keep separated the presentation layer from all the rest of the stuff. EVERY BUG IS A TEST YET NOT WRITTEN A program that passes all its tests is not necessarily a bug-free program. But once you find a new bug, try to make a point of writing a new test that check for that particular scenario in which said bug is happening. TEST-DRIVEN IS BETTER What I find useful (although not always applicable) is to start my programming session by writing the tests before I write the code to be tested. This somehow reconnect to my previously articulated "just think... in python!" point: you are however *already doing a list of rules* in your head, before writing code, so you could well write it down directly in code. All you need is to create a mock method/function in your code with the same signature you are using in your test. For example. You could write tests in the form: assertEqual(better_square_root(9), 3) assertRaises(ValueError, better_square_root, -4) and then write in your module: def my_better_square_root(number): pass all your tests will of course initially fail, but then you will keep on working on the code of my_better_square_root until all your tests pass. Well, these are just my two ?... As stated in the beginning: highly subjective, so keep your mind open for other (possibly opposite) opinions too! :) HTH, Mac. From roybayot at gmail.com Sun Aug 1 16:20:13 2010 From: roybayot at gmail.com (Roy Khristopher Bayot) Date: Sun, 1 Aug 2010 22:20:13 +0800 Subject: [Tutor] Help with Import Error problems Message-ID: Hi. Good day. I am having an import error problem. Last week, I was following this site: http://sites.google.com/site/spatialpython/processing-aster-with-python-numpy-and-gdal. I was able to make the python script run on the terminal. But this week, it was throwing some error. This was the traceback: Traceback (most recent call last): File "aster_convert.py", line 2, in from osgeo import gdal File "/usr/lib/python2.6/dist-packages/osgeo/__init__.py", line 21, in _gdal = swig_import_helper() File "/usr/lib/python2.6/dist-packages/osgeo/__init__.py", line 17, in swig_import_helper _mod = imp.load_module('_gdal', fp, pathname, description) ImportError: /usr/lib/libspatialite.so.2: undefined symbol: GEOSSimplify I tried google-ing for the ImportError but the results dont make sense. It was working last week. I might have installed something that "broke" it but I dont know how to trace it back. Could I ask for some pointers on how to fix this? Thank you. Roy P.S. I dont know if this is the right list to post this. If it isnt, I'm sorry for the inconvenience. Kindly direct me to the right one. -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Sun Aug 1 16:39:47 2010 From: evert.rol at gmail.com (Evert Rol) Date: Sun, 1 Aug 2010 16:39:47 +0200 Subject: [Tutor] Help with Import Error problems In-Reply-To: References: Message-ID: > Hi. Good day. > > I am having an import error problem. Last week, I was following this site: http://sites.google.com/site/spatialpython/processing-aster-with-python-numpy-and-gdal. I was able to make the python script run on the terminal. But this week, it was throwing some error. > > This was the traceback: > > Traceback (most recent call last): > File "aster_convert.py", line 2, in > from osgeo import gdal > File "/usr/lib/python2.6/dist-packages/osgeo/__init__.py", line 21, in > _gdal = swig_import_helper() > File "/usr/lib/python2.6/dist-packages/osgeo/__init__.py", line 17, in swig_import_helper > _mod = imp.load_module('_gdal', fp, pathname, description) > ImportError: /usr/lib/libspatialite.so.2: undefined symbol: GEOSSimplify > > I tried google-ing for the ImportError but the results dont make sense. It was working last week. I might have installed something that "broke" it but I dont know how to trace it back. > > Could I ask for some pointers on how to fix this? I have absolutely no experience with the libraries you're using, but the error tells you that libspatialite is expected to have the symbol GEOSSimplify (could be a function or a class definition, for example), which isn't found. The first Google hit for libspatialite results in http://www.gaia-gis.it/spatialite/how_to_build_libspatialite.html , which mentions two required dependencies: PROJ.4 and GEOS. Probably the latter provides GEOSSimplify. So, you've either uninstalled the GEOS library, your LD_ LIBRARY_PATH settings settings aren't what they were a week ago, or you've reinstalled libspatialite, but this time with the no-geos option. For a quick check, try the following from the command line: $> ldd /usr/lib/libspatialite.so.2 and see if it has any missing dependencies. If there's any missing (you can also post the output here if you'd like), see if you can that dependency somewhere on your system (the 'locate' command can help, or just good-old 'find'). If it's missing from libspatialite but you can find that library somewhere on your system (that would probably be the GEOS library then), it's your LD_LIBRARY_PATH that's likely different. Also, what linux distro are you using? Maybe you've been using the package manager overzealously, causing some essential packages to be modified or removed? And how did you install libspatialite; or for that matter, osgeo? > > Thank you. > > Roy > > P.S. I dont know if this is the right list to post this. If it isnt, I'm sorry for the inconvenience. Kindly direct me to the right one. If libspatialite or osgeo has a mailing list, you could (also) try that one. While this error shows up in Python, it's more likely a generic installation/system settings problems. Which are often tricky to find the correct mailing list for, actually, as long as it's not clear what's the underlying cause. Good luck, and let us know what you find. Evert From python at bdurham.com Sun Aug 1 16:44:08 2010 From: python at bdurham.com (python at bdurham.com) Date: Sun, 01 Aug 2010 10:44:08 -0400 Subject: [Tutor] Where to start with Unit Testing In-Reply-To: <1280669143.3357.115.camel@jabbar> References: <1280669143.3357.115.camel@jabbar> Message-ID: <1280673848.15494.1387763331@webmail.messagingengine.com> Mac, > My answer falls in the category "feedback" ... I'm not the OP, but I wanted to let you know that I really enjoyed your feedback - excellent writeup! Malcolm From pine508 at hotmail.com Sun Aug 1 18:18:35 2010 From: pine508 at hotmail.com (Che M) Date: Sun, 1 Aug 2010 12:18:35 -0400 Subject: [Tutor] Where to start with Unit Testing In-Reply-To: References: Message-ID: > Do any of you have any feedback, strategies and best practices > related to unit testing within Python. This is a relatively new topic > for me. I was thinking of starting with reading the documentation > associate with the unittest module. The idea of unit testing/test driven development has remained foreign to me throughout my time trying to learn Python--by choice. I want to make desktop GUI applications and I don't use MVC, so the idea of writing tests strikes me as far more work--and a major delayer of getting to an application that actually does something-- than simply using the software myself and noting problems. It sounds like TDD is probably the most proper way to go about things, but, in the interest of getting something out of Python to warrant the time I've put into it, I favor a "good enough" approach for now. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Sun Aug 1 19:07:37 2010 From: mehgcap at gmail.com (Alex Hall) Date: Sun, 1 Aug 2010 13:07:37 -0400 Subject: [Tutor] web-based python? Message-ID: Hi all, I have an IPowerWeb.com server, which claims to support Python. How would I use this? For example, to start, how would I print html code to the screen, or manage input from a form? Thanks. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From hugo.yoshi at gmail.com Sun Aug 1 19:17:46 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 1 Aug 2010 19:17:46 +0200 Subject: [Tutor] web-based python? In-Reply-To: References: Message-ID: On Sun, Aug 1, 2010 at 7:07 PM, Alex Hall wrote: > Hi all, > I have an IPowerWeb.com server, which claims to support Python. How > would I use this? For example, to start, how would I print html code > to the screen, or manage input from a form? Thanks. > There is a myriad of python web development frameworks. Here's a link with a ton of info: http://wiki.python.org/moin/WebFrameworks Hugo From roybayot at gmail.com Sun Aug 1 19:35:26 2010 From: roybayot at gmail.com (Roy Khristopher Bayot) Date: Mon, 2 Aug 2010 01:35:26 +0800 Subject: [Tutor] Help with Import Error problems In-Reply-To: References: Message-ID: Evert, I got it back working. But it was with some stroke of luck. And I dont know the explanation. I installed the latest source of GEOS (as suggested by someone from the gdal channel). Then i tried the script. It gave me a different import error. ImportError: libgeos-3.3.0.so: cannot open shared object file: No such file or directory I uninstalled the thing. And then tried the script again and it worked. :| I answered some of your questions below. Again, thanks. Roy On Sun, Aug 1, 2010 at 10:39 PM, Evert Rol wrote: > > Hi. Good day. > > > > I am having an import error problem. Last week, I was following this > site: > http://sites.google.com/site/spatialpython/processing-aster-with-python-numpy-and-gdal. > I was able to make the python script run on the terminal. But this week, it > was throwing some error. > > > > This was the traceback: > > > > Traceback (most recent call last): > > File "aster_convert.py", line 2, in > > from osgeo import gdal > > File "/usr/lib/python2.6/dist-packages/osgeo/__init__.py", line 21, in > > > _gdal = swig_import_helper() > > File "/usr/lib/python2.6/dist-packages/osgeo/__init__.py", line 17, in > swig_import_helper > > _mod = imp.load_module('_gdal', fp, pathname, description) > > ImportError: /usr/lib/libspatialite.so.2: undefined symbol: GEOSSimplify > > > > I tried google-ing for the ImportError but the results dont make sense. > It was working last week. I might have installed something that "broke" it > but I dont know how to trace it back. > > > > Could I ask for some pointers on how to fix this? > > I have absolutely no experience with the libraries you're using, but the > error tells you that libspatialite is expected to have the symbol > GEOSSimplify (could be a function or a class definition, for example), which > isn't found. > The first Google hit for libspatialite results in > http://www.gaia-gis.it/spatialite/how_to_build_libspatialite.html , which > mentions two required dependencies: PROJ.4 and GEOS. Probably the latter > provides GEOSSimplify. > So, you've either uninstalled the GEOS library, your LD_ LIBRARY_PATH > settings settings aren't what they were a week ago, or you've reinstalled > libspatialite, but this time with the no-geos option. > > For a quick check, try the following from the command line: > $> ldd /usr/lib/libspatialite.so.2 > The command line returns the following lines: linux-vdso.so.1 => (0x00007fff6edff000) libsqlite3.so.0 => /usr/lib/libsqlite3.so.0 (0x00007f793015c000) libgeos_c.so.1 => /usr/local/lib/libgeos_c.so.1 (0x00007f792ff4f000) libgeos-3.2.2.so => /usr/lib/libgeos-3.2.2.so (0x00007f792fbe8000) libproj.so.0 => /usr/lib/libproj.so.0 (0x00007f792f9a6000) libm.so.6 => /lib/libm.so.6 (0x00007f792f723000) libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00007f792f40e000) libpthread.so.0 => /lib/libpthread.so.0 (0x00007f792f1f1000) libdl.so.2 => /lib/libdl.so.2 (0x00007f792efed000) libc.so.6 => /lib/libc.so.6 (0x00007f792ec69000) libgeos.so.2 => /usr/local/lib/libgeos.so.2 (0x00007f792e964000) libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x00007f792e74d000) /lib64/ld-linux-x86-64.so.2 (0x00007f7930688000) I dont know what to make of it. and see if it has any missing dependencies. If there's any missing (you can > also post the output here if you'd like), see if you can that dependency > somewhere on your system (the 'locate' command can help, or just good-old > 'find'). If it's missing from libspatialite but you can find that library > somewhere on your system (that would probably be the GEOS library then), > it's your LD_LIBRARY_PATH that's likely different. > > Also, what linux distro are you using? Maybe you've been using the package > manager overzealously, causing some essential packages to be modified or > removed? > > I'm on Ubuntu 10.04 (64 bit). I think it was from installing different GIS-related software (not all of which could be installed from the package manager). > And how did you install libspatialite; or for that matter, osgeo? > I didnt install them both explicitly. I think it's a dependency from GRASS. > > > > > > Thank you. > > > > Roy > > > > P.S. I dont know if this is the right list to post this. If it isnt, I'm > sorry for the inconvenience. Kindly direct me to the right one. > > If libspatialite or osgeo has a mailing list, you could (also) try that > one. While this error shows up in Python, it's more likely a generic > installation/system settings problems. Which are often tricky to find the > correct mailing list for, actually, as long as it's not clear what's the > underlying cause. > > > Good luck, and let us know what you find. > > Evert > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Sun Aug 1 19:45:58 2010 From: python at bdurham.com (python at bdurham.com) Date: Sun, 01 Aug 2010 13:45:58 -0400 Subject: [Tutor] web-based python? In-Reply-To: References: Message-ID: <1280684758.5989.1387778693@webmail.messagingengine.com> Alex, > I have an IPowerWeb.com server, which claims to support Python Many hosting providers claim to support Python. The best hosting service I've found for Python is webfaction.com. Originally this hosting provider specialized in just Python hosting and this enthusiasm for Python and hands-on Python skills are still part of their culture. Highly recommended. Malcolm From mehgcap at gmail.com Sun Aug 1 19:46:42 2010 From: mehgcap at gmail.com (Alex Hall) Date: Sun, 1 Aug 2010 13:46:42 -0400 Subject: [Tutor] web-based python? In-Reply-To: References: Message-ID: On 8/1/10, Hugo Arts wrote: > On Sun, Aug 1, 2010 at 7:07 PM, Alex Hall wrote: >> Hi all, >> I have an IPowerWeb.com server, which claims to support Python. How >> would I use this? For example, to start, how would I print html code >> to the screen, or manage input from a form? Thanks. >> > > There is a myriad of python web development frameworks. Here's a link > with a ton of info: > > http://wiki.python.org/moin/WebFrameworks I had looked into Django before. What is confusing me is that it sounds like it is meant to be run on the server directly. I do not have direct access to my server, I just rent space on it and can login. Maybe I am missing something, but how would I get Django onto my server if I do not have the physical box available to me? > > Hugo > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From hugo.yoshi at gmail.com Sun Aug 1 19:51:08 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 1 Aug 2010 19:51:08 +0200 Subject: [Tutor] web-based python? In-Reply-To: References: Message-ID: On Sun, Aug 1, 2010 at 7:46 PM, Alex Hall wrote: > > I had looked into Django before. What is confusing me is that it > sounds like it is meant to be run on the server directly. I do not > have direct access to my server, I just rent space on it and can > login. Maybe I am missing something, but how would I get Django onto > my server if I do not have the physical box available to me? ssh access is usually enough. Log in and check if you can run python for starters. If all you have is ftp access, you'll need to ask your host for a clarification on how you can get python to work on their servers. Hugo From bgailer at gmail.com Sun Aug 1 19:54:38 2010 From: bgailer at gmail.com (bob gailer) Date: Sun, 01 Aug 2010 13:54:38 -0400 Subject: [Tutor] web-based python? In-Reply-To: References: Message-ID: <4C55B4DE.5060406@gmail.com> On 8/1/2010 1:07 PM, Alex Hall wrote: > Hi all, > I have an IPowerWeb.com server, which claims to support Python. How > would I use this? For example, to start, how would I print html code > to the screen, or manage input from a form? Thanks. > > Another participant just raised a similar question! Unfortunately IPowerWeb.com does not "provide support for custom code or custom scripts. We assume that if a customer wants to use Perl, CGI, PHP, Python, ASP or any other scripting language, he/she has the necessary programming skills to manage his/her scripts." A starting place is the following script - let's call it "test.py". Upload it then invoke it. Try http://url-to-your-site/test.py #!/usr/bin/python print "Content-type: text/html" print print "" print "Hello World from Python" print "" print "Standard Hello World from a Python CGI Script" print " -- Bob Gailer 919-636-4239 Chapel Hill NC From evert.rol at gmail.com Sun Aug 1 20:09:07 2010 From: evert.rol at gmail.com (Evert Rol) Date: Sun, 1 Aug 2010 20:09:07 +0200 Subject: [Tutor] Help with Import Error problems In-Reply-To: References: Message-ID: <7DBDABF6-E5FD-4B86-99C6-C153A31CF2DB@gmail.com> > I got it back working. But it was with some stroke of luck. And I dont know the explanation. > > I installed the latest source of GEOS (as suggested by someone from the gdal channel). Then i tried the script. It gave me a different import error. > > ImportError: libgeos-3.3.0.so: cannot open shared object file: No such file or directory > > I uninstalled the thing. And then tried the script again and it worked. :| I answered some of your questions below. Again, thanks. Sounds like a library mess-up. System thing, definitely not a Python thing. Installing the latest source was a bit of an odd suggestion, if you got things working earlier. But it's good it's working now. Just be careful that it doesn't come back to bite you when you install more things. Few other things below, after the break: > For a quick check, try the following from the command line: > $> ldd /usr/lib/libspatialite.so.2 > > The command line returns the following lines: > > linux-vdso.so.1 => (0x00007fff6edff000) > libsqlite3.so.0 => /usr/lib/libsqlite3.so.0 (0x00007f793015c000) > libgeos_c.so.1 => /usr/local/lib/libgeos_c.so.1 (0x00007f792ff4f000) > libgeos-3.2.2.so => /usr/lib/libgeos-3.2.2.so (0x00007f792fbe8000) > libproj.so.0 => /usr/lib/libproj.so.0 (0x00007f792f9a6000) > libm.so.6 => /lib/libm.so.6 (0x00007f792f723000) > libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00007f792f40e000) > libpthread.so.0 => /lib/libpthread.so.0 (0x00007f792f1f1000) > libdl.so.2 => /lib/libdl.so.2 (0x00007f792efed000) > libc.so.6 => /lib/libc.so.6 (0x00007f792ec69000) > libgeos.so.2 => /usr/local/lib/libgeos.so.2 (0x00007f792e964000) > libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x00007f792e74d000) > /lib64/ld-linux-x86-64.so.2 (0x00007f7930688000) > > I dont know what to make of it. It's the pointers to the libgeos libraries that are interesting. Which shows that one libgeos lives in /usr/lib, while the other one can be found in /usr/local/lib. And libgeos_c also lives in /usr/local/lib. So it still feels a bit messy, having similarly named libraries in two different system directories, and you may run into some compatibility issues later on, in just a few specific functions or classes. May, because I've never used this software. You should scan through /usr/local/lib for more libgeos* libraries. If you find libgeos-3.2.2.so there as well, then probably that should actually be the preferred one (although then libspatialite.so.2 should also be in /usr/local/lib). Anyway, don't change it if it's working. See also below. > and see if it has any missing dependencies. If there's any missing (you can also post the output here if you'd like), see if you can that dependency somewhere on your system (the 'locate' command can help, or just good-old 'find'). If it's missing from libspatialite but you can find that library somewhere on your system (that would probably be the GEOS library then), it's your LD_LIBRARY_PATH that's likely different. > > Also, what linux distro are you using? Maybe you've been using the package manager overzealously, causing some essential packages to be modified or removed? > > > I'm on Ubuntu 10.04 (64 bit). I think it was from installing different GIS-related software (not all of which could be installed from the package manager). So perhaps some stuff automatically installed in /usr/lib (that could be software installed through the package manager), and then you used the usual ./configure; make; make install (or python setup.py install; or whatever), which most likely (hopefully, actually) would install things in /usr/local/lib. And somewhere along the way, a library got removed or replaced by a different version library, and things stopped working. What exactly happened is hard to tell, depending on how exactly you installed everything, and in which order. I hope this keeps working for you. Probably the folks on the gdal channel or related mailing lists could otherwise help you; but perhaps then tell them you have the geos & related libraries spread across /usr/lib and /usr/local/lib. Cheers, Evert From roybayot at gmail.com Sun Aug 1 20:20:47 2010 From: roybayot at gmail.com (Roy Khristopher Bayot) Date: Mon, 2 Aug 2010 02:20:47 +0800 Subject: [Tutor] Help with Import Error problems In-Reply-To: <7DBDABF6-E5FD-4B86-99C6-C153A31CF2DB@gmail.com> References: <7DBDABF6-E5FD-4B86-99C6-C153A31CF2DB@gmail.com> Message-ID: Evert, Thank you very much. I do hope it goes on working. :D Roy On Mon, Aug 2, 2010 at 2:09 AM, Evert Rol wrote: > > I got it back working. But it was with some stroke of luck. And I dont > know the explanation. > > > > I installed the latest source of GEOS (as suggested by someone from the > gdal channel). Then i tried the script. It gave me a different import error. > > > > ImportError: libgeos-3.3.0.so: cannot open shared object file: No such > file or directory > > > > I uninstalled the thing. And then tried the script again and it worked. > :| I answered some of your questions below. Again, thanks. > > Sounds like a library mess-up. System thing, definitely not a Python thing. > Installing the latest source was a bit of an odd suggestion, if you got > things working earlier. > But it's good it's working now. Just be careful that it doesn't come back > to bite you when you install more things. > > Few other things below, after the break: > > > > > > For a quick check, try the following from the command line: > > $> ldd /usr/lib/libspatialite.so.2 > > > > The command line returns the following lines: > > > > linux-vdso.so.1 => (0x00007fff6edff000) > > libsqlite3.so.0 => /usr/lib/libsqlite3.so.0 (0x00007f793015c000) > > libgeos_c.so.1 => /usr/local/lib/libgeos_c.so.1 > (0x00007f792ff4f000) > > libgeos-3.2.2.so => /usr/lib/libgeos-3.2.2.so (0x00007f792fbe8000) > > libproj.so.0 => /usr/lib/libproj.so.0 (0x00007f792f9a6000) > > libm.so.6 => /lib/libm.so.6 (0x00007f792f723000) > > libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00007f792f40e000) > > libpthread.so.0 => /lib/libpthread.so.0 (0x00007f792f1f1000) > > libdl.so.2 => /lib/libdl.so.2 (0x00007f792efed000) > > libc.so.6 => /lib/libc.so.6 (0x00007f792ec69000) > > libgeos.so.2 => /usr/local/lib/libgeos.so.2 (0x00007f792e964000) > > libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x00007f792e74d000) > > /lib64/ld-linux-x86-64.so.2 (0x00007f7930688000) > > > > I dont know what to make of it. > > It's the pointers to the libgeos libraries that are interesting. > Which shows that one libgeos lives in /usr/lib, while the other one can be > found in /usr/local/lib. And libgeos_c also lives in /usr/local/lib. > So it still feels a bit messy, having similarly named libraries in two > different system directories, and you may run into some compatibility issues > later on, in just a few specific functions or classes. May, because I've > never used this software. > You should scan through /usr/local/lib for more libgeos* libraries. If you > find libgeos-3.2.2.so there as well, then probably that should actually be > the preferred one (although then libspatialite.so.2 should also be in > /usr/local/lib). Anyway, don't change it if it's working. > See also below. > > > and see if it has any missing dependencies. If there's any missing (you > can also post the output here if you'd like), see if you can that dependency > somewhere on your system (the 'locate' command can help, or just good-old > 'find'). If it's missing from libspatialite but you can find that library > somewhere on your system (that would probably be the GEOS library then), > it's your LD_LIBRARY_PATH that's likely different. > > > > Also, what linux distro are you using? Maybe you've been using the > package manager overzealously, causing some essential packages to be > modified or removed? > > > > > > I'm on Ubuntu 10.04 (64 bit). I think it was from installing different > GIS-related software (not all of which could be installed from the package > manager). > > So perhaps some stuff automatically installed in /usr/lib (that could be > software installed through the package manager), and then you used the usual > ./configure; make; make install (or python setup.py install; or whatever), > which most likely (hopefully, actually) would install things in > /usr/local/lib. > And somewhere along the way, a library got removed or replaced by a > different version library, and things stopped working. > What exactly happened is hard to tell, depending on how exactly you > installed everything, and in which order. > > I hope this keeps working for you. Probably the folks on the gdal channel > or related mailing lists could otherwise help you; but perhaps then tell > them you have the geos & related libraries spread across /usr/lib and > /usr/local/lib. > > Cheers, > > Evert > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Sun Aug 1 20:28:42 2010 From: mehgcap at gmail.com (Alex Hall) Date: Sun, 1 Aug 2010 14:28:42 -0400 Subject: [Tutor] web-based python? In-Reply-To: <4C55B4DE.5060406@gmail.com> References: <4C55B4DE.5060406@gmail.com> Message-ID: On 8/1/10, bob gailer wrote: > On 8/1/2010 1:07 PM, Alex Hall wrote: >> Hi all, >> I have an IPowerWeb.com server, which claims to support Python. How >> would I use this? For example, to start, how would I print html code >> to the screen, or manage input from a form? Thanks. > Another participant just raised a similar question! > > Unfortunately IPowerWeb.com does not "provide support for custom code or > custom scripts. We assume that if a customer wants to use Perl, CGI, > PHP, Python, ASP or any other scripting language, he/she has the > necessary programming skills to manage his/her scripts." Sure, but django would be quite helpful. I want to do more than just print, the point is to be able to handle form input, resize/position images, all that. Still, it is good to not have to go through the hastle of getting a straight answer from an iPowerWeb tech support person. Last time I asked them about my htaccess file they deleted it! > > A starting place is the following script - let's call it "test.py". > Upload it then invoke it. Try http://url-to-your-site/test.py > > #!/usr/bin/python Is this line necessary? I ask because, on Windows, it is ignored, and I do not know the path to the server's Python interpreter even if it is required. > print "Content-type: text/html" > print > print "" > print "Hello World from Python" > print "" > print "Standard Hello World from a Python CGI Script" > print " Thanks. I assume all built-in functions will work. Would I be able to upload and use packages? > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From rdmoores at gmail.com Sun Aug 1 20:29:39 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 1 Aug 2010 11:29:39 -0700 Subject: [Tutor] How to get script to detect whether a file exists? Message-ID: is a work in progress. If I could get the script to tell whether or not the pickle files already existed, I could radically revise it (yeah, functions and all :) ). So how to find if a file exists? Vista, Python 3.1 Thanks, Dick Moores From python at bdurham.com Sun Aug 1 20:33:30 2010 From: python at bdurham.com (python at bdurham.com) Date: Sun, 01 Aug 2010 14:33:30 -0400 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: References: Message-ID: <1280687610.11953.1387782947@webmail.messagingengine.com> Richard, Look at the os.path.isfile function. Malcolm From hugo.yoshi at gmail.com Sun Aug 1 20:39:00 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 1 Aug 2010 20:39:00 +0200 Subject: [Tutor] web-based python? In-Reply-To: References: <4C55B4DE.5060406@gmail.com> Message-ID: On Sun, Aug 1, 2010 at 8:28 PM, Alex Hall wrote: > > Sure, but django would be quite helpful. I want to do more than just > print, the point is to be able to handle form input, resize/position > images, all that. Still, it is good to not have to go through the > hastle of getting a straight answer from an iPowerWeb tech support > person. Last time I asked them about my htaccess file they deleted it! IIRC Some frameworks can work through CGI. Not django, I believe, at least not officially. But it's worth googling around, there might be some custom solutions. > Is this line necessary? I ask because, on Windows, it is ignored, and > I do not know the path to the server's Python interpreter even if it > is required. including it can never hurt. Linux systems sometimes need it. If you replace /usr/bin/python with /usr/bin/env python, env will find the python interpreter for you (assuming env is set up). > Thanks. I assume all built-in functions will work. Would I be able to > upload and use packages? Sure, just put them in your path and you're good to go. Maybe put a .htaccess so that it can't be accessed through http. Hugo From pine508 at hotmail.com Sun Aug 1 20:56:47 2010 From: pine508 at hotmail.com (Che M) Date: Sun, 1 Aug 2010 14:56:47 -0400 Subject: [Tutor] web-based python? In-Reply-To: References: , , Message-ID: > > There is a myriad of python web development frameworks. Here's a link > > with a ton of info: > > > > http://wiki.python.org/moin/WebFrameworks > I had looked into Django before. What is confusing me is that it > sounds like it is meant to be run on the server directly. I do not > have direct access to my server, I just rent space on it and can > login. Maybe I am missing something, but how would I get Django onto > my server if I do not have the physical box available to me? For a long time I have hoped for a "Python web apps for absolute beginners" tutorial that doesn't assume any knowledge. For a beginner, it is not even clear what a "web frameworks" is let alone which one he/she should start with or if it is even needed. I just checked Alan Gauld's Learning to Program and was disappointed to see the section on writing web apps hasn't been done yet, since all the other tutorial material is so good (I understand that it is a lot of work to write these, though, and greatly appreciate all you have already done). Brainstorming what a good soup-to-nuts tutorial for Python web apps might include... - What the the various kinds of web apps one can make are and (very) roughly how much work each entails. In other words, there is a difference between writing an online newspaper vs. a web based GUI app. - Whether it matters if you develop on Windows, Linux, or Mac. - The easiest possible "Hello, World!" (just text) in a web browser. - How much of other languages (XHTML, CSS, Javascript, etc.) you need to know. - What you need to understand about servers and how to communicate with them. - How you can get more than just text on a web app, that is, widgets, and therefore what are currently the options for that (learning javascript and whatever widget toolkits are out there for that; qooxdoo; Pyjamas; others). - Whether you could use Pyjamas to make your code work as both a web app and a desktop app. - How you can develop your web app on your own computer and when you need to test it actually on the web. - What to consider when choosing a way to host your app online. - How to get your Python code onto that server, as well as whatever other code (like Django) there too. (Alex's question) - Why starting with a MVC pattern may be the best way to go for a web app. - What you need to consider to make your web app work the same on most browsers. - Scalability issues, speed issues, Security issues, cost issues; etc. - What databases to use and why - Issues concerning whether your app can be used by iPhones and other smart phones. - Opening your code to contribution; monetizing your service - Probably lots of other stuff I don't even know about. I understand much of this is about web apps generally and is not germane only to Python, but it would be good if a Python tutorial at least pointed toward this information, since for many beginners, the entry portal to anything is through Python. To just refer someone to Django when they don't know the first thing about web apps is, I think, off-putting. Che -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Sun Aug 1 21:28:49 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 1 Aug 2010 12:28:49 -0700 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: <1280687610.11953.1387782947@webmail.messagingengine.com> References: <1280687610.11953.1387782947@webmail.messagingengine.com> Message-ID: On Sun, Aug 1, 2010 at 11:33, wrote: > Richard, > > Look at the os.path.isfile function. > > Malcolm Thanks, Malcolm. That makes a tremendous difference. If anyone's curious, they see what use I've made of os.path.isfile(path): Dick > From jmacfiggen at gmail.com Sun Aug 1 22:26:24 2010 From: jmacfiggen at gmail.com (Jason MacFiggen) Date: Sun, 1 Aug 2010 13:26:24 -0700 Subject: [Tutor] sys.exit help Message-ID: I was wondering how can I change sys.exit so if you use command line to run the program. it prompts a message asking if the user wants to exit instead of automatically just exiting? import random import sys my_hp = 50 mo_hp = 50 menu1 = """ Menu Selections: 1 - Attack 2 - Defend 3 - Help 4 - Exit """ print menu1 while True: my_dmg = random.randrange(1, 20) mo_dmg = random.randrange(1, 20) choice = input ("\nEnter your selection. ") choice = float(choice) print if choice == 1: mo_hp = mo_hp - my_dmg if mo_hp <= 0: print "Iris is at 0 Hit Points!\nYOU HAVE SLAIN IRIS!" sys.exit(0) elif mo_hp > 0: print "-----------------------------------------------------------------" print "Iris is at %s Hit Points\nYou did %s damage\n" % (mo_hp, my_dmg) my_hp = my_hp - mo_dmg if my_hp <= 0: print "Your Hit Points are 0!\nYOU HAVE BEEN SLAIN BY Iris!" sys.exit(0) elif my_hp > 0: print name,"was attacked by Iris for %s damage!\nMy Hit Points are %s" % (mo_dmg, my_hp) print "-----------------------------------------------------------------" else: print menu1 elif choice == 2: mo_hp = mo_hp - my_dmg / 2 if mo_hp <= 0: print "The Lich King is at 0 Hit Points!\nYOU HAVE SLAIN IRIS!" sys.exit(0) elif mo_hp > 0: print "-----------------------------------------------------------------" print "The Lich King is at %s Hit Points\nYou did %s damage\n" % (mo_hp, my_dmg) my_hp = my_hp - mo_dmg / 2 if my_hp <= 0: print "Your Hit Points are 0!\nYOU HAVE BEEN SLAIN BY IRIS!" sys.exit(0) elif my_hp > 0: print name,"was attacked by the Iris for %s damage!\nMy Hit Points are %s" % (mo_dmg, my_hp) print "-----------------------------------------------------------------" else: print menu1 elif choice == 3: print """ ------------------------------------------------------------- Attack = Attack for 100% of damage. Defending = Attack for 50% of damage and endure 50% of damage. ------------------------------------------------------------- """ elif choice == 4: sys.exit(0) -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Sun Aug 1 22:35:16 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 1 Aug 2010 22:35:16 +0200 Subject: [Tutor] sys.exit help In-Reply-To: References: Message-ID: On Sun, Aug 1, 2010 at 10:26 PM, Jason MacFiggen wrote: > I was wondering how can I change sys.exit so if you use command line to run > the program. it prompts a message asking if the user wants to exit instead > of automatically just exiting? You can't change sys.exit, but you can build something yourself. You have raw_input to ask the user something, and an if statement to make a decision based on that input. You should be able to figure something out. One other point: if you just want to exit, you don't have to call sys.exit really, you can just let the script end naturally (break out of the while loop and it'll end by itself). sys.exit is only really useful if you want a special exit status. Hugo From steve at pearwood.info Sun Aug 1 22:37:18 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 2 Aug 2010 06:37:18 +1000 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: References: Message-ID: <201008020637.19243.steve@pearwood.info> On Mon, 2 Aug 2010 04:29:39 am Richard D. Moores wrote: > is a work in progress. If I > could get the script to tell whether or not the pickle files already > existed, I could radically revise it (yeah, functions and all :) ). > So how to find if a file exists? The lazy way is with the os.file.exists() function: if os.file.exists(filename): f = open(filename) Of course, the lazy way usually ends up needing more work to fix the bugs it introduces. This is 2010, you're running under a multi-process operating system where a hundred other programs are sharing time with you, possibly even a multi-user system with other people reading and writing files. So the above is wrong, because there's no guarantee that just because the file exists when you call os.file.exists it will still be there a millisecond later when you call open. So the right way is to ignore os.file.exists and just open the file, catching errors: try: f = open(filename) except IOError: do_something_when_the_file_isnt_there() else: do_something_with_file(f) -- Steven D'Aprano From evert.rol at gmail.com Sun Aug 1 22:38:10 2010 From: evert.rol at gmail.com (Evert Rol) Date: Sun, 1 Aug 2010 22:38:10 +0200 Subject: [Tutor] sys.exit help In-Reply-To: References: Message-ID: <9D8113E9-9DF2-4E30-B62C-BF89A5155C63@gmail.com> > I was wondering how can I change sys.exit so if you use command line to run the program. it prompts a message asking if the user wants to exit instead of automatically just exiting? Just write a wrapper exit() function around sys.exit that does that. You don't want to change the sys.exit function to behave differently; it's purpose is simply to exit the program with a return value. > import random > import sys > my_hp = 50 > mo_hp = 50 > menu1 = """ > Menu Selections: > 1 - Attack > 2 - Defend > 3 - Help > 4 - Exit > """ > print menu1 > while True: > my_dmg = random.randrange(1, 20) > mo_dmg = random.randrange(1, 20) > > choice = input ("\nEnter your selection. ") > choice = float(choice) > print > if choice == 1: > mo_hp = mo_hp - my_dmg > if mo_hp <= 0: > print "Iris is at 0 Hit Points!\nYOU HAVE SLAIN IRIS!" > sys.exit(0) > elif mo_hp > 0: > print "-----------------------------------------------------------------" > print "Iris is at %s Hit Points\nYou did %s damage\n" % (mo_hp, my_dmg) > my_hp = my_hp - mo_dmg > if my_hp <= 0: > print "Your Hit Points are 0!\nYOU HAVE BEEN SLAIN BY Iris!" > sys.exit(0) > elif my_hp > 0: > print name,"was attacked by Iris for %s damage!\nMy Hit Points are %s" % (mo_dmg, my_hp) > print "-----------------------------------------------------------------" > else: > print menu1 > > > elif choice == 2: > mo_hp = mo_hp - my_dmg / 2 > if mo_hp <= 0: > print "The Lich King is at 0 Hit Points!\nYOU HAVE SLAIN IRIS!" > sys.exit(0) > elif mo_hp > 0: > print "-----------------------------------------------------------------" > print "The Lich King is at %s Hit Points\nYou did %s damage\n" % (mo_hp, my_dmg) > my_hp = my_hp - mo_dmg / 2 > if my_hp <= 0: > print "Your Hit Points are 0!\nYOU HAVE BEEN SLAIN BY IRIS!" > sys.exit(0) > elif my_hp > 0: > print name,"was attacked by the Iris for %s damage!\nMy Hit Points are %s" % (mo_dmg, my_hp) > print "-----------------------------------------------------------------" > else: > print menu1 > > elif choice == 3: > print """ > ------------------------------------------------------------- > Attack = Attack for 100% of damage. > Defending = Attack for 50% of damage and endure 50% of damage. > ------------------------------------------------------------- > """ > elif choice == 4: > sys.exit(0) > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From steve at pearwood.info Sun Aug 1 22:40:20 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 2 Aug 2010 06:40:20 +1000 Subject: [Tutor] sys.exit help In-Reply-To: References: Message-ID: <201008020640.21126.steve@pearwood.info> On Mon, 2 Aug 2010 06:26:24 am Jason MacFiggen wrote: > I was wondering how can I change sys.exit so if you use command line > to run the program. it prompts a message asking if the user wants to > exit instead of automatically just exiting? Don't do that. Leave sys.exit alone, write your own quit() function that asks the user and then calls sys.exit if they say yes. -- Steven D'Aprano From dsarmientos at gmail.com Sun Aug 1 23:41:11 2010 From: dsarmientos at gmail.com (Daniel Sarmiento) Date: Sun, 1 Aug 2010 16:41:11 -0500 Subject: [Tutor] Tutor Digest, Vol 78, Issue 8 In-Reply-To: References: Message-ID: > Date: Sun, 1 Aug 2010 12:28:49 -0700 > From: "Richard D. Moores" > To: python at bdurham.com > Cc: tutor at python.org > Subject: Re: [Tutor] How to get script to detect whether a file > exists? > Message-ID: > > Content-Type: text/plain; charset=UTF-8 > > On Sun, Aug 1, 2010 at 11:33, wrote: > > Richard, > > > > Look at the os.path.isfile function. > > > > Malcolm > > Thanks, Malcolm. That makes a tremendous difference. > > If anyone's curious, they see what use I've made of > os.path.isfile(path): > > Dick > > > > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 78, Issue 8 > ************************************ > I don't know if I am right, but I remember reading it is better to try to open the files and see if an exception is raised than checking if the files exist. In that way one can avoid TOCTTOU bugs ( http://en.wikipedia.org/wiki/Time-of-check-to-time-of-use ) Without knowing what your code does, I think it will be something like: try: F_unused = open(path1, 'rb') F_used = open(path2, 'rb') except IOError: print("no") ..... else: unused_ints = pickle.load(F_unused) ...... HTH Daniel Sarmiento S. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dsarmientos at gmail.com Sun Aug 1 23:44:05 2010 From: dsarmientos at gmail.com (Daniel Sarmiento) Date: Sun, 1 Aug 2010 16:44:05 -0500 Subject: [Tutor] How to get script to detect whether a file exists? Message-ID: > Date: Sun, 1 Aug 2010 12:28:49 -0700 > From: "Richard D. Moores" > To: python at bdurham.com > Cc: tutor at python.org > Subject: Re: [Tutor] How to get script to detect whether a file > exists? > Message-ID: > > Content-Type: text/plain; charset=UTF-8 > > On Sun, Aug 1, 2010 at 11:33, wrote: > > Richard, > > > > Look at the os.path.isfile function. > > > > Malcolm > > Thanks, Malcolm. That makes a tremendous difference. > > If anyone's curious, they see what use I've made of > os.path.isfile(path): > > Dick > > > > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > I don't know if I am right, but I remember reading it is better to try to open the files and see if an exception is raised than checking if the files exist. In that way one can avoid TOCTTOU bugs ( http://en.wikipedia.org/wiki/Time-of-check-to-time-of-use ) Without knowing what your code does, I think it will be something like: try: F_unused = open(path1, 'rb') F_used = open(path2, 'rb') except IOError: print("no") ..... else: unused_ints = pickle.load(F_unused) ...... HTH Daniel Sarmiento S. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Sun Aug 1 23:55:49 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 1 Aug 2010 14:55:49 -0700 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: <201008020637.19243.steve@pearwood.info> References: <201008020637.19243.steve@pearwood.info> Message-ID: On Sun, Aug 1, 2010 at 13:37, Steven D'Aprano wrote: > On Mon, 2 Aug 2010 04:29:39 am Richard D. Moores wrote: >> is a work in progress. If I >> could get the script to tell whether or not the pickle files already >> existed, I could radically revise it (yeah, functions and all :) ). >> So how to find if a file exists? > > The lazy way is with the os.file.exists() function: > > if os.file.exists(filename): > ? ?f = open(filename) > > > Of course, the lazy way usually ends up needing more work to fix the > bugs it introduces. This is 2010, you're running under a multi-process > operating system where a hundred other programs are sharing time with > you, possibly even a multi-user system with other people reading and > writing files. So the above is wrong, because there's no guarantee that > just because the file exists when you call os.file.exists it will still > be there a millisecond later when you call open. So the right way is to > ignore os.file.exists and just open the file, catching errors: > > try: > ? ?f = open(filename) > except IOError: > ? ?do_something_when_the_file_isnt_there() > else: > ? ?do_something_with_file(f) OK, but there are actually 2 files that need to be checked. If either one or both are missing I need to create/recreate both. How do I do that your way? I've forgotten the little I knew about catching errors. My lazy way has it now as "if not (os.path.isfile(path1) and os.path.isfile(path2)):" Thanks, Dick From rdmoores at gmail.com Mon Aug 2 00:53:17 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 1 Aug 2010 15:53:17 -0700 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: References: Message-ID: On Sun, Aug 1, 2010 at 15:00, Richard D. Moores wrote: > On Sun, Aug 1, 2010 at 14:44, Daniel Sarmiento wrote: >> >> Without knowing what your code does, I think it will be something like: >> >> try: >> ??? F_unused = open(path1, 'rb') >> ??? F_used = open(path2, 'rb') >> except IOError: >> ??? print("no") >> ??? ..... >> else: >> ??? unused_ints = pickle.load(F_unused) OK. Did that. And it works: . Now what? Am I done? Or should I break it up into a bunch of functions, each one doing just one thing? Dick From hugo.yoshi at gmail.com Mon Aug 2 01:01:47 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Mon, 2 Aug 2010 01:01:47 +0200 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: References: Message-ID: On Mon, Aug 2, 2010 at 12:53 AM, Richard D. Moores wrote: > On Sun, Aug 1, 2010 at 15:00, Richard D. Moores wrote: >> On Sun, Aug 1, 2010 at 14:44, Daniel Sarmiento wrote: >>> > >>> Without knowing what your code does, I think it will be something like: >>> >>> try: >>> ??? F_unused = open(path1, 'rb') >>> ??? F_used = open(path2, 'rb') >>> except IOError: >>> ??? print("no") >>> ??? ..... >>> else: >>> ??? unused_ints = pickle.load(F_unused) > > OK. Did that. And it works: . > Now what? Am I done? Or should I break it up into a bunch of > functions, each one doing just one thing? > For a script this short, you could probably get away with just leaving it here. However, I mean that in a "if you're really lazy, I suppose you could" way. It will become easier to understand if you break it up, and that is good for your future sanity. So it's not required, but it definitely can't hurt, and if this script gets any larger you will be glad you broke it up. Hugo From smokefloat at gmail.com Mon Aug 2 01:24:51 2010 From: smokefloat at gmail.com (David Hutto) Date: Sun, 1 Aug 2010 19:24:51 -0400 Subject: [Tutor] Where to start with Unit Testing In-Reply-To: References: Message-ID: On Sun, Aug 1, 2010 at 12:18 PM, Che M wrote: > > >> Do any of you have any feedback, strategies and best practices >> related to unit testing within Python. This is a relatively new topic >> for me. I was thinking of starting with reading the documentation >> associate with the unittest module. > > The idea of unit testing/test driven development has remained > foreign to me throughout my time trying to learn Python--by choice. > I want to make desktop GUI applications and I don't use MVC, so > the idea of writing tests strikes me as far more work--and a major > delayer of getting to an application that actually does something-- > than simply using the software myself and noting problems.? It > sounds like TDD is probably the most proper way to go about things, > but, in the interest of getting something out of Python to warrant the > time I've put into it, I favor a "good enough" approach for now. Writers just call this a rough draft. Perfection is in the revisions that come after a little thought. > > > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From ehamiter at gmail.com Mon Aug 2 01:38:35 2010 From: ehamiter at gmail.com (Eric Hamiter) Date: Sun, 1 Aug 2010 18:38:35 -0500 Subject: [Tutor] web-based python? In-Reply-To: References: Message-ID: On Sun, Aug 1, 2010 at 1:56 PM, Che M wrote: > For a long time I have hoped for a "Python web apps for absolute beginners" > tutorial that doesn't assume any knowledge. For a beginner, it is not even > clear what a "web frameworks" is let alone which one he/she should start > with or if it is even needed. > > I understand much of this is about web apps generally and is not germane > only to Python, but it would be good if a Python tutorial at least pointed > toward > this information, since for many beginners, the entry portal to anything is > through > Python. To just refer someone to Django when they don't know the first > thing about > web apps is, I think, off-putting. > > Che > > Che, my sentinments exactly. I'm looking for something similar. Eric -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Mon Aug 2 01:46:52 2010 From: smokefloat at gmail.com (David Hutto) Date: Sun, 1 Aug 2010 19:46:52 -0400 Subject: [Tutor] web-based python? In-Reply-To: References: Message-ID: On Sun, Aug 1, 2010 at 7:38 PM, Eric Hamiter wrote: > On Sun, Aug 1, 2010 at 1:56 PM, Che M wrote: >> >> For a long time I have hoped for a "Python web apps for absolute >> beginners" >> tutorial that doesn't assume any knowledge.? For a beginner, it is not >> even >> clear what a "web frameworks" is let alone which one he/she should start >> with or if it is even needed. >> >> I understand much of this is about web apps generally and is not germane >> only to Python, but it would be good if a Python tutorial at least pointed >> toward >> this information, since for many beginners, the entry portal to anything >> is through >> Python.? To just refer someone to Django when they don't know the first >> thing about >> web apps is, I think, off-putting. I think just using the term web app instead of interactive website is confusing, unless by web app(and this is the way I might, incorrectly, use the term) you mean a desktop app that works only with an internet connection, and communication with a nonlocal server. >> >> Che >> > Che, my sentinments exactly. I'm looking for something similar. > > Eric > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at btinternet.com Mon Aug 2 02:10:54 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 2 Aug 2010 01:10:54 +0100 Subject: [Tutor] web-based python? References: , , Message-ID: "Che M" wrote > For a long time I have hoped for a "Python web apps for absolute > beginners" > .... I just checked Alan Gauld's Learning to Program and was > disappointed > to see the section on writing web apps hasn't been done yet, I started on the client side topic but then Python 3 came out and I've been diverted rewriting everything for that. I'm hoping to get the v3 tutorial up to the same place as the v2 one by the end of the year - then maybe I'll get round to finishing the web programming section. However I will only be covering basic CGI scripting, I don't intend to attemp any of the Frameworks. Mainly becauase moast of them have perfectly good tutorials already once you understand the bare bones of CGI. > - What the the various kinds of web apps one can make are and (very) > roughly > how much work each entails. In other words, there is a difference > between > writing an online newspaper vs. a web based GUI app. Actually web apps are all pretty similar. They consist of three basic parts (maybe 4): 1) A mechanism for mapping a URL to a Python function or method. 2) A mechanism for generating HTML with embedded data values 3) A data storage mechanism 4) Some client code for a more dynamic feel What they look like is just down to HTML creativity. But they all start out as an HTML web page with some kind of form that captures data. When you submit the form yyou send some data to the server which interprets it and generates a new HTML page back again. There might be some flash graphics or some Javascript doing clever display stuff to make tings more dynamic, but basically all web apps work by capturing some data and sending it to a server which generates a new page in response. In fact designing a web app is a lot like designing an old fashioned mainframe terminal application. They also worked on a page view basis albeit a 24linex80character display page... > - Whether it matters if you develop on Windows, Linux, or Mac. The whole point of the web is that it doersn'ty care. You can write platform specific web code - especially on Microsoft platforms - but all that does is limits your audience. There is no good reason to do it. > - The easiest possible "Hello, World!" (just text) in a web browser.

Hello, World! That's it as a one liner. If you want it as a CGI program in Python its only slightly longer and the CGI documentation shows you how... > - How much of other languages (XHTML, CSS, Javascript, etc.) you > need to know. That all depends on how fancy you want the presentation to be. For professional standard you will definitely need all 3. For basic stuff HTML is all you really need. > - What you need to understand about servers and how to communicate > with them. Not a lot if you use a Framework, but debugging problems is easier if you understand whats actually happening. > - How you can get more than just text on a web app, that is, > widgets, and > therefore what are currently the options for that (learning > javascript and whatever > widget toolkits are out there for that; qooxdoo; Pyjamas; others). This is where it gets very complicated. There are lots of different ways of doing widgets (in out company we have a "standard" that defines 4 levels, or kinds, of widget you can build and still be complant with the company architecture! The simplest is an IFrame fragment) > - Whether you could use Pyjamas to make your code work > as both a web app and a desktop app. I've heard of pyjamas but not used it. The .NET framework has a similar concept but in my experience the results are usually not very good GUIs and not very good web apps... Its better to design for one or the other and do a good job for that one. > - How you can develop your web app on your own computer and when you > need to test it actually on the web. Thats usually just a case of running a web server on your PC. There are many to choose from and Python even offers a couple in the standard library. > - What to consider when choosing a way to host your app online. > - How to get your Python code onto that server, as well as whatever > other > code (like Django) there too. (Alex's question) ftp is the usual way. > - Why starting with a MVC pattern may be the best way to go for a > web app. MVC is usually the best pattern for any UI centric app, whether desktop, client/server or web. It maximises reuse and clarifies the logic. > - What you need to consider to make your web app work the same > on most browsers. Stick to established standards and remember that by its nature the web does not give you fine control. So design the GUI in the knowledge that different browsers will do different things with it and that is their right - and that of your user. Then realise that this will invariably compromise the user experienve. So you then decide whether maximum reach or maximum user satisfaction is most important to you. > - Scalability issues, speed issues, Security issues, cost issues; > etc. Pretty much the same as for any server application. > - What databases to use and why Pretty much web independant. > - Issues concerning whether your app can be used by iPhones > and other smart phones. Yes, this is becoming a real issue. I've no real experience to offer on this one yet. > - Opening your code to contribution; monetizing your service Again not really web specific. > - Probably lots of other stuff I don't even know about. Probably :-) > I understand much of this is about web apps generally > and is not germane only to Python, Thats true of any general programming paradigm like GUI or database programming. There just happens to be some Python libraries stuck on top thats all. > but it would be good if a Python tutorial at least pointed toward > this information, since for many beginners, the entry portal to > anything is through Python. Wikipedia is your friend and the partial topic that I did on web programming did include some of the basic stuff with lots of links to Wikipedia articles. You can find it on the v2 tutor under writing web clients, but its very draft and incomplete... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Aug 2 02:20:51 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 2 Aug 2010 01:20:51 +0100 Subject: [Tutor] sys.exit help References: Message-ID: "Jason MacFiggen" wrote >I was wondering how can I change sys.exit so if you use command line >to run > the program. it prompts a message asking if the user wants to exit > instead > of automatically just exiting? Don't just use sys.exit use a try/except SystemExit... >>> import sys >>> try: ... sys.exit() ... except SystemExit: ... print 'caught exit' ... raise ... caught exit However thats usually the wrong way to do it. Better to have your program exit naturally and have the control logic in the code control when it finishes. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rdmoores at gmail.com Mon Aug 2 02:26:41 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 1 Aug 2010 17:26:41 -0700 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: References: Message-ID: On Sun, Aug 1, 2010 at 16:01, Hugo Arts wrote: > On Mon, Aug 2, 2010 at 12:53 AM, Richard D. Moores wrote: >> On Sun, Aug 1, 2010 at 15:00, Richard D. Moores wrote: >>> On Sun, Aug 1, 2010 at 14:44, Daniel Sarmiento wrote: >>>> >> >>>> Without knowing what your code does, I think it will be something like: >>>> >>>> try: >>>> ??? F_unused = open(path1, 'rb') >>>> ??? F_used = open(path2, 'rb') >>>> except IOError: >>>> ??? print("no") >>>> ??? ..... >>>> else: >>>> ??? unused_ints = pickle.load(F_unused) >> >> OK. Did that. And it works: . >> Now what? Am I done? Or should I break it up into a bunch of >> functions, each one doing just one thing? >> > > For a script this short, you could probably get away with just leaving > it here. However, I mean that in a "if you're really lazy, I suppose > you could" way. It will become easier to understand if you break it > up, and that is good for your future sanity. So it's not required, but > it definitely can't hurt, and if this script gets any larger you will > be glad you broke it up. Well, I'd like to try. Could you give me, say, an outline of what might be a good way? Actually, before I changed to the error catching, I tried to break it up into a bunch of small functions. But they got all tangled up with some functions returning the calling of others, that I couldn't get them straightened out. Also, some were required to have such a long string of arguments I couldn't get them all on one line. Dick > > Hugo > From hugo.yoshi at gmail.com Mon Aug 2 02:38:12 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Mon, 2 Aug 2010 02:38:12 +0200 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: References: Message-ID: On Mon, Aug 2, 2010 at 2:26 AM, Richard D. Moores wrote: > > Well, I'd like to try. Could you give me, say, an outline of what > might be a good way? Actually, before I changed to the error catching, > I tried to break it up into a bunch of small functions. But they got > all tangled up with some functions returning the calling of others, > that I couldn't get them straightened out. Also, some were required to > have such a long string of arguments I couldn't get them all on one > line. > For starters, the code recreating both your files is almost exactly the same, so you can easily turn that into one function and call it twice. I see two necessary arguments, the path and the data you're dumping in. See if you can work that one out. The file saving code at the end is another one that can be easily made into one function and called twice. If you get those two pieces done you should be in good shape. Hugo From pine508 at hotmail.com Mon Aug 2 03:11:23 2010 From: pine508 at hotmail.com (Che M) Date: Sun, 1 Aug 2010 21:11:23 -0400 Subject: [Tutor] Where to start with Unit Testing In-Reply-To: References: , , Message-ID: > > The idea of unit testing/test driven development has remained > > foreign to me throughout my time trying to learn Python--by choice. > > I want to make desktop GUI applications and I don't use MVC, so > > the idea of writing tests strikes me as far more work--and a major > > delayer of getting to an application that actually does something-- > > than simply using the software myself and noting problems. It > > sounds like TDD is probably the most proper way to go about things, > > but, in the interest of getting something out of Python to warrant the > > time I've put into it, I favor a "good enough" approach for now. > > Writers just call this a rough draft. Perfection is in the revisions > that come after a little thought. Well, I don't see what I'm doing as a rough draft, as I am attempting to hone it to "perfection" (that is, a working app)--just without unit testing. A different analogy comes to my mind; I once saw two different sets of people analyze data. One did it "by hand": visually inspecting thousands of signals herself and typing Y or N to accept or reject each signal. The other did it with an automated system that accepted or rejected signals based on fuzzy logic. In an important interpretation, the automated system was far better, and yet the first scientist was done with her analysis and accepted for publication before the second team even had the bugs worked out of the automated system! Yes, I think the slow-but-more-proper team did the more correct thing, but there is something to be said for "good enough", too (it works for evolution, for example). -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Mon Aug 2 03:31:46 2010 From: smokefloat at gmail.com (David Hutto) Date: Sun, 1 Aug 2010 21:31:46 -0400 Subject: [Tutor] Where to start with Unit Testing In-Reply-To: References: Message-ID: On Sun, Aug 1, 2010 at 9:11 PM, Che M wrote: > > >> > The idea of unit testing/test driven development has remained >> > foreign to me throughout my time trying to learn Python--by choice. >> > I want to make desktop GUI applications and I don't use MVC, so >> > the idea of writing tests strikes me as far more work--and a major >> > delayer of getting to an application that actually does something-- >> > than simply using the software myself and noting problems.? It >> > sounds like TDD is probably the most proper way to go about things, >> > but, in the interest of getting something out of Python to warrant the >> > time I've put into it, I favor a "good enough" approach for now. >> >> Writers just call this a rough draft. Perfection is in the revisions >> that come after a little thought. > > Well, I don't see what I'm doing as a rough draft, as I am attempting > to hone it to "perfection" (that is, a working app)--just without unit > testing. Every time you try to perfect is a revision of your initial 'written' algorithm. From concept forward is your revisions. Notice that svn and cvs are called revisions. How quickly is a different story. To you, your writing and rewriting, but each rewrite is a revision of the initial concept. And as far as i can tell, if you want to be the unit test yourself, it's fine, but unit testing might be inappropriate for something like this. But basically unit testing would be a script that inputs the possible combinations of requests to the original script, which should be tested like chefs do soups-intermittently as you design it. So the tests are really what you put or type as input given directly to the script , right?. > > A different analogy comes to my mind; I once saw two different sets of > people analyze data.? One did it "by hand":? visually inspecting thousands > of signals herself and typing Y or N to accept or reject each signal.? The > other did it with an automated system that accepted or rejected signals > based on fuzzy logic. This depends on your need for control, do you need to manually accept, or can you just detect the signal, and let the program proceedl. Do you want the local nuclear plant to have their system throw an error, without a human response? In an important interpretation, the automated system > was far better, and yet the first scientist was done with her analysis and > accepted for publication before the second team even had the bugs worked > out of the automated system! Like you state below, the automated system used, evolved from manually designed systems, so automation is the easy way, but sometimes not the best, depending on the circumstance and priority level of the information being received. Yes, I think the slow-but-more-proper team > did the more correct thing, but there is something to be said for "good > enough", too (it works for evolution, for example). > > > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From smokefloat at gmail.com Mon Aug 2 03:39:24 2010 From: smokefloat at gmail.com (David Hutto) Date: Sun, 1 Aug 2010 21:39:24 -0400 Subject: [Tutor] Where to start with Unit Testing In-Reply-To: References: Message-ID: On Sun, Aug 1, 2010 at 9:31 PM, David Hutto wrote: > On Sun, Aug 1, 2010 at 9:11 PM, Che M wrote: >> >> >>> > The idea of unit testing/test driven development has remained >>> > foreign to me throughout my time trying to learn Python--by choice. >>> > I want to make desktop GUI applications and I don't use MVC, so >>> > the idea of writing tests strikes me as far more work--and a major >>> > delayer of getting to an application that actually does something-- >>> > than simply using the software myself and noting problems.? It >>> > sounds like TDD is probably the most proper way to go about things, >>> > but, in the interest of getting something out of Python to warrant the >>> > time I've put into it, I favor a "good enough" approach for now. >>> >>> Writers just call this a rough draft. Perfection is in the revisions >>> that come after a little thought. >> >> Well, I don't see what I'm doing as a rough draft, as I am attempting >> to hone it to "perfection" (that is, a working app)--just without unit >> testing. > > Every time you try to perfect is a revision of your initial 'written' > algorithm. From concept forward is your revisions. Notice that svn and > cvs are called revisions. How quickly is a different story. To you, > your writing and rewriting, but each rewrite is a revision of the > initial concept. And as far as i can tell, if you want to be the unit > test yourself, it's fine, but unit testing might be inappropriate for > something like this. But basically unit testing would be a script that > inputs the possible combinations of requests to the original script, > which should be tested like chefs do soups-intermittently as you > design it. So the tests are really what you put or type as input given > directly to the script , right?. > > > >> >> A different analogy comes to my mind; I once saw two different sets of >> people analyze data.? One did it "by hand":? visually inspecting thousands >> of signals herself and typing Y or N to accept or reject each signal.? The >> other did it with an automated system that accepted or rejected signals >> based on fuzzy logic. > > This depends on your need for control, do you need to manually accept, > or can you just detect the signal, and let the program proceedl. Do > you want the local nuclear plant to have their system throw an error, > without a human response? > > In an important interpretation, the automated system >> was far better, and yet the first scientist was done with her analysis and >> accepted for publication before the second team even had the bugs worked >> out of the automated system! > > Like you state below, the automated system used, evolved from manually > designed systems, so automation is the easy way, but sometimes not the > best, depending on the circumstance and priority level of the > information being received. > > Yes, I think the slow-but-more-proper team >> did the more correct thing, but there is something to be said for "good >> enough", too (it works for evolution, for example). > > >> >> >> >> >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > Disclaimer: I have no clue what unit testing is, nor have I had to use it yet. From smokefloat at gmail.com Mon Aug 2 03:42:10 2010 From: smokefloat at gmail.com (David Hutto) Date: Sun, 1 Aug 2010 21:42:10 -0400 Subject: [Tutor] Where to start with Unit Testing In-Reply-To: References: Message-ID: On Sun, Aug 1, 2010 at 9:39 PM, David Hutto wrote: > On Sun, Aug 1, 2010 at 9:31 PM, David Hutto wrote: >> On Sun, Aug 1, 2010 at 9:11 PM, Che M wrote: >>> >>> >>>> > The idea of unit testing/test driven development has remained >>>> > foreign to me throughout my time trying to learn Python--by choice. >>>> > I want to make desktop GUI applications and I don't use MVC, so >>>> > the idea of writing tests strikes me as far more work--and a major >>>> > delayer of getting to an application that actually does something-- >>>> > than simply using the software myself and noting problems.? It >>>> > sounds like TDD is probably the most proper way to go about things, >>>> > but, in the interest of getting something out of Python to warrant the >>>> > time I've put into it, I favor a "good enough" approach for now. >>>> >>>> Writers just call this a rough draft. Perfection is in the revisions >>>> that come after a little thought. >>> >>> Well, I don't see what I'm doing as a rough draft, as I am attempting >>> to hone it to "perfection" (that is, a working app)--just without unit >>> testing. >> >> Every time you try to perfect is a revision of your initial 'written' >> algorithm. From concept forward is your revisions. Notice that svn and >> cvs are called revisions. How quickly is a different story. To you, >> your writing and rewriting, but each rewrite is a revision of the >> initial concept. And as far as i can tell, if you want to be the unit >> test yourself, it's fine, but unit testing might be inappropriate for >> something like this. But basically unit testing would be a script that >> inputs the possible combinations of requests to the original script, >> which should be tested like chefs do soups-intermittently as you >> design it. So the tests are really what you put or type as input given >> directly to the script , right?. >> >> >> >>> >>> A different analogy comes to my mind; I once saw two different sets of >>> people analyze data.? One did it "by hand":? visually inspecting thousands >>> of signals herself and typing Y or N to accept or reject each signal.? The >>> other did it with an automated system that accepted or rejected signals >>> based on fuzzy logic. >> >> This depends on your need for control, do you need to manually accept, >> or can you just detect the signal, and let the program proceedl. Do >> you want the local nuclear plant to have their system throw an error, >> without a human response? >> >> In an important interpretation, the automated system >>> was far better, and yet the first scientist was done with her analysis and >>> accepted for publication before the second team even had the bugs worked >>> out of the automated system! >> >> Like you state below, the automated system used, evolved from manually >> designed systems, so automation is the easy way, but sometimes not the >> best, depending on the circumstance and priority level of the >> information being received. >> >> Yes, I think the slow-but-more-proper team >>> did the more correct thing, but there is something to be said for "good >>> enough", too (it works for evolution, for example). >> >> >>> >>> >>> >>> >>> _______________________________________________ >>> Tutor maillist ?- ?Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >> > > Disclaimer: I have no clue what unit testing is, nor have I had to use it yet. > But it would be a series of function instances from a module, right? Not to butt in on the OP. From huyslogic at gmail.com Mon Aug 2 04:13:14 2010 From: huyslogic at gmail.com (Huy Ton That) Date: Sun, 1 Aug 2010 22:13:14 -0400 Subject: [Tutor] Where to start with Unit Testing In-Reply-To: References: Message-ID: All these responses are incredible, I will go through them on my venture to bring unit testing under my belt. I have never done formal unit testing in my programming career, I've just gone through way of general debugging and utilizing version control such as Mercurial. On Sun, Aug 1, 2010 at 9:42 PM, David Hutto wrote: > On Sun, Aug 1, 2010 at 9:39 PM, David Hutto wrote: > > On Sun, Aug 1, 2010 at 9:31 PM, David Hutto > wrote: > >> On Sun, Aug 1, 2010 at 9:11 PM, Che M wrote: > >>> > >>> > >>>> > The idea of unit testing/test driven development has remained > >>>> > foreign to me throughout my time trying to learn Python--by choice. > >>>> > I want to make desktop GUI applications and I don't use MVC, so > >>>> > the idea of writing tests strikes me as far more work--and a major > >>>> > delayer of getting to an application that actually does something-- > >>>> > than simply using the software myself and noting problems. It > >>>> > sounds like TDD is probably the most proper way to go about things, > >>>> > but, in the interest of getting something out of Python to warrant > the > >>>> > time I've put into it, I favor a "good enough" approach for now. > >>>> > >>>> Writers just call this a rough draft. Perfection is in the revisions > >>>> that come after a little thought. > >>> > >>> Well, I don't see what I'm doing as a rough draft, as I am attempting > >>> to hone it to "perfection" (that is, a working app)--just without unit > >>> testing. > >> > >> Every time you try to perfect is a revision of your initial 'written' > >> algorithm. From concept forward is your revisions. Notice that svn and > >> cvs are called revisions. How quickly is a different story. To you, > >> your writing and rewriting, but each rewrite is a revision of the > >> initial concept. And as far as i can tell, if you want to be the unit > >> test yourself, it's fine, but unit testing might be inappropriate for > >> something like this. But basically unit testing would be a script that > >> inputs the possible combinations of requests to the original script, > >> which should be tested like chefs do soups-intermittently as you > >> design it. So the tests are really what you put or type as input given > >> directly to the script , right?. > >> > >> > >> > >>> > >>> A different analogy comes to my mind; I once saw two different sets of > >>> people analyze data. One did it "by hand": visually inspecting > thousands > >>> of signals herself and typing Y or N to accept or reject each signal. > The > >>> other did it with an automated system that accepted or rejected signals > >>> based on fuzzy logic. > >> > >> This depends on your need for control, do you need to manually accept, > >> or can you just detect the signal, and let the program proceedl. Do > >> you want the local nuclear plant to have their system throw an error, > >> without a human response? > >> > >> In an important interpretation, the automated system > >>> was far better, and yet the first scientist was done with her analysis > and > >>> accepted for publication before the second team even had the bugs > worked > >>> out of the automated system! > >> > >> Like you state below, the automated system used, evolved from manually > >> designed systems, so automation is the easy way, but sometimes not the > >> best, depending on the circumstance and priority level of the > >> information being received. > >> > >> Yes, I think the slow-but-more-proper team > >>> did the more correct thing, but there is something to be said for "good > >>> enough", too (it works for evolution, for example). > >> > >> > >>> > >>> > >>> > >>> > >>> _______________________________________________ > >>> Tutor maillist - Tutor at python.org > >>> To unsubscribe or change subscription options: > >>> http://mail.python.org/mailman/listinfo/tutor > >>> > >>> > >> > > > > Disclaimer: I have no clue what unit testing is, nor have I had to use it > yet. > > > > But it would be a series of function instances from a module, right? > Not to butt in on the OP. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From quasipedia at gmail.com Mon Aug 2 05:30:42 2010 From: quasipedia at gmail.com (Mac Ryan) Date: Mon, 02 Aug 2010 05:30:42 +0200 Subject: [Tutor] Where to start with Unit Testing In-Reply-To: References: , , Message-ID: <1280719842.3357.167.camel@jabbar> > A different analogy comes to my mind; I once saw two different sets of > people analyze data. One did it "by hand": visually inspecting > thousands > of signals herself and typing Y or N to accept or reject each signal. > The > other did it with an automated system that accepted or rejected > signals > based on fuzzy logic. In an important interpretation, the automated > system > was far better, and yet the first scientist was done with her analysis > and > accepted for publication before the second team even had the bugs > worked > out of the automated system! Yes, I think the slow-but-more-proper > team > did the more correct thing, but there is something to be said for > "good > enough", too (it works for evolution, for example). Che, from the analogies you made, it looks like you might not have very clear what Unit Testing is for. True, UT is a way to automate tests that otherwise you should do manually (as per your analogy), but the test you automate with UT are not a "one off" thing (as it is processing the data needed to publish a paper): depending on the coding philosophy you follow, you might run UT as often as every couple of hours of coding (as it is in certain agile programming techniques). UT is there to give you a tool to prevent regression *when/if you modify or refactor your code* (which is the norm if you are a professional programmer), and its advantages grow exponentially with the increase of complexity of the code and the increase of number of developers working on the project (it is very easy to break someone's else code... there is a reason for which "blame" - http://blame.sourceforge.net/ - is called that way!). If you are an hobbyist programmer busy on a simple one-off small app, you may skip UT altogether, manually inspect the behaviour of your program, and never regret it. But if you are writing an e-commerce application that will organise transaction for millions of euros of revenue monthly, UT is probably the very first code you will want to commit to your repo. Mac. PS: I did not comment on the analogy with evolution, because did not get the parallelism you were trying to draw. Care to explain? From jmacfiggen at gmail.com Mon Aug 2 12:21:35 2010 From: jmacfiggen at gmail.com (Jason MacFiggen) Date: Mon, 2 Aug 2010 03:21:35 -0700 Subject: [Tutor] Menu not working properly Message-ID: My problem is choice 3. Exit, if you select no or put an invalid answer... It will run menu1... but then it runs name = raw_input ("Enter your character name. ") print "Your character name is:", name How can i make it so it prints menu1 like normal... then asks you to enter your selection again? instead of running the above code. -Thank you import sys def menu(): menu1 = """ Pick A Class From The Menu or choose Exit. 1. Warrior 2. Mage 3. Exit """ print "Welcome to Iris's Last Breath" print menu1 characterChoice = input ("Enter your choice. ") print if characterChoice == 1: print """ *Place Holder* """ elif characterChoice == 2: print "Currently under construction.\nPlease choose again." print menu1 elif characterChoice == 3: endProgram = raw_input ("Do you want to end program? yes or no ") if endProgram == "yes": sys.exit(0) elif endProgram == "no": print menu1 else: print "\nInvalid Command:\nSelect from the menu again.\n" print menu1 print name = raw_input ("Enter your character name. ") print "Your character name is:", name -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Mon Aug 2 12:35:17 2010 From: evert.rol at gmail.com (Evert Rol) Date: Mon, 2 Aug 2010 12:35:17 +0200 Subject: [Tutor] Menu not working properly In-Reply-To: References: Message-ID: > My problem is choice 3. Exit, if you select no or put an invalid answer... It will run menu1... but then it runs > name = raw_input ("Enter your character name. ") > print "Your character name is:", name > > How can i make it so it prints menu1 like normal... then asks you to enter your selection again? > instead of running the above code. Put it in a loop with the necessary break statements. Something like: while True: print menu1 answer = raw_input() if ...: ... break elif ...: ... elif ...: answer = raw_input() if ...: sys.exit() raw_input('character name') Only the first option will break out of the loop to the 'character name' question; the other two options will continue to loop, apart from the point where you exit() the whole program. If you need user input until the correct input has been given, that means you'll have to wrap things in a loop (generally a while loop that you break out of when you received correct input). You could factor out the actual code inside the while loop into a function, which can make the structure clearer. Btw, > characterChoice = input ("Enter your choice. ") You have input() here, while further down raw_input(). The latter is preferred in Python 2.x. I assume this is just a minor mistake. Evert > print > > if characterChoice == 1: > print """ > > *Place Holder* > > """ > > elif characterChoice == 2: > print "Currently under construction.\nPlease choose again." > print menu1 > elif characterChoice == 3: > endProgram = raw_input ("Do you want to end program? yes or no ") > if endProgram == "yes": > sys.exit(0) > elif endProgram == "no": > print menu1 > else: > print "\nInvalid Command:\nSelect from the menu again.\n" > print menu1 > > print > name = raw_input ("Enter your character name. ") > print "Your character name is:", name > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From evert.rol at gmail.com Mon Aug 2 14:00:09 2010 From: evert.rol at gmail.com (Evert Rol) Date: Mon, 2 Aug 2010 14:00:09 +0200 Subject: [Tutor] Menu not working properly In-Reply-To: References: Message-ID: <4ED3BBA9-ADA9-4669-98F3-B42765C3C215@gmail.com> > Hello Evert Rol, > Thank you for the menu help, I have completed it with great success... There is 1 more problem I am currently having, and when I fix it my program will be completed. If you are interested in helping me with this last stretch, I will be greatly appreciative. > > If you respond with a yes. I will go ahead and send my code over and list the problem I am currently having. Jason, it makes more sense to send this to the full tutor list, not just to me: there are more people who can and will help you. Unless I've missed a response to a previous post of yours where people disrecommended your postings, but that shouldn't happen to quickly. Although in general, it's better to try and solve the problem yourself, and ask the tutor list if you're really stuck, either with an error or a concept. And the 'try and solve yourself' step can take one or more days and a lot of Googling, but in the end you learn a lot from it. So, depending on your current problem, see if you want to try yourself first, or that you feel you need the input from the list. (Code can be included with the mail if short; use something like http://python.pastebin.com/ if lengthly code.) Good luck, Evert > > -Thank You > > On Mon, Aug 2, 2010 at 3:35 AM, Evert Rol wrote: > > My problem is choice 3. Exit, if you select no or put an invalid answer... It will run menu1... but then it runs > > name = raw_input ("Enter your character name. ") > > print "Your character name is:", name > > > > How can i make it so it prints menu1 like normal... then asks you to enter your selection again? > > instead of running the above code. > > Put it in a loop with the necessary break statements. Something like: > > while True: > print menu1 > answer = raw_input() > if ...: > ... > break > elif ...: > ... > elif ...: > answer = raw_input() > if ...: > sys.exit() > raw_input('character name') > > Only the first option will break out of the loop to the 'character name' question; the other two options will continue to loop, apart from the point where you exit() the whole program. > If you need user input until the correct input has been given, that means you'll have to wrap things in a loop (generally a while loop that you break out of when you received correct input). > You could factor out the actual code inside the while loop into a function, which can make the structure clearer. > > > Btw, > > > > > characterChoice = input ("Enter your choice. ") > > You have input() here, while further down raw_input(). The latter is preferred in Python 2.x. I assume this is just a minor mistake. > > > Evert > > > > print > > > > if characterChoice == 1: > > print """ > > > > *Place Holder* > > > > """ > > > > elif characterChoice == 2: > > print "Currently under construction.\nPlease choose again." > > print menu1 > > elif characterChoice == 3: > > endProgram = raw_input ("Do you want to end program? yes or no ") > > if endProgram == "yes": > > sys.exit(0) > > elif endProgram == "no": > > print menu1 > > else: > > print "\nInvalid Command:\nSelect from the menu again.\n" > > print menu1 > > > > print > > name = raw_input ("Enter your character name. ") > > print "Your character name is:", name > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > From smokefloat at gmail.com Mon Aug 2 15:13:34 2010 From: smokefloat at gmail.com (David Hutto) Date: Mon, 2 Aug 2010 09:13:34 -0400 Subject: [Tutor] Menu not working properly In-Reply-To: <4ED3BBA9-ADA9-4669-98F3-B42765C3C215@gmail.com> References: <4ED3BBA9-ADA9-4669-98F3-B42765C3C215@gmail.com> Message-ID: On Mon, Aug 2, 2010 at 8:00 AM, Evert Rol wrote: >> Hello Evert Rol, >> ? ? ? ? ? Thank you for the menu help, I have completed it with great success... There is 1 more problem I am currently having, and when I fix it my program will be completed. If you are interested in helping me with this last stretch, I will be greatly appreciative. >> >> ? ? ? ? ? If you respond with a yes. I will go ahead and send my code over and list the problem I am currently having. > > Jason, it makes more sense to send this to the full tutor list, not just to me: Ahhhh ha haha, you hit the wrong 'reply to button'. Stupid newb says what? there are more people who can and will help you. Unless I've missed a response to a previous post of yours where people disrecommended your postings, but that shouldn't happen to quickly. > Although in general, it's better to try and solve the problem yourself, and ask the tutor list if you're really stuck, either with an error or a concept. And the 'try and solve yourself' step can take one or more days and a lot of Googling, but in the end you learn a lot from it. > So, depending on your current problem, see if you want to try yourself first, or that you feel you need the input from the list. > (Code can be included with the mail if short; use something like http://python.pastebin.com/ if lengthly code.) > > Good luck, > > ?Evert > > > > > >> >> ? ? ? ? ?-Thank You >> >> On Mon, Aug 2, 2010 at 3:35 AM, Evert Rol wrote: >> > My problem is choice 3. Exit, if you select no or put an invalid answer... It will run menu1... but then it runs >> > ? ? name = raw_input ("Enter your character name. ") >> > ? ? print "Your character name is:", name >> > >> > How can i make it so it prints menu1 like normal... then asks you to enter your selection again? >> > instead of running the above code. >> >> Put it in a loop with the necessary break statements. Something like: >> >> while True: >> ?print menu1 >> ?answer = raw_input() >> ?if ...: >> ? ?... >> ? ?break >> ?elif ...: >> ? ?... >> ?elif ...: >> ? answer = raw_input() >> ? if ...: >> ? ? sys.exit() >> raw_input('character name') >> >> Only the first option will break out of the loop to the 'character name' question; the other two options will continue to loop, apart from the point where you exit() the whole program. >> If you need user input until the correct input has been given, that means you'll have to wrap things in a loop (generally a while loop that you break out of when you received correct input). >> You could factor out the actual code inside the while loop into a function, which can make the structure clearer. >> >> >> Btw, >> >> >> >> > ? ? characterChoice = input ("Enter your choice. ") >> >> You have input() here, while further down raw_input(). The latter is preferred in Python 2.x. I assume this is just a minor mistake. >> >> >> ?Evert >> >> >> > ? ? print >> > >> > ? ? if characterChoice == 1: >> > ? ? ? ? print """ >> > >> > *Place Holder* >> > >> > ? ? ? ? """ >> > >> > ? ? elif characterChoice == 2: >> > ? ? ? ? print "Currently under construction.\nPlease choose again." >> > ? ? ? ? print menu1 >> > ? ? elif characterChoice == 3: >> > ? ? ? ? endProgram = raw_input ("Do you want to end program? yes or no ") >> > ? ? ? ? if endProgram == "yes": >> > ? ? ? ? ? ? sys.exit(0) >> > ? ? ? ? elif endProgram == "no": >> > ? ? ? ? ? ? print menu1 >> > ? ? ? ? else: >> > ? ? ? ? ? ? print "\nInvalid Command:\nSelect from the menu again.\n" >> > ? ? ? ? ? ? print menu1 >> > >> > ? ? print >> > ? ? name = raw_input ("Enter your character name. ") >> > ? ? print "Your character name is:", name >> > _______________________________________________ >> > Tutor maillist ?- ?Tutor at python.org >> > To unsubscribe or change subscription options: >> > http://mail.python.org/mailman/listinfo/tutor >> >> > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From rabidpoobear at gmail.com Mon Aug 2 16:41:38 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 2 Aug 2010 09:41:38 -0500 Subject: [Tutor] Menu not working properly In-Reply-To: References: <4ED3BBA9-ADA9-4669-98F3-B42765C3C215@gmail.com> Message-ID: On Aug 2, 2010, at 8:13 AM, David Hutto wrote: > On Mon, Aug 2, 2010 at 8:00 AM, Evert Rol wrote: >>> Hello Evert Rol, >>> Thank you for the menu help, I have completed it with great success... There is 1 more problem I am currently having, and when I fix it my program will be completed. If you are interested in helping me with this last stretch, I will be greatly appreciative. >>> >>> If you respond with a yes. I will go ahead and send my code over and list the problem I am currently having. >> >> Jason, it makes more sense to send this to the full tutor list, not just to me: > > Ahhhh ha haha, you hit the wrong 'reply to button'. Stupid newb says what? I hope you're kidding. If you're not, leave the list right away. You are not being helpful. If you were kidding, make it more clear next time. > > there are more people who can and will help you. Unless I've missed a > response to a previous post of yours where people disrecommended your > postings, but that shouldn't happen to quickly. Have you heard the saying about throwing rocks at glass houses? 'cause you just screwed up your reply quoting. -Luke From smokefloat at gmail.com Mon Aug 2 16:57:26 2010 From: smokefloat at gmail.com (David Hutto) Date: Mon, 2 Aug 2010 10:57:26 -0400 Subject: [Tutor] Menu not working properly In-Reply-To: References: <4ED3BBA9-ADA9-4669-98F3-B42765C3C215@gmail.com> Message-ID: On Mon, Aug 2, 2010 at 10:41 AM, Luke Paireepinart wrote: > > > On Aug 2, 2010, at 8:13 AM, David Hutto wrote: > >> On Mon, Aug 2, 2010 at 8:00 AM, Evert Rol wrote: >>>> Hello Evert Rol, >>>> ? ? ? ? ? Thank you for the menu help, I have completed it with great success... There is 1 more problem I am currently having, and when I fix it my program will be completed. If you are interested in helping me with this last stretch, I will be greatly appreciative. >>>> >>>> ? ? ? ? ? If you respond with a yes. I will go ahead and send my code over and list the problem I am currently having. >>> >>> Jason, it makes more sense to send this to the full tutor list, not just to me: >> >> Ahhhh ha haha, you hit the wrong 'reply to button'. Stupid newb says what? The first rule of any endeavour is to learn to laugh at yourself. If you don't have cahunas to call your own self a newb, and laugh at the mistakes you made, after thought , then what kind of programmers will you be? > I hope you're kidding. If you're not, leave the list right away. It was a joke. Bad but I laughed at it. You are not being helpful. If you were kidding, make it more clear next time. >> >> there are more people who can and will help you. Unless I've missed a >> response to a previous post of yours where people disrecommended your >> postings, but that shouldn't happen to quickly. > Have you heard the saying about throwing rocks at glass houses? 'cause you just screwed up your reply quoting. > > -Luke From huyslogic at gmail.com Mon Aug 2 17:01:27 2010 From: huyslogic at gmail.com (Huy Ton That) Date: Mon, 2 Aug 2010 11:01:27 -0400 Subject: [Tutor] Where to start with Unit Testing In-Reply-To: <1280669143.3357.115.camel@jabbar> References: <1280669143.3357.115.camel@jabbar> Message-ID: Thanks additionally for your insight gems. Without reading too much into it, it was quite simple to create a series of test classes which just run some expected assertion values on a small scenario of inputs and what's expected. I usually find that I learn best by dabbling around in source code, then writing some code to test what I think I know. I'll try to integrate this and commit this to memory with time where I won't have to look back as much (: On Sun, Aug 1, 2010 at 9:25 AM, Mac Ryan wrote: > On Sun, 2010-08-01 at 03:30 -0400, Huy Ton That wrote: > > Hi all, > > > > Do any of you have any feedback, strategies and best practices related > > to unit testing within Python. This is a relatively new topic for me. > > I was thinking of starting with reading the documentation associate > > with the unittest module. > > My answer falls in the category "feedback" (I was also going to mention > the diveintopython page, but somebody else has done that already!), so > you should be aware what follows is highly subjective... > > JUST THINK... IN PYTHON! > IMO, unit testing is really easy to pick up. It really does not > amount to much more than taking note (in python) of what you are > thinking when you are coding. > If you are anything like me, when you code you keep on formulating > "rules" in your head, in the line of "when everything works as expected, > if the methods iterates four times, then this method must return X" or > "when everything works as expected, if a user enter a value over 212 > then the script must throw this exception", etc... > * the "when everything works as expected" translates in "this test > pass when..." > * the "if X" translates in your test case (i.e. the scenario you are > testing for) > * the "then Y" translates in "the outcome of my test case must be Y" > > TESTING IS VALUABLE IN THE LONG RUN > At times, designing and coding a test is a time-consuming activity, > and if the code is particularly straightforward you might be tempted to > skip the unit testing altogether. In my experience - however - unit > testing is never as useful on the spot as it is three months from now, > when you will have/want/choose to modify a little bit of your old code, > and all of a sudden everything will break. In the latter scenario, your > test suite will be an invaluable asset. > > FUNCTIONAL PROGRAMMING WINS > The most difficult thing in writing a test, is replicating the state > of the environment needed for the test to happen. This is especially > (but not uniquely) true for DB-driven applications, when you might wish > to perform test on methods that interact with the DB. In that case you > have to create a test DB, populate it with ~credible data, etc... > The most "functional" (as in functional programming, i.e. > machine-state independent) is your code, the easiest is to write a test. > Example: if you need to check a method that validate the postal code of > an address based on the name of the city, it is easier to test a method > that is invoked with "validate_postal_code(code, city)" rather than one > that is invoked with "validate_postal_address(user)" and that will have > to retrieve the full address of a user from a DB, and extract the city > and postal address from it. > > MVC WINS > I never test UI's. I know it is bad... but it is simply too > time-consuming for me (I'll be very glad if somebody reading this will > show me how one can make it snappier!). This means - at least for me - > that writing tests become extremely easier for me if I keep separated > the presentation layer from all the rest of the stuff. > > EVERY BUG IS A TEST YET NOT WRITTEN > A program that passes all its tests is not necessarily a bug-free > program. But once you find a new bug, try to make a point of writing a > new test that check for that particular scenario in which said bug is > happening. > > TEST-DRIVEN IS BETTER > What I find useful (although not always applicable) is to start my > programming session by writing the tests before I write the code to be > tested. This somehow reconnect to my previously articulated "just > think... in python!" point: you are however *already doing a list of > rules* in your head, before writing code, so you could well write it > down directly in code. All you need is to create a mock method/function > in your code with the same signature you are using in your test. For > example. You could write tests in the form: > > assertEqual(better_square_root(9), 3) > assertRaises(ValueError, better_square_root, -4) > > and then write in your module: > > def my_better_square_root(number): > pass > > all your tests will of course initially fail, but then you will keep on > working on the code of my_better_square_root until all your tests pass. > > Well, these are just my two ?... As stated in the beginning: highly > subjective, so keep your mind open for other (possibly opposite) > opinions too! :) > > HTH, > Mac. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From huyslogic at gmail.com Mon Aug 2 17:16:50 2010 From: huyslogic at gmail.com (Huy Ton That) Date: Mon, 2 Aug 2010 11:16:50 -0400 Subject: [Tutor] Where to start with Unit Testing In-Reply-To: References: Message-ID: One final note, that I thought might be useful to others. I've just discovered doctest, which allows you to run tests on your embedded function/class documentation. Check it out here: http://docs.python.org/tutorial/stdlib.html#quality-control On Sun, Aug 1, 2010 at 3:30 AM, Huy Ton That wrote: > Hi all, > > Do any of you have any feedback, strategies and best practices related to > unit testing within Python. This is a relatively new topic for me. I was > thinking of starting with reading the documentation associate with the > unittest module. > > -Huy > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pine508 at hotmail.com Mon Aug 2 17:59:18 2010 From: pine508 at hotmail.com (Che M) Date: Mon, 2 Aug 2010 11:59:18 -0400 Subject: [Tutor] Where to start with Unit Testing In-Reply-To: <1280719842.3357.167.camel@jabbar> References: ,, ,, , , <1280719842.3357.167.camel@jabbar> Message-ID: > Che, from the analogies you made, it looks like you might not have very > clear what Unit Testing is for. > > True, UT is a way to automate tests that otherwise you should do > manually (as per your analogy), but the test you automate with UT are > not a "one off" thing (as it is processing the data needed to publish a > paper): depending on the coding philosophy you follow, you might run UT > as often as every couple of hours of coding (as it is in certain agile > programming techniques). > > UT is there to give you a tool to prevent regression *when/if you modify > or refactor your code* (which is the norm if you are a professional > programmer), and its advantages grow exponentially with the increase of > complexity of the code and the increase of number of developers working > on the project (it is very easy to break someone's else code... there is > a reason for which "blame" - http://blame.sourceforge.net/ - is called > that way!). > > If you are an hobbyist programmer busy on a simple one-off small app, > you may skip UT altogether, manually inspect the behaviour of your > program, and never regret it. > > But if you are writing an e-commerce application that will organise > transaction for millions of euros of revenue monthly, UT is probably the > very first code you will want to commit to your repo. Mac, I found this an excellent brief overview of UT and your points all seem very strong to me. Thanks very much. I admit I didn't really know anything about the topic and was mentioning my feelings on the matter partly to elicit enlightening responses like this (maybe because I was feeling like I was being irresponsible with my own project by not learning UT and running tests). I am in the "hobbyist programmer busy on a simple one-off small app" camp ("simple" is relative...though it is clearly nothing like a big e-commerce application!), so I feel OK with foregoing getting into UT for now. If things get more complex and I at some point have actual users instead of the large number of vapor users I have now (:D) I may buckle down and learn it. > PS: I did not comment on the analogy with evolution, because did not get > the parallelism you were trying to draw. Care to explain? I just meant that evolution by natural selection works on a "good enough" principle: that successful species evolve not toward the most perfected forms but the forms that are simply good enough to allow them to pass on enough of their genes to stay in the game. And sometimes "good enough" is good enough--that is, you shouldn't waste your time doing things perfectly properly. In my case, I thought doing things perfectly properly would be learning all about UT and bringing that into my development process--but manual inspection would be "good enough". (But now I see that really it *is* proper to skip UT if the project doesn't warrant it). Thanks, Che -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Mon Aug 2 20:58:17 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Mon, 2 Aug 2010 11:58:17 -0700 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: References: Message-ID: On Sun, Aug 1, 2010 at 17:38, Hugo Arts wrote: > On Mon, Aug 2, 2010 at 2:26 AM, Richard D. Moores wrote: >> >> Well, I'd like to try. Could you give me, say, an outline of what >> might be a good way? Actually, before I changed to the error catching, >> I tried to break it up into a bunch of small functions. But they got >> all tangled up with some functions returning the calling of others, >> that I couldn't get them straightened out. Also, some were required to >> have such a long string of arguments I couldn't get them all on one >> line. >> > > For starters, the code recreating both your files is almost exactly > the same, so you can easily turn that into one function and call it > twice. I see two necessary arguments, the path and the data you're > dumping in. See if you can work that one out. > > The file saving code at the end is another one that can be easily made > into one function and called twice. If you get those two pieces done > you should be in good shape. OK, here's my attempt: . Better? Dick From pine508 at hotmail.com Mon Aug 2 22:07:09 2010 From: pine508 at hotmail.com (Che M) Date: Mon, 2 Aug 2010 16:07:09 -0400 Subject: [Tutor] global exception handling? Message-ID: A week or two back I asked this list about how to deal with SQLite database errors like 'database is locked'. Since then I figured out one way to reproduce that error (*see p.s. below if anyone is interested). I can also then catch the error with a try/except block and prevent it from causing problems. But, the issue is, I have many places where I write to the database and would have to embed each of these in a try/except block. I can do that, but wondered if there is a "global" way to catch this 'database is locked' error? I found someone asking this sort of question online but it doesn't appear to be answered: http://bytes.com/topic/python/answers/799486-how-do-i-prevent-exceptions-stopping-execution-global-exception-handler Thanks, Che p.s. *I use the nice program SQLite Database Browser and if I edit a field in the database my Python app is accessing, click "Apply changes", but I do *not* save the changes (that is, I do not click the disk icon), when I go to write to that database from my Python app, I get a 'database is locked' error. -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Mon Aug 2 22:48:36 2010 From: evert.rol at gmail.com (Evert Rol) Date: Mon, 2 Aug 2010 22:48:36 +0200 Subject: [Tutor] sys.exit help In-Reply-To: References: <9D8113E9-9DF2-4E30-B62C-BF89A5155C63@gmail.com> Message-ID: <224CD238-D70C-47CF-91F0-C52CDA695AAF@gmail.com> (replying to the full list; hope that was intended.) >>> I was wondering how can I change sys.exit so if you use command line to run the program. it prompts a message asking if the user wants to exit instead of automatically just exiting? >> >> Just write a wrapper exit() function around sys.exit that does that. > > In a post 2 minutes after yours, Steven D'Aprano says, "write your own > quit() function that > asks the user and then calls sys.exit if they say yes." > > Is that an example of what you meant by a wrapper? I've never been > sure I understood the term, "wrapper". Yes. A "wrapper function" would be a function that "wraps itself around" something else, most of the time around another function. It's often used to expand original functionality of a function, or to make life easier it you need to always set some variables before calling the original function. In Python, you could almost call it a decorator, although in this case that wouldn't be a good idea. And wrapper function (as far as I'm aware) is a more general term. For fun I just Googled for "wrapper function" (always useful). First hit leads to wikipedia: http://en.wikipedia.org/wiki/Wrapper_function (though it's a short wiki entry, and I'm not sure how much extra it would clarify). Evert From evert.rol at gmail.com Mon Aug 2 23:08:45 2010 From: evert.rol at gmail.com (Evert Rol) Date: Mon, 2 Aug 2010 23:08:45 +0200 Subject: [Tutor] global exception handling? In-Reply-To: References: Message-ID: > A week or two back I asked this list about how to deal with SQLite database errors like 'database is locked'. Since then I figured out one way to reproduce that error (*see p.s. below if anyone is interested). I can also then catch the error with a try/except block and prevent it from causing problems. > > But, the issue is, I have many places where I write to the database and would have to embed each of these in a try/except block. I can do that, but wondered if there is a "global" way to catch this 'database is locked' error? I found someone asking this sort of question online but it doesn't appear to be answered: > http://bytes.com/topic/python/answers/799486-how-do-i-prevent-exceptions-stopping-execution-global-exception-handler I'm not sure why you would like to do that: your code assumes the database interaction works fine, and based on that just continues it's normal flow. If the database is locked, you'll need to do something to prevent your code crashing further down, which is what you put in the except OperationalError: block. I would assume that the error handling depends on where you are in the code. If you can always perform the same type of error handling, just create a convenience function (possibly with the SQL statement as argument) that calls the database and returns the results, and put the database call inside the try: except: clause. Then you need to do this only once. A global way to catch the database-locked exception is just to put the try: except OperationalError: around your complete code. Exceptions propagate all the way to the function where your program started, and if you catch it there, you will catch every OperationalError exception from anywhere in the code. Of course, your program then always exits anyway, because you can't return to the point where the the exception was thrown (or maybe you can, but not that I'm aware of. I wouldn't recommend it though). > Thanks, > Che > > p.s. *I use the nice program SQLite Database Browser and if I edit a field in the database my Python app is accessing, click "Apply changes", but I do *not* save the changes (that is, I do not click the disk icon), when I go to write to that database from my Python app, I get a 'database is locked' error. Sounds like somewhat odd behaviour to me: "apply changes" for me means "apply & commit", ie, it includes the save operation. Might just be me. I guess "Apply changes" opens the database connection, but then "save" performs the actual commit to the database, and in the meantime the database is locked. From hugo.yoshi at gmail.com Mon Aug 2 23:28:28 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Mon, 2 Aug 2010 23:28:28 +0200 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: References: Message-ID: On Mon, Aug 2, 2010 at 8:58 PM, Richard D. Moores wrote: > > OK, here's my attempt: . ?Better? > Much better. But why is that F in the argument list of both functions? It's overwritten immediately with the open() call, so it seems unnecessary to include in the arguments. Hugo From rdmoores at gmail.com Tue Aug 3 00:42:01 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Mon, 2 Aug 2010 15:42:01 -0700 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: References: Message-ID: On Mon, Aug 2, 2010 at 14:28, Hugo Arts wrote: > On Mon, Aug 2, 2010 at 8:58 PM, Richard D. Moores wrote: >> >> OK, here's my attempt: . ?Better? >> > > Much better. But why is that F in the argument list of both functions? > It's overwritten immediately with the open() call, so it seems > unnecessary to include in the arguments. I need it for lines 36 and 37, don't I? Here's the latest incarnation: Dick From hugo.yoshi at gmail.com Tue Aug 3 00:43:59 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 3 Aug 2010 00:43:59 +0200 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: References: Message-ID: On Tue, Aug 3, 2010 at 12:42 AM, Richard D. Moores wrote: > On Mon, Aug 2, 2010 at 14:28, Hugo Arts wrote: >> On Mon, Aug 2, 2010 at 8:58 PM, Richard D. Moores wrote: >>> >>> OK, here's my attempt: . ?Better? >>> >> >> Much better. But why is that F in the argument list of both functions? >> It's overwritten immediately with the open() call, so it seems >> unnecessary to include in the arguments. > > I need it for lines 36 and 37, don't I? > > Here's the latest incarnation: > > Dick > Do you? you're just passing in the strings "F_used" and "F_unused", and you're not even using them inside the function. I'd say cut it all out. From rdmoores at gmail.com Tue Aug 3 00:56:04 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Mon, 2 Aug 2010 15:56:04 -0700 Subject: [Tutor] sys.exit help In-Reply-To: <224CD238-D70C-47CF-91F0-C52CDA695AAF@gmail.com> References: <9D8113E9-9DF2-4E30-B62C-BF89A5155C63@gmail.com> <224CD238-D70C-47CF-91F0-C52CDA695AAF@gmail.com> Message-ID: On Mon, Aug 2, 2010 at 13:48, Evert Rol wrote: > (replying to the full list; hope that was intended.) > >>>> I was wondering how can I change sys.exit so if you use command line to run the program. it prompts a message asking if the user wants to exit instead of automatically just exiting? >>> >>> Just write a wrapper exit() function around sys.exit that does that. >> >> In a post 2 minutes after yours, Steven D'Aprano says, "write your own >> quit() function that >> asks the user and then calls sys.exit if they say yes." >> >> Is that an example of what you meant by a wrapper? I've never been >> sure I understood the term, "wrapper". > > Yes. A "wrapper function" would be a function that "wraps itself around" something else, most of the time around another function. It's often used to expand original functionality of a function, or to make life easier it you need to always set some variables before calling the original function. > In Python, you could almost call it a decorator, although in this case that wouldn't be a good idea. And wrapper function (as far as I'm aware) is a more general term. > > For fun I just Googled for "wrapper function" (always useful). First hit leads to wikipedia: http://en.wikipedia.org/wiki/Wrapper_function (though it's a short wiki entry, and I'm not sure how much extra it would clarify). Thanks, Evert, for your explanation. A big help. Dick From rdmoores at gmail.com Tue Aug 3 01:31:13 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Mon, 2 Aug 2010 16:31:13 -0700 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: References: Message-ID: On Mon, Aug 2, 2010 at 15:43, Hugo Arts wrote: > On Tue, Aug 3, 2010 at 12:42 AM, Richard D. Moores wrote: >> On Mon, Aug 2, 2010 at 14:28, Hugo Arts wrote: >>> On Mon, Aug 2, 2010 at 8:58 PM, Richard D. Moores wrote: >>>> >>>> OK, here's my attempt: . ?Better? >>>> >>> >>> Much better. But why is that F in the argument list of both functions? >>> It's overwritten immediately with the open() call, so it seems >>> unnecessary to include in the arguments. >> >> I need it for lines 36 and 37, don't I? >> >> Here's the latest incarnation: >> >> Dick >> > > Do you? you're just passing in the strings "F_used" and "F_unused", > and you're not even using them inside the function. I'd say cut it all > out. By golly, you're right! Your point led to changes in 4 lines, the ones highlighted: Thanks very much, Hugo. Dick From alan.gauld at btinternet.com Tue Aug 3 01:55:56 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 3 Aug 2010 00:55:56 +0100 Subject: [Tutor] How to get script to detect whether a file exists? References: Message-ID: "Richard D. Moores" wrote > By golly, you're right! Your point led to changes in 4 lines, the > ones > highlighted: Its a Good Thing(TM) to keep your interface specs consistent so I'd change the order of the parameters in repickling() to match those in create_pickle_file() For bonus points create a PickleFile class that has dump(), load() and repickle() methods - and uses __init__() for create obviously. The class can store the file name for convenience. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Tue Aug 3 01:57:13 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 3 Aug 2010 09:57:13 +1000 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: References: Message-ID: <201008030957.14180.steve@pearwood.info> On Tue, 3 Aug 2010 08:42:01 am Richard D. Moores wrote: > On Mon, Aug 2, 2010 at 14:28, Hugo Arts wrote: > > On Mon, Aug 2, 2010 at 8:58 PM, Richard D. Moores wrote: > >> OK, here's my attempt: . > >> ?Better? > > > > Much better. But why is that F in the argument list of both > > functions? It's overwritten immediately with the open() call, so it > > seems unnecessary to include in the arguments. > > I need it for lines 36 and 37, don't I? > > Here's the latest incarnation: > One hint is that functions that do similar things should have similar signatures. (The signature of a function is the list of arguments it takes.) So create_pickle_file and repickling do similar things, they should look similar. The F argument isn't used, it's just immediately thrown away and replaced, so drop it: def create_pickle_file(path, D): F = open(path, 'wb') pickle.dump(D, F) F.close() def repickling(path, D): F = open(path, 'wb') pickle.dump(D, F) Now, let's look carefully at the bodies of the functions. The first shares 2 lines out of 3 with the second. The second shares 100% of it's body with the first. The *only* difference is a trivial one: in the first function, the opened file is explicitly closed, while in the second function, the opened file is automatically closed. In other words, your two functions do EXACTLY the same thing. Let's throw one out, and give the survivor a nicer name and some help text and documentation (although in this case the function is so simple it hardly needs it): def save(path, D): """Open file given by path and save D to it. Returns nothing. """ F = open(path, 'wb') pickle.dump(D, F) F.close() Notice that the function name says *what* it does ("save") rather than *how* it does it ("pickling"). You might change your mind and decide later that instead of pickle you want to use an INI file, or JSON, or XML, or something else. Also, I prefer to explicitly close files, although on a small script like this it makes no real difference. Feel free to leave that line out. Now how do you use it? Let's look what you do next: try: F_unused = open(path1, 'rb') F_used = open(path2, 'rb') except IOError: unused_ints = [x for x in range(1, record_label_num_pages + 1)] used_ints = [] create_pickle_file(path1, 'F_unused', unused_ints) create_pickle_file(path2, 'F_used', used_ints) print("Pickle files have been created.") print() There's a few problems there. For starters, if *either* file is missing, BOTH get re-created. Surely that's not what you want? You only want to re-create the missing file. Worse, if an IOError does occur, the variables F_used and F_unused never get set, so when you try to used those variables later, you'll have a problem. I'm not sure why you need to store both used and unused numbers. Surely you can calculate one from the other? So here's my thoughts... record_label_name = "ABC_Classics" record_label_num_pages = 37 used_ints_pickle_filename = record_label_name + "_used_ints.pkl" path = '/p31working/Pickles/' + used_ints_pickle_filename # These are the available page numbers. pool = range(1, record_label_num_pages + 1) def save(path, D): """Open file given by path and save D to it. Returns nothing. """ F = open(path, 'wb') pickle.dump(D, F) F.close() def load(path): """Open file given by path if it exists, and return its contents. If it doesn't exist, save and return the default contents. """ try: f = open(path, 'r') except IOError: # File *probably* doesn't exist. Consider better error checking. data = [] save(path, data) else: data = pickle.load(f) f.close() return data used_page_numbers = load(path) unused_page_numbers = [n for n in pool if n not in used_page_numbers] if not unused_page_numbers: print("All pages checked.") print("Program will now close.") sleep(2.1) sys.exit() and now that you have a list of unused page numbers, continue on with the rest of your program. -- Steven D'Aprano From rdmoores at gmail.com Tue Aug 3 02:16:15 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Mon, 2 Aug 2010 17:16:15 -0700 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: References: Message-ID: On Mon, Aug 2, 2010 at 16:55, Alan Gauld wrote: > "Richard D. Moores" wrote > >> By golly, you're right! Your point led to changes in 4 lines, the ones >> highlighted: > > Its a Good Thing(TM) to keep your interface specs consistent so > I'd change the order of the parameters in repickling() to match > those in create_pickle_file() Yes, I discovered that. A good lesson. That was one factor that kept me from recognizing that create_pickle_file() and repickling() were essentially identical, and as Hugo pointed out, one could be removed. I did that. See > > For bonus points create a PickleFile class that has dump(), > load() and repickle() methods - and uses __init__() for create obviously. > The class can store the file name for convenience. Hoo boy, how much time do I have? I've yet to create a class, though I've studied them a bit. For example in an older version of your tutorial -- the bank account example. Dick From rdmoores at gmail.com Tue Aug 3 02:53:50 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Mon, 2 Aug 2010 17:53:50 -0700 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: References: <201008030957.14180.steve@pearwood.info> Message-ID: On Mon, Aug 2, 2010 at 16:57, Steven D'Aprano wrote: > ?# File *probably* doesn't exist. Consider better error checking. Steve, before I dig into your detailed reply, please tell me what you meant by " # File *probably* doesn't exist. Consider better error checking.". Context was def load(path): ? """Open file given by path if it exists, and return its contents. ? If it doesn't exist, save and return the default contents. ? """ ? try: ? ? ? f = open(path, 'r') ? except IOError: ? ? ? # File *probably* doesn't exist. Consider better error checking. ? ? ? data = [] ? ? ? save(path, data) ? else: ? ? ? data = pickle.load(f) ? ? ? f.close() ? return data Dick From smokefloat at gmail.com Tue Aug 3 06:05:24 2010 From: smokefloat at gmail.com (David Hutto) Date: Tue, 3 Aug 2010 00:05:24 -0400 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: References: <201008030957.14180.steve@pearwood.info> Message-ID: On Mon, Aug 2, 2010 at 8:53 PM, Richard D. Moores wrote: > On Mon, Aug 2, 2010 at 16:57, Steven D'Aprano wrote: >> ?# File *probably* doesn't exist. Consider better error checking. > > Steve, before I dig into your detailed reply, please tell me what you > meant by " # File *probably* doesn't exist. Consider better error > checking.". He was referring to the uncertainty principle that applies to all man and life, ain't that right stephan?...*wink*, *wink*, *nudge*, *nudge*. > > Context was > > def load(path): > ? """Open file given by path if it exists, and return its contents. > ? If it doesn't exist, save and return the default contents. > ? """ > ? try: > ? ? ? f = open(path, 'r') > ? except IOError: > ? ? ? # File *probably* doesn't exist. Consider better error checking. > ? ? ? data = [] > ? ? ? save(path, data) > ? else: > ? ? ? data = pickle.load(f) > ? ? ? f.close() > ? return data > > Dick > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From pine508 at hotmail.com Tue Aug 3 06:08:18 2010 From: pine508 at hotmail.com (Che M) Date: Tue, 3 Aug 2010 00:08:18 -0400 Subject: [Tutor] web-based python? In-Reply-To: References: , , , , , , Message-ID: Thanks, Alan, for this set of helpful pointers. Just a few responses. > Actually web apps are all pretty similar. They consist of three basic > parts > (maybe 4): > 1) A mechanism for mapping a URL to a Python function or method. > 2) A mechanism for generating HTML with embedded data values > 3) A data storage mechanism > 4) Some client code for a more dynamic feel What does "client code" and "more dynamic feel" mean here? > > - The easiest possible "Hello, World!" (just text) in a web browser. > >

Hello, World! > > That's it as a one liner. I guess I meant the easiest possible "Hello, World!" that incorporates Python and works through a server, etc. This is just the HTML. And even with this, a total beginner will have no idea that he or she should copy that into a Notepad window, save it as helloworld.html, and then open that file from Firefox to see it as HTML. The point is, in many discussions of web programming all the elements (and there are many) are scattered and disconnected from the concrete steps one needs to take to put them into working order. I recall that CherryPy has a little walk-through on how to get something very simple working with it, and that's closer to what I'm recommending. (Though obviously you're just answering bullet points in an email and this is not your tutorial :D ). > If you want it as a CGI program in Python its only slightly longer > and the CGI documentation shows you how... Probably that's what I'm after, but my guess is the CGI documentation is not particularly approachable (though haven't checked). A beginner would also not know where "the" CGI documentation is. > > - How you can get more than just text on a web app, that is, > > widgets, and > > therefore what are currently the options for that (learning > > javascript and whatever > > widget toolkits are out there for that; qooxdoo; Pyjamas; others). > > This is where it gets very complicated. And yet I think this what it's all about. When beginners think about a web app (or dynamic web page as someone else here put it), they don't think about HTML and text going back and forth to/from a server, they think about widgets similar to widgets seen on the desktop (calendars, buttons, textboxes, checkboxes, etc.). I was excited to see the Quooxdoo widget set and heard it might be possible to use it with a Python backend...via JSON (which I don't know about) but it was too nebulous to motivate pursuing when I am still working on learning desktop programming. > > - How you can develop your web app on your own computer and when you > > need to test it actually on the web. > > Thats usually just a case of running a web server on your PC. And that's its own topic. "Running a web server on your PC" rings zero bells for beginners. > Wikipedia is your friend and the partial topic that I did on web > programming did include some of the basic stuff with lots of > links to Wikipedia articles. I don't think Wikipedia is the beginner's friend on this sort of thing. I have not found it good for learning how to program. Just looking at the topic "web development" shows this; it is an overview of the field, but there is no instructional/tutorial material. It doesn't teach how to do it. > HTH, It is helpful, and like anything one can probably work his or her way through the topic slowly and stumblingly, but I do think that a thorough starting-with- zero-knowledge-and-defining-all-terms tutorial would be a wonderful thing to have. As you said before, web programming is a lot more involved than desktop programming. I think it would be really a fun challenge to put together a great soup-to-nuts tutorial on this (but I am far from the one to do it!), since it incorporates so many elements. I wish you luck on the Py3 tutorial and and web app tutorial work when you have the chance. Thanks, Che -------------- next part -------------- An HTML attachment was scrubbed... URL: From smokefloat at gmail.com Tue Aug 3 06:13:46 2010 From: smokefloat at gmail.com (David Hutto) Date: Tue, 3 Aug 2010 00:13:46 -0400 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: References: <201008030957.14180.steve@pearwood.info> Message-ID: On Tue, Aug 3, 2010 at 12:05 AM, David Hutto wrote: > On Mon, Aug 2, 2010 at 8:53 PM, Richard D. Moores wrote: >> On Mon, Aug 2, 2010 at 16:57, Steven D'Aprano wrote: >>> ?# File *probably* doesn't exist. Consider better error checking. >> >> Steve, before I dig into your detailed reply, please tell me what you >> meant by " # File *probably* doesn't exist. Consider better error >> checking.". > > > He was referring to the uncertainty principle that applies to all man > and life, ain't that right stephan?...*wink*, *wink*, *nudge*, > *nudge*. >> >> Context was >> >> def load(path): >> ? """Open file given by path if it exists, and return its contents. >> ? If it doesn't exist, save and return the default contents. >> ? """ >> ? try: >> ? ? ? f = open(path, 'r') >> ? except IOError: >> ? ? ? # File *probably* doesn't exist. Consider better error checking. >> ? ? ? data = [] >> ? ? ? save(path, data) >> ? else: >> ? ? ? data = pickle.load(f) >> ? ? ? f.close() >> ? return data >> >> Dick >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> I know that sometimes, in the darkof night, i say stephan of oracle eternance, please impart to me thy wisdom. And stephan answers with bowels in hand, and relevance upon his tongue he delivers our saving grace. From guerrerocarlos at gmail.com Tue Aug 3 06:34:06 2010 From: guerrerocarlos at gmail.com (Carlos Guerrero) Date: Tue, 3 Aug 2010 00:04:06 -0430 Subject: [Tutor] web-based python? In-Reply-To: References: Message-ID: IMHO, i believe that yes you can run django inside that server, but in a different way, this is how i believe this could be possible: do your django app but do it inside the django source folder you can download from the official site, and make it so, that all functions and models you need from django can be found by the interpreter, and make it run well in your computer without installing django in it, but making it work as a standalone python app. Then upload all the code to the server, and just like you would do by ssh command line, invoking commands to run the django apps and the httpserver, invoke the commands, -from- a .py script also in the server, so that by entering in www.example.com/rundjangoserver.py would make the django server run. just a thought, hope others can give more light to this, best regards. On Mon, Aug 2, 2010 at 11:38 PM, Che M wrote: > > > Thanks, Alan, for this set of helpful pointers. Just a few responses. > > > > Actually web apps are all pretty similar. They consist of three basic > > parts > > (maybe 4): > > 1) A mechanism for mapping a URL to a Python function or method. > > 2) A mechanism for generating HTML with embedded data values > > 3) A data storage mechanism > > 4) Some client code for a more dynamic feel > > What does "client code" and "more dynamic feel" mean here? > > > > > - The easiest possible "Hello, World!" (just text) in a web browser. > > > >

Hello, World! > > > > That's it as a one liner. > > I guess I meant the easiest possible "Hello, World!" that incorporates > Python and works through a server, etc. This is just the HTML. And > even with this, a total beginner will have no idea that he or she should > copy that into a Notepad window, save it as helloworld.html, and then > open that file from Firefox to see it as HTML. The point is, in many > discussions of web programming all the elements (and there are > many) are scattered and disconnected from the concrete steps one > needs to take to put them into working order. > > I recall that CherryPy has a little walk-through on how to get something > very simple working with it, and that's closer to what I'm recommending. > (Though obviously you're just answering bullet points in an email and > this is not your tutorial :D ). > > > > If you want it as a CGI program in Python its only slightly longer > > and the CGI documentation shows you how... > > Probably that's what I'm after, but my guess is the CGI documentation > is not particularly approachable (though haven't checked). A beginner > would also not know where "the" CGI documentation is. > > > > > - How you can get more than just text on a web app, that is, > > > widgets, and > > > therefore what are currently the options for that (learning > > > javascript and whatever > > > widget toolkits are out there for that; qooxdoo; Pyjamas; others). > > > > This is where it gets very complicated. > > And yet I think this what it's all about. When beginners think about > a web app (or dynamic web page as someone else here put it), they > don't think about HTML and text going back and forth to/from a server, > they think about widgets similar to widgets seen on the desktop > (calendars, buttons, textboxes, checkboxes, etc.). I was excited to > see the Quooxdoo widget set and heard it might be possible to use > it with a Python backend...via JSON (which I don't know about) but > it was too nebulous to motivate pursuing when I am still working on > learning desktop programming. > > > > > - How you can develop your web app on your own computer and when you > > > need to test it actually on the web. > > > > Thats usually just a case of running a web server on your PC. > > And that's its own topic. "Running a web server on your PC" rings zero > bells for beginners. > > > Wikipedia is your friend and the partial topic that I did on web > > programming did include some of the basic stuff with lots of > > links to Wikipedia articles. > > I don't think Wikipedia is the beginner's friend on this sort of thing. > I have not found it good for learning how to program. Just looking > at the topic "web development" shows this; it is an overview of the > field, but there is no instructional/tutorial material. It doesn't teach > how to do it. > > > HTH, > > It is helpful, and like anything one can probably work his or her way > through > the topic slowly and stumblingly, but I do think that a thorough > starting-with- > zero-knowledge-and-defining-all-terms tutorial would be a wonderful thing > to > have. As you said before, web programming is a lot more involved than > desktop programming. I think it would be really a fun challenge to put > together a great soup-to-nuts tutorial on this (but I am far from the one > to do it!), since it incorporates so many elements. I wish you luck on > the Py3 tutorial and and web app tutorial work when you have the chance. > > Thanks, > Che > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Atte: Carlos A. Guerrero M. -------------- next part -------------- An HTML attachment was scrubbed... URL: From quasipedia at gmail.com Tue Aug 3 11:28:12 2010 From: quasipedia at gmail.com (Mac Ryan) Date: Tue, 03 Aug 2010 11:28:12 +0200 Subject: [Tutor] Where to start with Unit Testing In-Reply-To: References: ,, ,, , ,<1280719842.3357.167.camel@jabbar> Message-ID: <1280827693.15805.139.camel@jabbar> On Mon, 2010-08-02 at 11:59 -0400, Che M wrote: > Mac, I found this an excellent brief overview of UT and your points > all > seem very strong to me. Thanks very much. I admit I didn't really > know > anything about the topic and was mentioning my feelings on the matter > partly to elicit enlightening responses like this (maybe because I was > feeling > like I was being irresponsible with my own project by not learning UT > and running tests). > > I am in the "hobbyist programmer busy on a simple one-off small app" > camp ("simple" is relative...though it is clearly nothing like a big > e-commerce application!), so I feel OK with foregoing getting into UT > for now. If things get more complex and I at some point have actual > users > instead of the large number of vapor users I have now (:D) I may > buckle > down and learn it. No worries than, I am happy my answer was of some use. Unit testing in python is however very very easy to use in a great number of situations, so don't be scared to get your hands dirty with it! A few days back I read this sentence: "Later than you expected, but sooner than you think" which in the context meant that we tend to over-estimate our abilities prior to start something new, but than - once we started working on it, we contrarily under-estimate our ability to achieve quickly a good level of performance... Happy learning! :) Mac. From wesbrooks at gmail.com Tue Aug 3 12:02:21 2010 From: wesbrooks at gmail.com (Wesley Brooks) Date: Tue, 3 Aug 2010 11:02:21 +0100 Subject: [Tutor] Maximum recursion depth problem. Message-ID: Dear Python Users, I'm having real difficulty understanding why the following is not working and hoped I've either missed something obvious of I'm doing something wrong! class A: def break_down(self, value, base, broken_list=[]): power = len(broken_list) digit = int((value % (base ** (power + 1))) / (base ** power)) value -= digit * (base**power) broken_list.append(digit) if value != 0: return self.break_down(value, base, broken_list=broken_list) else: return broken_list[:] if __name__ == '__main__': a = A() d_list_1 = a.break_down(34567, 256) print d_list_1 a2 = A() d_list_2 = a2.break_down(34567, 256) print d_list_2 When the above runs it fails with the error "RuntimeError: maximum recursion depth exceeded while calling a Python object". The following also does not work: if __name__ == '__main__': a = A() digit_list_1 = a.break_down(34567, 256) print digit_list_1 del digit_list_1, usc a2 = A() digit_list_2 = a2.break_down(34567, 256) print digit_list_2 but the following two do work: if __name__ == '__main__': a = A() digit_list_1 = a.break_down(34567, 256) print digit_list_1 #a2 = A() #digit_list_2 = a2.break_down(34567, 256) #print digit_list_2 if __name__ == '__main__': #a = A() #digit_list_1 = a.break_down(34567, 256) #print digit_list_1 a2 = A() digit_list_2 = a2.break_down(34567, 256) print digit_list_2 I'm a little stumped as I don't think I'm using any global or class variables? Any help would be much appreciated. Yours Faithfully, Wesley Brooks From wesbrooks at gmail.com Tue Aug 3 12:18:36 2010 From: wesbrooks at gmail.com (Wesley Brooks) Date: Tue, 3 Aug 2010 11:18:36 +0100 Subject: [Tutor] Maximum recursion depth problem. In-Reply-To: References: Message-ID: Ok a little more investigation has found the follwing work but there not as tidy. I'd still really appreciate someone explaing why this behaves like this! class A: def break_down(self, value, base, broken_list=[]): power = len(broken_list) digit = (value % (base ** (power + 1))) / (base ** power) value -= digit * (base**power) broken_list.append(digit) if value != 0: return self.break_down(value, base, broken_list=broken_list) else: return broken_list if __name__ == '__main__': a = A() d_list_1 = a.break_down(34567, 256, []) print d_list_1 a2 = A() d_list_2 = a2.break_down(34567, 256, []) print d_list_2 ......OR: class A: def break_down(self, value, base, broken_list=None): if broken_list == None: broken_list = [] power = len(broken_list) digit = (value % (base ** (power + 1))) / (base ** power) value -= digit * (base**power) broken_list.append(digit) if value != 0: return self.break_down(value, base, broken_list=broken_list) else: return broken_list if __name__ == '__main__': a = A() d_list_1 = a.break_down(34567, 256) print d_list_1 a2 = A() d_list_2 = a2.break_down(34567, 256) print d_list_2 Yours Faithfully, Wesley Brooks On 3 August 2010 11:02, Wesley Brooks wrote: > Dear Python Users, > > I'm having real difficulty understanding why the following is not > working and hoped I've either missed something obvious of I'm doing > something wrong! > > class A: > ? ?def break_down(self, value, base, broken_list=[]): > ? ? ? ?power = len(broken_list) > ? ? ? ?digit = int((value % (base ** (power + 1))) / (base ** power)) > ? ? ? ?value -= digit * (base**power) > ? ? ? ?broken_list.append(digit) > ? ? ? ?if value != 0: > ? ? ? ? ? ?return self.break_down(value, base, broken_list=broken_list) > ? ? ? ?else: > ? ? ? ? ? ?return broken_list[:] > > if __name__ == '__main__': > ? ?a = A() > ? ?d_list_1 = a.break_down(34567, 256) > ? ?print d_list_1 > ? ?a2 = A() > ? ?d_list_2 = a2.break_down(34567, 256) > ? ?print d_list_2 > > When the above runs it fails with the error "RuntimeError: maximum > recursion depth exceeded while calling a Python object". > > The following also does not work: > > if __name__ == '__main__': > ? ?a = A() > ? ?digit_list_1 = a.break_down(34567, 256) > ? ?print digit_list_1 > ? ?del digit_list_1, usc > ? ?a2 = A() > ? ?digit_list_2 = a2.break_down(34567, 256) > ? ?print digit_list_2 > > but the following two do work: > > if __name__ == '__main__': > ? ?a = A() > ? ?digit_list_1 = a.break_down(34567, 256) > ? ?print digit_list_1 > ? ?#a2 = A() > ? ?#digit_list_2 = a2.break_down(34567, 256) > ? ?#print digit_list_2 > > if __name__ == '__main__': > ? ?#a = A() > ? ?#digit_list_1 = a.break_down(34567, 256) > ? ?#print digit_list_1 > ? ?a2 = A() > ? ?digit_list_2 = a2.break_down(34567, 256) > ? ?print digit_list_2 > > I'm a little stumped as I don't think I'm using any global or class > variables? Any help would be much appreciated. > > Yours Faithfully, > > Wesley Brooks > From __peter__ at web.de Tue Aug 3 12:40:38 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 03 Aug 2010 12:40:38 +0200 Subject: [Tutor] Maximum recursion depth problem. References: Message-ID: Wesley Brooks wrote: > I'm having real difficulty understanding why the following is not > working and hoped I've either missed something obvious of I'm doing > something wrong! > > class A: > def break_down(self, value, base, broken_list=[]): > I'm a little stumped as I don't think I'm using any global or class > variables? Any help would be much appreciated. You are on the right track, the default value for broken_list is evaluated only once; Modifications during an invocation of the break_down() method are visible when break_down() is called again later. See also http://docs.python.org/faq/design.html#why-are-default-values-shared-between-objects Peter From wesbrooks at gmail.com Tue Aug 3 12:48:41 2010 From: wesbrooks at gmail.com (Wesley Brooks) Date: Tue, 3 Aug 2010 11:48:41 +0100 Subject: [Tutor] Maximum recursion depth problem. In-Reply-To: References: Message-ID: Morning Peter, Thanks, that was something I was unaware of! Not sure how I hadn't bumped into that before! Cheers, Wesley. On 3 August 2010 11:40, Peter Otten <__peter__ at web.de> wrote: > Wesley Brooks wrote: > >> I'm having real difficulty understanding why the following is not >> working and hoped I've either missed something obvious of I'm doing >> something wrong! >> >> class A: >> ? ? def break_down(self, value, base, broken_list=[]): > >> I'm a little stumped as I don't think I'm using any global or class >> variables? Any help would be much appreciated. > > You are on the right track, the default value for broken_list is > evaluated only once; Modifications during an invocation of the > break_down() method are visible when break_down() is called again later. > > See also > > http://docs.python.org/faq/design.html#why-are-default-values-shared-between-objects > > Peter > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From alex.baraibar at gmail.com Tue Aug 3 14:22:32 2010 From: alex.baraibar at gmail.com (Alex Baraibar) Date: Tue, 3 Aug 2010 14:22:32 +0200 Subject: [Tutor] Conflict with encoding in console view and file dump Message-ID: Hi, Peter. Sorry for the delay, I've been out for a while. So I did what you suggested and it prints the following: " import sys print >> sys.stderr, sys.stdout.encoding what does the above print (a) when you print to the console? it prints cp850 (b) when you redirect to a file? it prints None " Any suggestions? Thanx for your time. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Aug 3 17:04:14 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 4 Aug 2010 01:04:14 +1000 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: References: <201008030957.14180.steve@pearwood.info> Message-ID: <201008040104.15411.steve@pearwood.info> On Tue, 3 Aug 2010 10:52:27 am Richard D. Moores wrote: > On Mon, Aug 2, 2010 at 16:57, Steven D'Aprano wrote: > > ?# File *probably* doesn't exist. Consider better error checking. > > Steve, before I dig into your detailed reply, please tell me what you > meant by " # File *probably* doesn't exist. Consider better error > checking.". open(pathname) will fail with an IOError for many reasons. It could be that the file simply doesn't exist, so it can't be opened. It could be that you don't have read permission, or that the disk is corrupt and even though you have permission to open the file, attempting to do so fails. For a simple script, it's acceptable to assume that the likely reason for IOError is that the file isn't there, and therefore creating it will solve the problem. But for a more solid program, you should inspect the exception to determine the error code, and then take appropriate action. -- Steven D'Aprano From __peter__ at web.de Tue Aug 3 18:29:33 2010 From: __peter__ at web.de (Peter Otten) Date: Tue, 03 Aug 2010 18:29:33 +0200 Subject: [Tutor] Conflict with encoding in console view and file dump References: Message-ID: Alex Baraibar wrote: > Hi, Peter. > Sorry for the delay, I've been out for a while. > So I did what you suggested and it prints the following: > > " > import sys > print >> sys.stderr, sys.stdout.encoding > > what does the above print > (a) when you print to the console? it prints cp850 > (b) when you redirect to a file? it prints None That's as expected. You should normally get an exception like Traceback (most recent call last): File "tmp_enc.py", line 33, in print element UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in position 11: ordinal not in range(128) when you redirect your script's output to a file. Did you change the default encoding? If you didn't you probably have an ill- behaved application on your system that did it without asking. > Any suggestions? Check stdout.encoding, and if it is None (unknown encoding) wrap the stdout stream into a Writer. Your script with that modification: # -*- coding: cp1252 -*- def festivos(): fest = [ 'Any Nou:\t\t\t1 de enero', 'Reis:\t\t\t\t6 de enero', 'Festa del Treball:\t\t1 de mayo', 'Sant Joan:\t\t\t24 de junio', u'La Assumpci?:\t\t\t15 de agosto', 'La Diada:\t\t\t11 de septiembre', u'La Merc?:\t\t\t24 de septiembre', 'La Hispanitat:\t\t\t12 de octubre', 'Tots Sants:\t\t\t1 de novembre', u'La Constituci?:\t\t\t6 de desembre', u'La Concepci?:\t\t\t8 de desembre', 'Nadal:\t\t\t\t25 de desembre', 'Sant Esteve:\t\t\t26 de desembre' ] return fest def separador( num, char ): return char * num # --- Main --- import sys if sys.stdout.encoding is None: import codecs Writer = codecs.getwriter("latin-1") sys.stdout = Writer(sys.stdout) dias = festivos() print "Los festivos fijos anuales son:\n" for element in dias: sep = separador( 50, '-' ) # move that out of the loop print element print sep Peter From rdmoores at gmail.com Wed Aug 4 01:37:33 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Tue, 3 Aug 2010 16:37:33 -0700 Subject: [Tutor] How to get script to detect whether a file exists? In-Reply-To: <201008040104.15411.steve@pearwood.info> References: <201008030957.14180.steve@pearwood.info> <201008040104.15411.steve@pearwood.info> Message-ID: On Tue, Aug 3, 2010 at 08:04, Steven D'Aprano wrote: > On Tue, 3 Aug 2010 10:52:27 am Richard D. Moores wrote: >> On Mon, Aug 2, 2010 at 16:57, Steven D'Aprano > wrote: >> > ?# File *probably* doesn't exist. Consider better error checking. >> >> Steve, before I dig into your detailed reply, please tell me what you >> meant by " # File *probably* doesn't exist. Consider better error >> checking.". > > open(pathname) will fail with an IOError for many reasons. It could be > that the file simply doesn't exist, so it can't be opened. It could be > that you don't have read permission, or that the disk is corrupt and > even though you have permission to open the file, attempting to do so > fails. > > For a simple script, it's acceptable to assume that the likely reason > for IOError is that the file isn't there, and therefore creating it > will solve the problem. But for a more solid program, you should > inspect the exception to determine the error code, and then take > appropriate action. Ah. Got it. Thanks, Steven. Dick From nathan.farrar at gmail.com Wed Aug 4 06:48:50 2010 From: nathan.farrar at gmail.com (Nathan Farrar) Date: Tue, 3 Aug 2010 22:48:50 -0600 Subject: [Tutor] Simple Python Telnet Client (Help with Asynchronous IO) Message-ID: Hello All, I'm attempting to write a simple telnet client. Yes, I've been told that I should be using twisted to do this. I want to learn to do it myself first, so that I can fully understand the concepts - then I will scrap it and switch to using twisted. When I started, I didn't realize there was such a thing as blocking IO. I assumed that if I put the read/write calls for stdio & the socket in different threads all would be good. I've been told that this is not the case and that if I perform a blocking IO call in a thread (such as sys.stdin.read()) it will halt the execution of all threads in the process. I found an example that uses the select module to see if any data is available from stdin before attempting to read ... and that this is the asynchronous/non-blocking way to do it. I've implemented this code, but I can't figure out a similar way to do this with the socket. Here's the code I've put together so far: #!/usr/bin/env python import collections import os import select import socket import sys import termios import tty import threading class InputThread(threading.Thread): """ Read data from the stdin and place in the input buffer. """ def __init__(self, input_buffer): threading.Thread.__init__(self) self.input_buffer = input_buffer def run(self): self.old_settings = termios.tcgetattr(sys.stdin) tty.setcbreak(sys.stdin.fileno()) # prompt loop try: while True: if select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []): self.input_buffer.append(sys.stdin.read()) print "> " finally: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings) class DisplayThread(threading.Thread): """ Check ouput buffer for data. Print and data and flush buffer. """ def __init__(self, output_buffer): threading.Thread.__init__(self) self.output_buffer = output_buffer def run(self): while True: while len(self.output_buffer) > 0: output_data = self.output_buffer.pop() print output_data, class SocketThread(threading.Thread): """ Check input buffer. If data exists, send it to socket. Read any incoming data from socket and place it in output buffer. """ def __init__(self, input_buffer, output_buffer): threading.Thread.__init__(self) self.input_buffer = input_buffer self.output_buffer = output_buffer def run(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setblocking(1) self.socket.connect(('nannymud.lysator.liu.se',2000)) while True: while len(self.input_buffer) > 0: input_data = self.input_buffer.pop() self.socket.send(input_data, '\n') self.output_buffer.append(self.socket.recv(1024)) self.sock.close() def main(): """ Interactive, multithreaded network client written in python. """ print "Use 'quit' to exit client." input_buffer = collections.deque() output_buffer = collections.deque(); input_thread = InputThread(input_buffer) input_thread.start() display_thread = DisplayThread(output_buffer) display_thread.start() socket_thread = SocketThread(input_buffer, output_buffer) socket_thread.start() if __name__ == '__main__': main() Help sorting this out so that I can fully understand the concepts and get this working would be greatly appreciated. As I mentioned previously, I am fully planning on scrapping this and rewriting it using twisted once I understand the concepts and have a working prototype. Thank you! - F4RR4R -- Science replaces private prejudice with publicly verifiable evidence. - Richard Dawkins -------------- next part -------------- An HTML attachment was scrubbed... URL: From alex.baraibar at gmail.com Wed Aug 4 09:09:59 2010 From: alex.baraibar at gmail.com (Alex Baraibar) Date: Wed, 4 Aug 2010 09:09:59 +0200 Subject: [Tutor] Conflict with encoding in console view and file dump Message-ID: Hello, Peter. I checked my sys.stdout.encoding and it prints: >>> import sys >>> sys.stdout.encoding 'cp1252' Sometimes IDLE tells me I'm using characters that might not work if I don't place this at the beginning of my script: # -*- coding: cp1252 -*- Other than that, I have not made any changes to the default installation. Anyway, the modifications you made seem to work fine, so the problem appears to be solved. I just wish I understood better what happened and why. I've looked into the Unicode section of the official docs, but I probably need to study it more in order to fully understand it, so... I appreciate your help, thanx again. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Aug 4 13:32:31 2010 From: __peter__ at web.de (Peter Otten) Date: Wed, 04 Aug 2010 13:32:31 +0200 Subject: [Tutor] Conflict with encoding in console view and file dump References: Message-ID: Alex Baraibar wrote: > I just wish I understood better what happened and why. I've looked into > the Unicode section of the official docs, but I probably need to study it > more in order to fully understand it, so... Just in case you didn't come across it, there's a howto that covers the basics: http://docs.python.org/howto/unicode Peter From mehgcap at gmail.com Wed Aug 4 16:37:11 2010 From: mehgcap at gmail.com (Alex Hall) Date: Wed, 4 Aug 2010 10:37:11 -0400 Subject: [Tutor] how to get str() to use my function? Message-ID: Hi all, I have a card class. A card object simply consists of a pair of numbers; 0,0 might be the ace of clubs, for example. I have a toString method in my card class. Is there a way to just say str(card) instead of card.toString()? Maybe some sort of basic, built-in function to override? TIA. Oh, what about doing the same with operators? For example, could I get the program to call my own math functions when it sees a card object in a math expression, like if(card1==card2) -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From prologic at shortcircuit.net.au Wed Aug 4 16:46:51 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 5 Aug 2010 00:46:51 +1000 Subject: [Tutor] how to get str() to use my function? In-Reply-To: References: Message-ID: On Thu, Aug 5, 2010 at 12:37 AM, Alex Hall wrote: > Hi all, > I have a card class. A card object simply consists of a pair of > numbers; 0,0 might be the ace of clubs, for example. I have a toString > method in my card class. Is there a way to just say str(card) instead > of card.toString()? Maybe some sort of basic, built-in function to > override? TIA. Oh, what about doing the same with operators? For > example, could I get the program to call my own math functions when it > sees a card object in a math expression, like > if(card1==card2) implement a __str__ method. For example: $ python Python 2.6.5 (r265:79063, Jun 13 2010, 14:03:16) [GCC 4.4.4 (CRUX)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Foo(object): ... def __str__(self): ... return "" ... >>> foo = Foo() >>> foo <__main__.Foo object at 0x83d796c> >>> str(foo) '' >>> cheers James -- -- James Mills -- -- "Problems are solved by method" From huyslogic at gmail.com Wed Aug 4 16:49:08 2010 From: huyslogic at gmail.com (Huy Ton That) Date: Wed, 4 Aug 2010 10:49:08 -0400 Subject: [Tutor] how to get str() to use my function? In-Reply-To: References: Message-ID: You could write __str__ function >>> class card(object): ... def __init__(self, card1, card2): ... self.card1, self.card2 = card1, card2 ... def __str__(self): ... return str(str(self.card1)+','+str(self.card2)) ... >>> a = card(0,0) >>> str(a) '0,0' On Wed, Aug 4, 2010 at 10:37 AM, Alex Hall wrote: > Hi all, > I have a card class. A card object simply consists of a pair of > numbers; 0,0 might be the ace of clubs, for example. I have a toString > method in my card class. Is there a way to just say str(card) instead > of card.toString()? Maybe some sort of basic, built-in function to > override? TIA. Oh, what about doing the same with operators? For > example, could I get the program to call my own math functions when it > sees a card object in a math expression, like > if(card1==card2) > > -- > Have a great day, > Alex (msg sent from GMail website) > mehgcap at gmail.com; http://www.facebook.com/mehgcap > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Wed Aug 4 17:37:34 2010 From: mehgcap at gmail.com (Alex Hall) Date: Wed, 4 Aug 2010 11:37:34 -0400 Subject: [Tutor] how to get str() to use my function? In-Reply-To: References: Message-ID: It worked, thanks. Is there a list of these functions somewhere? That is, the functions that map implicitly to operators or implied uses? For example, printing will call __str__, as will a cal to str(). What about math or comparison operators? I have heard of __eq__, __gt__, and so on, but I tried to implement one and I got an error saying that it required three arguments. It did, but only because the first was self. I put the function inside my card class: def __eq__(self, card1, card2): return(card1.rank==card2.rank) #end def __eq__ For some reason it is still looking for three arguments... On 8/4/10, Huy Ton That wrote: > You could write __str__ function > >>>> class card(object): > ... def __init__(self, card1, card2): > ... self.card1, self.card2 = card1, card2 > ... def __str__(self): > ... return str(str(self.card1)+','+str(self.card2)) > ... >>>> a = card(0,0) >>>> str(a) > '0,0' > > On Wed, Aug 4, 2010 at 10:37 AM, Alex Hall wrote: > >> Hi all, >> I have a card class. A card object simply consists of a pair of >> numbers; 0,0 might be the ace of clubs, for example. I have a toString >> method in my card class. Is there a way to just say str(card) instead >> of card.toString()? Maybe some sort of basic, built-in function to >> override? TIA. Oh, what about doing the same with operators? For >> example, could I get the program to call my own math functions when it >> sees a card object in a math expression, like >> if(card1==card2) >> >> -- >> Have a great day, >> Alex (msg sent from GMail website) >> mehgcap at gmail.com; http://www.facebook.com/mehgcap >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From knacktus at googlemail.com Wed Aug 4 17:55:47 2010 From: knacktus at googlemail.com (Knacktus) Date: Wed, 04 Aug 2010 17:55:47 +0200 Subject: [Tutor] how to get str() to use my function? In-Reply-To: References: Message-ID: <4C598D83.404@googlemail.com> Am 04.08.2010 17:37, schrieb Alex Hall: > It worked, thanks. Is there a list of these functions somewhere? That > is, the functions that map implicitly to operators or implied uses? > For example, printing will call __str__, as will a cal to str(). What > about math or comparison operators? I have heard of __eq__, __gt__, > and so on, but I tried to implement one and I got an error saying that > it required three arguments. It did, but only because the first was > self. I put the function inside my card class: > def __eq__(self, card1, card2): > return(card1.rank==card2.rank) > #end def __eq__ > For some reason it is still looking for three arguments... > > The official list of all special methods can be found at the datamodel description, chapter 3.4: http://docs.python.org/reference/datamodel.html#special-method-names Most Python books also have some explanations about this. Maybe the nice online book "Dive into Python" has a chapter? (I didn't check...) Regarding your problem: I've flew very fast over the docs. __eq__ seems to expect two arguments (self, other). So probably your method of the card class should look like: def __eq__(self, card2): return(self.rank==card2.rank) Cheers, Jan From huyslogic at gmail.com Wed Aug 4 17:58:34 2010 From: huyslogic at gmail.com (Huy Ton That) Date: Wed, 4 Aug 2010 11:58:34 -0400 Subject: [Tutor] how to get str() to use my function? In-Reply-To: References: Message-ID: These are special method names. View section 3.4 and below here http://docs.python.org/reference/datamodel.html On Wed, Aug 4, 2010 at 11:37 AM, Alex Hall wrote: > It worked, thanks. Is there a list of these functions somewhere? That > is, the functions that map implicitly to operators or implied uses? > For example, printing will call __str__, as will a cal to str(). What > about math or comparison operators? I have heard of __eq__, __gt__, > and so on, but I tried to implement one and I got an error saying that > it required three arguments. It did, but only because the first was > self. I put the function inside my card class: > def __eq__(self, card1, card2): > return(card1.rank==card2.rank) > #end def __eq__ > For some reason it is still looking for three arguments... > > > On 8/4/10, Huy Ton That wrote: > > You could write __str__ function > > > >>>> class card(object): > > ... def __init__(self, card1, card2): > > ... self.card1, self.card2 = card1, card2 > > ... def __str__(self): > > ... return str(str(self.card1)+','+str(self.card2)) > > ... > >>>> a = card(0,0) > >>>> str(a) > > '0,0' > > > > On Wed, Aug 4, 2010 at 10:37 AM, Alex Hall wrote: > > > >> Hi all, > >> I have a card class. A card object simply consists of a pair of > >> numbers; 0,0 might be the ace of clubs, for example. I have a toString > >> method in my card class. Is there a way to just say str(card) instead > >> of card.toString()? Maybe some sort of basic, built-in function to > >> override? TIA. Oh, what about doing the same with operators? For > >> example, could I get the program to call my own math functions when it > >> sees a card object in a math expression, like > >> if(card1==card2) > >> > >> -- > >> Have a great day, > >> Alex (msg sent from GMail website) > >> mehgcap at gmail.com; http://www.facebook.com/mehgcap > >> _______________________________________________ > >> Tutor maillist - Tutor at python.org > >> To unsubscribe or change subscription options: > >> http://mail.python.org/mailman/listinfo/tutor > >> > > > > > -- > Have a great day, > Alex (msg sent from GMail website) > mehgcap at gmail.com; http://www.facebook.com/mehgcap > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Wed Aug 4 18:11:04 2010 From: mehgcap at gmail.com (Alex Hall) Date: Wed, 4 Aug 2010 12:11:04 -0400 Subject: [Tutor] how to get str() to use my function? In-Reply-To: References: Message-ID: Thanks, and I also see what I did wrong with my __eq__ function. On 8/4/10, Huy Ton That wrote: > These are special method names. > > View section 3.4 and below here > > http://docs.python.org/reference/datamodel.html > > On Wed, Aug 4, 2010 at 11:37 AM, Alex Hall wrote: > >> It worked, thanks. Is there a list of these functions somewhere? That >> is, the functions that map implicitly to operators or implied uses? >> For example, printing will call __str__, as will a cal to str(). What >> about math or comparison operators? I have heard of __eq__, __gt__, >> and so on, but I tried to implement one and I got an error saying that >> it required three arguments. It did, but only because the first was >> self. I put the function inside my card class: >> def __eq__(self, card1, card2): >> return(card1.rank==card2.rank) >> #end def __eq__ >> For some reason it is still looking for three arguments... >> >> >> On 8/4/10, Huy Ton That wrote: >> > You could write __str__ function >> > >> >>>> class card(object): >> > ... def __init__(self, card1, card2): >> > ... self.card1, self.card2 = card1, card2 >> > ... def __str__(self): >> > ... return str(str(self.card1)+','+str(self.card2)) >> > ... >> >>>> a = card(0,0) >> >>>> str(a) >> > '0,0' >> > >> > On Wed, Aug 4, 2010 at 10:37 AM, Alex Hall wrote: >> > >> >> Hi all, >> >> I have a card class. A card object simply consists of a pair of >> >> numbers; 0,0 might be the ace of clubs, for example. I have a toString >> >> method in my card class. Is there a way to just say str(card) instead >> >> of card.toString()? Maybe some sort of basic, built-in function to >> >> override? TIA. Oh, what about doing the same with operators? For >> >> example, could I get the program to call my own math functions when it >> >> sees a card object in a math expression, like >> >> if(card1==card2) >> >> >> >> -- >> >> Have a great day, >> >> Alex (msg sent from GMail website) >> >> mehgcap at gmail.com; http://www.facebook.com/mehgcap >> >> _______________________________________________ >> >> Tutor maillist - Tutor at python.org >> >> To unsubscribe or change subscription options: >> >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > >> >> >> -- >> Have a great day, >> Alex (msg sent from GMail website) >> mehgcap at gmail.com; http://www.facebook.com/mehgcap >> > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From pkoek11 at xs4all.nl Wed Aug 4 19:23:13 2010 From: pkoek11 at xs4all.nl (Pete) Date: Wed, 4 Aug 2010 13:23:13 -0400 Subject: [Tutor] getattr() Message-ID: <3502A2E1-994D-47E4-BA7E-28C5AF06348E@xs4all.nl> Hi, I'm trying to understand the syntax for reflection in python. I was wondering about this. From the example on diveintopython: http://diveintopython.org/power_of_introspection/index.html import statsout def output(data, format="text"): output_function = getattr(statsout, "output_%s" % format, statsout.output_text) return output_function(data) I was wondering about how to make this work if the function that you are trying to call is not in a module. Is that possible? Something like this: def output_text(data): return_value = "This is text: " + data return return_value def output(data, format="text"): output_function = getattr(*****, "output_%s" % format, statsout.output_text) return output_function(data) What I can't figure out is what to put in place of *****. I've tried globals()['__name__'], in various forms, to no avail. Any pointers would be appreciated. thanks, Pete -------------- next part -------------- An HTML attachment was scrubbed... URL: From eduardo.susan at gmail.com Wed Aug 4 20:30:25 2010 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Wed, 4 Aug 2010 12:30:25 -0600 Subject: [Tutor] Formatting date/time Message-ID: I'm trying this example from python docs: from time import gmtime, strftime strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) Output = 'Wed, 04 Aug 2010 17:58:42 +0000' Is not there a string formatting option for the day without a leading zero? Like: 'Wed, 4 Aug 2010 17:58:42 +0000' It looks like it's not in the docs. Thanks Eduardo From ehamiter at gmail.com Wed Aug 4 20:45:20 2010 From: ehamiter at gmail.com (Eric Hamiter) Date: Wed, 4 Aug 2010 13:45:20 -0500 Subject: [Tutor] Formatting date/time In-Reply-To: References: Message-ID: There are a few solutions here: http://stackoverflow.com/questions/904928/python-strftime-date-decimal-remove-0 Eric On Wed, Aug 4, 2010 at 1:30 PM, Eduardo Vieira wrote: > I'm trying this example from python docs: > from time import gmtime, strftime > strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) > > Output = 'Wed, 04 Aug 2010 17:58:42 +0000' > Is not there a string formatting option for the day without a leading > zero? Like: 'Wed, 4 Aug 2010 17:58:42 +0000' > > It looks like it's not in the docs. > > Thanks > > Eduardo > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pkoek11 at xs4all.nl Wed Aug 4 21:18:32 2010 From: pkoek11 at xs4all.nl (Pete) Date: Wed, 4 Aug 2010 15:18:32 -0400 Subject: [Tutor] getattr() In-Reply-To: References: <3502A2E1-994D-47E4-BA7E-28C5AF06348E@xs4all.nl> Message-ID: Hey Huy, thanks. But what is the first parameter in this case? (Note there is nothing here I'm trying to accomplish except understand). In the original example, 'statsout' is the name of the module. In this case there is no module so why can you substitute 'output_text'? thanks, Pete On 2010-08-04, at 3:09 PM, Huy Ton That wrote: > If it is in the same code, and the namespace isn't a module or another class you could do this: > > def output_text(data): > return_value = "This is text: " + data > return return_value > > def output(data, format="text"): > output_function = getattr(output_text, "output_%s" % format, output_text) > return output_function(data) > > -HTH > > Huy > > On Wed, Aug 4, 2010 at 1:23 PM, Pete wrote: > Hi, > > I'm trying to understand the syntax for reflection in python. I was wondering about this. > > From the example on diveintopython: > > http://diveintopython.org/power_of_introspection/index.html > > > import statsout > > def output(data, format="text"): > output_function = getattr(statsout, "output_%s" % format, statsout.output_text) > return output_function(data) > > > I was wondering about how to make this work if the function that you are trying to call is not in a module. Is that possible? > > Something like this: > > > def output_text(data): > > return_value = "This is text: " + data > return return_value > > > > def output(data, format="text"): > output_function = getattr(*****, "output_%s" % format, statsout.output_text) > return output_function(data) > > What I can't figure out is what to put in place of *****. I've tried globals()['__name__'], in various forms, to no avail. > > Any pointers would be appreciated. > > thanks, > > Pete > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Wed Aug 4 21:23:35 2010 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 4 Aug 2010 15:23:35 -0400 Subject: [Tutor] Formatting date/time In-Reply-To: References: Message-ID: On Wed, Aug 4, 2010 at 2:45 PM, Eric Hamiter wrote: > There are a few solutions here: > > > http://stackoverflow.com/questions/904928/python-strftime-date-decimal-remove-0 > > Eric > > > > On Wed, Aug 4, 2010 at 1:30 PM, Eduardo Vieira wrote: > >> I'm trying this example from python docs: >> from time import gmtime, strftime >> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) >> >> Output = 'Wed, 04 Aug 2010 17:58:42 +0000' >> Is not there a string formatting option for the day without a leading >> zero? Like: 'Wed, 4 Aug 2010 17:58:42 +0000' >> >> It looks like it's not in the docs. >> >> Thanks >> >> Eduardo >> > %e worked for me on Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From huyslogic at gmail.com Wed Aug 4 21:30:56 2010 From: huyslogic at gmail.com (Huy Ton That) Date: Wed, 4 Aug 2010 15:30:56 -0400 Subject: [Tutor] getattr() In-Reply-To: References: <3502A2E1-994D-47E4-BA7E-28C5AF06348E@xs4all.nl> Message-ID: *You can do like below Pete. Where globals has a reference to all functions in this space.* def output(data, format="text"): output_function = getattr(globals()['FUNCTION'], "output_%s" % format, statsout.output_text) return output_function(data) On Wed, Aug 4, 2010 at 3:18 PM, Pete wrote: > Hey Huy, > > thanks. But what is the first parameter in this case? (Note there is > nothing here I'm trying to accomplish except understand). > > In the original example, 'statsout' is the name of the module. In this case > there is no module so why can you substitute 'output_text'? > > thanks, > > Pete > > On 2010-08-04, at 3:09 PM, Huy Ton That wrote: > > If it is in the same code, and the namespace isn't a module or another > class you could do this: > > def output_text(data): > return_value = "This is text: " + data > return return_value > > def output(data, format="text"): > output_function = getattr(output_text, "output_%s" % format, > output_text) > return output_function(data) > > -HTH > > Huy > > On Wed, Aug 4, 2010 at 1:23 PM, Pete wrote: > >> Hi, >> >> I'm trying to understand the syntax for reflection in python. I was >> wondering about this. >> >> From the example on diveintopython: >> >> http://diveintopython.org/power_of_introspection/index.html >> >> import statsout >> def output(data, format="text"): >> output_function = getattr(statsout, "output_%s" % format, statsout.output_text) >> return output_function(data) >> >> >> I was wondering about how to make this work if the function that you are >> trying to call is not in a module. Is that possible? >> >> Something like this: >> >> def output_text(data): >> >> >> return_value = "This is text: " + data >> return return_value >> >> >> def output(data, format="text"): >> output_function = getattr(*****, "output_%s" % format, statsout.output_text) >> return output_function(data) >> >> >> What I can't figure out is what to put in place of *****. I've tried >> globals()['__name__'], in various forms, to no avail. >> >> Any pointers would be appreciated. >> >> thanks, >> >> Pete >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Aug 4 21:32:39 2010 From: bgailer at gmail.com (bob gailer) Date: Wed, 04 Aug 2010 15:32:39 -0400 Subject: [Tutor] getattr() In-Reply-To: <3502A2E1-994D-47E4-BA7E-28C5AF06348E@xs4all.nl> References: <3502A2E1-994D-47E4-BA7E-28C5AF06348E@xs4all.nl> Message-ID: <4C59C057.7030705@gmail.com> On 8/4/2010 1:23 PM, Pete wrote: > Hi, > > I'm trying to understand the syntax for reflection in python. I was > wondering about this. > > From the example on diveintopython: > > http://diveintopython.org/power_of_introspection/index.html > > import statsout > > def output(data, format="text"): > output_function = getattr(statsout,"output_%s" % format, statsout.output_text) > return output_function(data) > > I was wondering about how to make this work if the function that you > are trying to call is not in a module. Everything in Python is in a module. I suspect you mean not in an imported module, e.g. in the main module. Whose __name__ is '__main__'. A reference to the main module can be found: import sys main = sys.modules['__main__'] > Is that possible? > > Something like this: > > def output_text(data): > return_value = "This is text: " + data > return return_value > > def output(data, format="text"): > output_function = getattr(*****,"output_%s" % format, statsout.output_text) > return output_function(data) > > What I can't figure out is what to put in place of *****. I've tried > globals()['__name__'], in various forms, to no avail. Replace those stars with main as derived above. globals()['output_text'] will also give you a reference to the function. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From huyslogic at gmail.com Wed Aug 4 21:44:22 2010 From: huyslogic at gmail.com (Huy Ton That) Date: Wed, 4 Aug 2010 15:44:22 -0400 Subject: [Tutor] getattr() In-Reply-To: <4C59C057.7030705@gmail.com> References: <3502A2E1-994D-47E4-BA7E-28C5AF06348E@xs4all.nl> <4C59C057.7030705@gmail.com> Message-ID: Oh, that's right, I should have tried to example in the interpreter instead of in my head:P Say Bob, Is that the preferred method over something like: >>> import __main__ as main On Wed, Aug 4, 2010 at 3:32 PM, bob gailer wrote: > On 8/4/2010 1:23 PM, Pete wrote: > > Hi, > > I'm trying to understand the syntax for reflection in python. I was > wondering about this. > > From the example on diveintopython: > > http://diveintopython.org/power_of_introspection/index.html > > import statsout > def output(data, format="text"): > output_function = getattr(statsout, "output_%s" % format, statsout.output_text) > return output_function(data) > > I was wondering about how to make this work if the function that you > are trying to call is not in a module. > > > Everything in Python is in a module. I suspect you mean not in an imported > module, e.g. in the main module. Whose __name__ is '__main__'. A reference > to the main module can be found: > > import sys > main = sys.modules['__main__'] > > Is that possible? > > Something like this: > > def output_text(data): > > return_value = "This is text: " + data > return return_value > > def output(data, format="text"): > output_function = getattr(*****, "output_%s" % format, statsout.output_text) > return output_function(data) > > > What I can't figure out is what to put in place of *****. I've tried > globals()['__name__'], in various forms, to no avail. > > > Replace those stars with main as derived above. > > globals()['output_text'] will also give you a reference to the function. > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Aug 4 22:04:52 2010 From: bgailer at gmail.com (bob gailer) Date: Wed, 04 Aug 2010 16:04:52 -0400 Subject: [Tutor] getattr() In-Reply-To: References: <3502A2E1-994D-47E4-BA7E-28C5AF06348E@xs4all.nl> <4C59C057.7030705@gmail.com> Message-ID: <4C59C7E4.5090906@gmail.com> On 8/4/2010 3:44 PM, Huy Ton That wrote: > Oh, that's right, I should have tried to example in the interpreter > instead of in my head:P > > Say Bob, > > Is that the preferred method over something like: I would prefer to create a class and make these functions class methods. class A: def output_text(self, data):return data def output_hex(self, data):return '\\x' + data def __getattr__(self, name): return self.output_text a = A() data='bar' print a.output_text(data) print a.output_hex(data) print a.foo(data) -- Bob Gailer 919-636-4239 Chapel Hill NC From eduardo.susan at gmail.com Wed Aug 4 22:07:13 2010 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Wed, 4 Aug 2010 14:07:13 -0600 Subject: [Tutor] Formatting date/time In-Reply-To: References: Message-ID: On Wed, Aug 4, 2010 at 12:45 PM, Eric Hamiter wrote: > There are a few solutions here: > > http://stackoverflow.com/questions/904928/python-strftime-date-decimal-remove-0 > > Eric > > > On Wed, Aug 4, 2010 at 1:30 PM, Eduardo Vieira > wrote: >> >> I'm trying this example from python docs: >> from time import gmtime, strftime >> strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) >> >> Output = 'Wed, 04 Aug 2010 17:58:42 +0000' >> Is not there a string formatting option for the day without a leading >> zero? Like: 'Wed, 4 Aug 2010 17:58:42 +0000' >> >> It looks like it's not in the docs. >> >> Thanks >> >> Eduardo >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > Thank you for the link. Just what I needed to know. The option %e didn't work for me, but I will use the other suggestions in the answers. Eduardo From bgailer at gmail.com Wed Aug 4 22:08:42 2010 From: bgailer at gmail.com (bob gailer) Date: Wed, 04 Aug 2010 16:08:42 -0400 Subject: [Tutor] getattr() In-Reply-To: <4C59C7E4.5090906@gmail.com> References: <3502A2E1-994D-47E4-BA7E-28C5AF06348E@xs4all.nl> <4C59C057.7030705@gmail.com> <4C59C7E4.5090906@gmail.com> Message-ID: <4C59C8CA.8040709@gmail.com> On 8/4/2010 4:04 PM, bob gailer wrote: > On 8/4/2010 3:44 PM, Huy Ton That wrote: >> Oh, that's right, I should have tried to example in the interpreter >> instead of in my head:P >> >> Say Bob, >> >> Is that the preferred method over something like: > > I would prefer to create a class and make these functions class methods. > > class A: > def output_text(self, data):return data > def output_hex(self, data):return '\\x' + data > def __getattr__(self, name): > return self.output_text > a = A() > data='bar' > print a.output_text(data) > print a.output_hex(data) > print a.foo(data) > I just realized my answer does not accomodate your looking for the function by name. Please stand by.... -- Bob Gailer 919-636-4239 Chapel Hill NC From mehgcap at gmail.com Wed Aug 4 22:17:31 2010 From: mehgcap at gmail.com (Alex Hall) Date: Wed, 4 Aug 2010 16:17:31 -0400 Subject: [Tutor] access class through indexing? Message-ID: Hi all, Further to my questions about overriding builtin methods earlier, how would I make a class able to be accessed and changed using index notation? For example, take the following: deck=CardPile(52) #creates a new deck of cards print(len(deck)) #prints 52, thanks to my __len__ function for c in deck: print c #also works thanks to __iter__ print(deck[4]) #fails with a list index out of range error How would I get the last one working? I tried __getattr__(self, i), but it did not work. I want to be able to get an arbitrary item from the "pile" of cards (which can be a deck, a hand, whatever), and/or set an element. A "pile" is just a list of Card objects, so I would only need to use sequence indexing, not mapping functions. -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From evert.rol at gmail.com Wed Aug 4 22:31:20 2010 From: evert.rol at gmail.com (Evert Rol) Date: Wed, 4 Aug 2010 22:31:20 +0200 Subject: [Tutor] access class through indexing? In-Reply-To: References: Message-ID: > Hi all, > Further to my questions about overriding builtin methods earlier, how > would I make a class able to be accessed and changed using index > notation? For example, take the following: > deck=CardPile(52) #creates a new deck of cards > print(len(deck)) #prints 52, thanks to my __len__ function > for c in deck: print c #also works thanks to __iter__ > print(deck[4]) #fails with a list index out of range error > How would I get the last one working? I tried __getattr__(self, i), > but it did not work. I want to be able to get an arbitrary item from > the "pile" of cards (which can be a deck, a hand, whatever), and/or > set an element. A "pile" is just a list of Card objects, so I would > only need to use sequence indexing, not mapping functions. If you want most or all of the things that lists implement, and you feel in general that CardPile is really an advanced/augmented list, just let CardPile inherit from list: class CardPile(list). I would think that should work for what you want. Evert From huyslogic at gmail.com Wed Aug 4 22:32:02 2010 From: huyslogic at gmail.com (Huy Ton That) Date: Wed, 4 Aug 2010 16:32:02 -0400 Subject: [Tutor] getattr() In-Reply-To: <4C59C8CA.8040709@gmail.com> References: <3502A2E1-994D-47E4-BA7E-28C5AF06348E@xs4all.nl> <4C59C057.7030705@gmail.com> <4C59C7E4.5090906@gmail.com> <4C59C8CA.8040709@gmail.com> Message-ID: I have a side question, I am using python 2.7. Why do you use class A: instead of class A(object): ? -Huy On Wed, Aug 4, 2010 at 4:08 PM, bob gailer wrote: > On 8/4/2010 4:04 PM, bob gailer wrote: > >> On 8/4/2010 3:44 PM, Huy Ton That wrote: >> >>> Oh, that's right, I should have tried to example in the interpreter >>> instead of in my head:P >>> >>> Say Bob, >>> >>> Is that the preferred method over something like: >>> >> >> I would prefer to create a class and make these functions class methods. >> >> class A: >> def output_text(self, data):return data >> def output_hex(self, data):return '\\x' + data >> def __getattr__(self, name): >> return self.output_text >> a = A() >> data='bar' >> print a.output_text(data) >> print a.output_hex(data) >> print a.foo(data) >> >> I just realized my answer does not accomodate your looking for the > function by name. Please stand by.... > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Aug 4 22:40:50 2010 From: bgailer at gmail.com (bob gailer) Date: Wed, 04 Aug 2010 16:40:50 -0400 Subject: [Tutor] getattr() In-Reply-To: <4C59C8CA.8040709@gmail.com> References: <3502A2E1-994D-47E4-BA7E-28C5AF06348E@xs4all.nl> <4C59C057.7030705@gmail.com> <4C59C7E4.5090906@gmail.com> <4C59C8CA.8040709@gmail.com> Message-ID: <4C59D052.7020303@gmail.com> class A: def call_by_name(self, func, data): f = A.__dict__.get(func, self.output_text) return f(data) def output_text(self, data):return data def output_hex(self, data):return '\\x' + data a = A() data = 'bar' print a.call_by_name('output_text', data) print a.call_by_name('output_hex', data) print a.call_by_name('foo', data) -- Bob Gailer 919-636-4239 Chapel Hill NC From malaclypse2 at gmail.com Wed Aug 4 22:44:36 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 4 Aug 2010 16:44:36 -0400 Subject: [Tutor] access class through indexing? In-Reply-To: References: Message-ID: On Wed, Aug 4, 2010 at 4:17 PM, Alex Hall wrote: > Hi all, > Further to my questions about overriding builtin methods earlier, how > would I make a class able to be accessed and changed using index > notation? For example, take the following: > deck=CardPile(52) #creates a new deck of cards > print(len(deck)) #prints 52, thanks to my __len__ function > for c in deck: print c #also works thanks to __iter__ > print(deck[4]) #fails with a list index out of range error > How would I get the last one working? I tried __getattr__(self, i), > but it did not work. I want to be able to get an arbitrary item from > the "pile" of cards (which can be a deck, a hand, whatever), and/or > set an element. A "pile" is just a list of Card objects, so I would > only need to use sequence indexing, not mapping functions. > Implement __getitem__(self, key) (See http://docs.python.org/reference/datamodel.html#emulating-container-types ) If you want to support slicing (access like deck[0:10]), you'll need to handle getting a slice object as the key in addition to accepting an integer key. If a pile is really "just" a list of cards, you may want to look into inheriting from list instead of re-implementing all of the functionality on your own. -- Jerry -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Wed Aug 4 23:00:53 2010 From: mehgcap at gmail.com (Alex Hall) Date: Wed, 4 Aug 2010 17:00:53 -0400 Subject: [Tutor] access class through indexing? In-Reply-To: References: Message-ID: On 8/4/10, Jerry Hill wrote: > On Wed, Aug 4, 2010 at 4:17 PM, Alex Hall wrote: > >> Hi all, >> Further to my questions about overriding builtin methods earlier, how >> would I make a class able to be accessed and changed using index >> notation? For example, take the following: >> deck=CardPile(52) #creates a new deck of cards >> print(len(deck)) #prints 52, thanks to my __len__ function >> for c in deck: print c #also works thanks to __iter__ >> print(deck[4]) #fails with a list index out of range error >> How would I get the last one working? I tried __getattr__(self, i), >> but it did not work. I want to be able to get an arbitrary item from >> the "pile" of cards (which can be a deck, a hand, whatever), and/or >> set an element. A "pile" is just a list of Card objects, so I would >> only need to use sequence indexing, not mapping functions. >> > > Implement __getitem__(self, key) (See > http://docs.python.org/reference/datamodel.html#emulating-container-types ) > > If you want to support slicing (access like deck[0:10]), you'll need to > handle getting a slice object as the key in addition to accepting an integer > key. > > If a pile is really "just" a list of cards, you may want to look into > inheriting from list instead of re-implementing all of the functionality on > your own. I tried this first, by typing class Pile(list): Doing this does not seem to work, though, since creating a pile of size 52 results in a list of size 0, unless I include the __len__ function. I thought putting (list) in my class definition would automatically give me the functions of a list as well as anything I wanted to implement, but that does not seem to be the case. > > -- > Jerry > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From evert.rol at gmail.com Wed Aug 4 23:10:18 2010 From: evert.rol at gmail.com (Evert Rol) Date: Wed, 4 Aug 2010 23:10:18 +0200 Subject: [Tutor] access class through indexing? In-Reply-To: References: Message-ID: >>> Further to my questions about overriding builtin methods earlier, how >>> would I make a class able to be accessed and changed using index >>> notation? For example, take the following: >>> deck=CardPile(52) #creates a new deck of cards >>> print(len(deck)) #prints 52, thanks to my __len__ function >>> for c in deck: print c #also works thanks to __iter__ >>> print(deck[4]) #fails with a list index out of range error >>> How would I get the last one working? I tried __getattr__(self, i), >>> but it did not work. I want to be able to get an arbitrary item from >>> the "pile" of cards (which can be a deck, a hand, whatever), and/or >>> set an element. A "pile" is just a list of Card objects, so I would >>> only need to use sequence indexing, not mapping functions. >>> >> >> Implement __getitem__(self, key) (See >> http://docs.python.org/reference/datamodel.html#emulating-container-types ) >> >> If you want to support slicing (access like deck[0:10]), you'll need to >> handle getting a slice object as the key in addition to accepting an integer >> key. >> >> If a pile is really "just" a list of cards, you may want to look into >> inheriting from list instead of re-implementing all of the functionality on >> your own. > I tried this first, by typing > class Pile(list): > Doing this does not seem to work, though, since creating a pile of > size 52 results in a list of size 0, unless I include the __len__ > function. I thought putting (list) in my class definition would > automatically give me the functions of a list as well as anything I > wanted to implement, but that does not seem to be the case. That depends how you create the Pile of 52 cards: list(52) also doesn't generate 52 (random) items. If you override __init__ to accept an integer that generates the cards for you, this should work. Something like: class Pile(list): def __init__(self, *args, **kwargs): if len(args) == 1 and isinstance(args[0], (int, long)): args = ([Card(i) for i in xrange(args[0])],) super(Pile, self).__init__(*args, **kwargs) allows things like Pile(52), Pile([card1, card2, card3]), Pile(12)[0:3] etc. Cheers, Evert From mehgcap at gmail.com Wed Aug 4 23:28:03 2010 From: mehgcap at gmail.com (Alex Hall) Date: Wed, 4 Aug 2010 17:28:03 -0400 Subject: [Tutor] access class through indexing? In-Reply-To: References: Message-ID: On 8/4/10, Evert Rol wrote: >>>> Further to my questions about overriding builtin methods earlier, how >>>> would I make a class able to be accessed and changed using index >>>> notation? For example, take the following: >>>> deck=CardPile(52) #creates a new deck of cards >>>> print(len(deck)) #prints 52, thanks to my __len__ function >>>> for c in deck: print c #also works thanks to __iter__ >>>> print(deck[4]) #fails with a list index out of range error >>>> How would I get the last one working? I tried __getattr__(self, i), >>>> but it did not work. I want to be able to get an arbitrary item from >>>> the "pile" of cards (which can be a deck, a hand, whatever), and/or >>>> set an element. A "pile" is just a list of Card objects, so I would >>>> only need to use sequence indexing, not mapping functions. >>>> >>> >>> Implement __getitem__(self, key) (See >>> http://docs.python.org/reference/datamodel.html#emulating-container-types >>> ) >>> >>> If you want to support slicing (access like deck[0:10]), you'll need to >>> handle getting a slice object as the key in addition to accepting an >>> integer >>> key. >>> >>> If a pile is really "just" a list of cards, you may want to look into >>> inheriting from list instead of re-implementing all of the functionality >>> on >>> your own. >> I tried this first, by typing >> class Pile(list): >> Doing this does not seem to work, though, since creating a pile of >> size 52 results in a list of size 0, unless I include the __len__ >> function. I thought putting (list) in my class definition would >> automatically give me the functions of a list as well as anything I >> wanted to implement, but that does not seem to be the case. > > That depends how you create the Pile of 52 cards: list(52) also doesn't > generate 52 (random) items. > If you override __init__ to accept an integer that generates the cards for > you, this should work. Here is my init, not half as pretty as yours, but it should work. Maybe this will explain the problem. def __init__(self, size, cards=None, fill=False): #creates a pile of cards. If "fill"==true, it will auto-fill the pile starting from the Ace of Clubs up through the King of Spades, stopping if it exceeds the size arg. #if the cards arg is not null, it will populate the pile with the cards in the list. self=[] if fill: #auto-fill, useful to generate a new, unshuffled deck for i in range(1, 14): for j in range(1, 5): self.append(Card(i, j)) #end for #end for self=self[:size] #keep only the amount specified elif cards is not None: #fill the pile with the cards for c in cards: self.append(c) #end for #end if #end def __init__ > Something like: > > class Pile(list): > def __init__(self, *args, **kwargs): > if len(args) == 1 and isinstance(args[0], (int, long)): > args = ([Card(i) for i in xrange(args[0])],) > super(Pile, self).__init__(*args, **kwargs) Why call super here, if it is already my own __init__? > > allows things like Pile(52), Pile([card1, card2, card3]), Pile(12)[0:3] etc. Again, my init is not nearly so fancy, and I will have to look hard at what you did to understand it, but they are the same in terms of class structure/inheriting list attributes as far as I can see, except the call to the super.__init__ method. > > Cheers, > > Evert > > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From evert.rol at gmail.com Wed Aug 4 23:52:57 2010 From: evert.rol at gmail.com (Evert Rol) Date: Wed, 4 Aug 2010 23:52:57 +0200 Subject: [Tutor] access class through indexing? In-Reply-To: References: Message-ID: On 4 Aug 2010, at 23:28 , Alex Hall wrote: > On 8/4/10, Evert Rol wrote: >>>>> Further to my questions about overriding builtin methods earlier, how >>>>> would I make a class able to be accessed and changed using index >>>>> notation? For example, take the following: >>>>> deck=CardPile(52) #creates a new deck of cards >>>>> print(len(deck)) #prints 52, thanks to my __len__ function >>>>> for c in deck: print c #also works thanks to __iter__ >>>>> print(deck[4]) #fails with a list index out of range error >>>>> How would I get the last one working? I tried __getattr__(self, i), >>>>> but it did not work. I want to be able to get an arbitrary item from >>>>> the "pile" of cards (which can be a deck, a hand, whatever), and/or >>>>> set an element. A "pile" is just a list of Card objects, so I would >>>>> only need to use sequence indexing, not mapping functions. >>>>> >>>> >>>> Implement __getitem__(self, key) (See >>>> http://docs.python.org/reference/datamodel.html#emulating-container-types >>>> ) >>>> >>>> If you want to support slicing (access like deck[0:10]), you'll need to >>>> handle getting a slice object as the key in addition to accepting an >>>> integer >>>> key. >>>> >>>> If a pile is really "just" a list of cards, you may want to look into >>>> inheriting from list instead of re-implementing all of the functionality >>>> on >>>> your own. >>> I tried this first, by typing >>> class Pile(list): >>> Doing this does not seem to work, though, since creating a pile of >>> size 52 results in a list of size 0, unless I include the __len__ >>> function. I thought putting (list) in my class definition would >>> automatically give me the functions of a list as well as anything I >>> wanted to implement, but that does not seem to be the case. >> >> That depends how you create the Pile of 52 cards: list(52) also doesn't >> generate 52 (random) items. >> If you override __init__ to accept an integer that generates the cards for >> you, this should work. > Here is my init, not half as pretty as yours, but it should work. > Maybe this will explain the problem. > > def __init__(self, size, cards=None, fill=False): > #creates a pile of cards. If "fill"==true, it will auto-fill the > pile starting from the Ace of Clubs up through the King of Spades, > stopping if it exceeds the size arg. > #if the cards arg is not null, it will populate the pile with the > cards in the list. > self=[] You declare self to be a list here (while somewhere before the def __init__, you'll have class Pile(list), meaning every self will be a Pile object. While self is an arbitrarily chosen name, it is assigned by the interpreter when calling the methods (I hope I'm saying that correctly). So when __init__(self, ...) is called, self is a Pile object, then you turn self into a list object, loosing its meaning. Don't reassign self (but you can do 'print self[:size]'. Then again, you probably don't need that inside your class. Try using your __init__, then at the end of the __init__ method, print type(self). That should be something like . Now do the same with the init below that uses super. You should get something like . > if fill: #auto-fill, useful to generate a new, unshuffled deck > for i in range(1, 14): > for j in range(1, 5): > self.append(Card(i, j)) > #end for > #end for > self=self[:size] #keep only the amount specified > elif cards is not None: #fill the pile with the cards > for c in cards: > self.append(c) > #end for > #end if > #end def __init__ > > >> Something like: >> >> class Pile(list): >> def __init__(self, *args, **kwargs): >> if len(args) == 1 and isinstance(args[0], (int, long)): >> args = ([Card(i) for i in xrange(args[0])],) >> super(Pile, self).__init__(*args, **kwargs) > Why call super here, if it is already my own __init__? It's just Good Practice to always call super, propagating any remaining arguments to the base class __init__ (hence the *args & **kwargs). Google for "Python super" and read a few of those hits. At first, it may make little sense, because there's a lot that can be said about it, but after a while, it'll become clearer. >> allows things like Pile(52), Pile([card1, card2, card3]), Pile(12)[0:3] etc. > Again, my init is not nearly so fancy, and I will have to look hard at > what you did to understand it, but they are the same in terms of class > structure/inheriting list attributes as far as I can see, except the > call to the super.__init__ method. If you're confused about the first line, I can image, but it's just a fancy way to find out if you initialize the Pile with a list of cards, or with a single integer argument. The *args & **kwargs, again, Google around a bit. In essence, these just capture extra argument (positional arguments, then keyword arguments). def __init__(self, ncards=0, *args, **kwargs) could even be better, but I'm not sure if that works correctly. But yes, other than the self assignment in your code, the structures are essentially the same. Evert From malaclypse2 at gmail.com Wed Aug 4 23:59:20 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 4 Aug 2010 17:59:20 -0400 Subject: [Tutor] access class through indexing? In-Reply-To: References: Message-ID: On Wed, Aug 4, 2010 at 5:28 PM, Alex Hall wrote: > Here is my init, not half as pretty as yours, but it should work. > Maybe this will explain the problem. > > def __init__(self, size, cards=None, fill=False): > #creates a pile of cards. If "fill"==true, it will auto-fill the > pile starting from the Ace of Clubs up through the King of Spades, > stopping if it exceeds the size arg. > #if the cards arg is not null, it will populate the pile with the > cards in the list. > self=[] > This is the problem. You cannot re-assign self inside the __init__ method (or any method, for that matter). Well, you can, but it doesn't do what you expect. All you're doing is shadowing the self that gets passed in to the function, not changing it. Just call list.__init__(self) to initialize self using the initialized from the list class. > if fill: #auto-fill, useful to generate a new, unshuffled deck > for i in range(1, 14): > for j in range(1, 5): > self.append(Card(i, j)) > #end for > #end for > self=self[:size] #keep only the amount specified > The same thing goes on here, you can't re-assign self. Instead, you can alter it in place by doing self[:] = self[:size]. That's called slice assignment. There's some discussion of this here: http://docs.python.org/release/2.5.2/ref/assignment.html and http://docs.python.org/library/stdtypes.html#mutable-sequence-types > elif cards is not None: #fill the pile with the cards > for c in cards: > self.append(c) > #end for > #end if > #end def __init__ > I don't have a Card class built, but here's an example that uses tuples instead: class Pile(list): def __init__(self, size=52, cards=None, fill=False): list.__init__(self) #Initialize self as an empty list if fill: for i in range(1, 14): for j in range(1, 5): self.append((i,j)) self[:] = self[:size] elif cards is not None: for c in cards: self.append(c) I think that supports all the same things you had in your example. -- Jerry -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Thu Aug 5 00:30:56 2010 From: davea at ieee.org (Dave Angel) Date: Wed, 04 Aug 2010 18:30:56 -0400 Subject: [Tutor] access class through indexing? In-Reply-To: References: Message-ID: <4C59EA20.3090108@ieee.org> Alex Hall wrote: > On 8/4/10, Evert Rol wrote: > >> >> That depends how you create the Pile of 52 cards: list(52) also doesn't >> generate 52 (random) items. >> If you override __init__ to accept an integer that generates the cards for >> you, this should work. >> > Here is my init, not half as pretty as yours, but it should work. > Maybe this will explain the problem. > > def __init__(self, size, cards=None, fill=False): > #creates a pile of cards. If "fill"==true, it will auto-fill the > pile starting from the Ace of Clubs up through the King of Spades, > stopping if it exceeds the size arg. > #if the cards arg is not null, it will populate the pile with the > cards in the list. > self=[] > if fill: #auto-fill, useful to generate a new, unshuffled deck > for i in range(1, 14): > for j in range(1, 5): > self.append(Card(i, j)) > #end for > #end for > self=self[:size] #keep only the amount specified > elif cards is not None: #fill the pile with the cards > for c in cards: > self.append(c) > #end for > #end if > #end def __init__ > > > You have two serious problems here, and maybe others, I didn't keep looking. Since you never call super(), the init of the base class never happens. It may happen to work, since you're apparently willing to take its default behavior, but I don't know. But even worse, you never even talk to your own object. The first parameter to __init__() is a ref to the actual object you're supposed to be initializing, and you immediately overwrite it (self) with another object. As a result, everything else you do in that method is thrown out when the method returns. Remove that line self = [] DaveA From pine508 at hotmail.com Thu Aug 5 01:02:56 2010 From: pine508 at hotmail.com (Che M) Date: Wed, 4 Aug 2010 19:02:56 -0400 Subject: [Tutor] global exception handling? In-Reply-To: References: , Message-ID: > > But, the issue is, I have many places where I write to the database and would have to embed each of these in a try/except block. I can do that, but wondered if there is a "global" way to catch this 'database is locked' error? I found someone asking this sort of question online but it doesn't appear to be answered: > > http://bytes.com/topic/python/answers/799486-how-do-i-prevent-exceptions-stopping-execution-global-exception-handler > > I'm not sure why you would like to do that: your code assumes the database interaction works fine, and based on that just continues it's normal flow. If the database is locked, you'll need to do something to prevent your code crashing further down, which is what you put in the except OperationalError: block. I would assume that the error handling depends on where you are in the code. > If you can always perform the same type of error handling, just create a convenience function (possibly with the SQL statement as argument) that calls the database and returns the results, and put the database call inside the try: except: clause. Then you need to do this only once. Interesting, it didn't occur to me to do that. I may give it a try. Since I am making INSERTs and UPDATEs to the database from all over the application (in different modules), maybe I should put this error-handling convenience function in a module and import it into every other module, then I can just use it. Unfortunately, I'll still have to go back and find every instance of when I do INSERT or UPDATE to change this to use the convenience function, but it will still save me some keystrokes to fix the app. > A global way to catch the database-locked exception is just to put the try: except OperationalError: around your complete code. Exceptions propagate all the way to the function where your program started, and if you catch it there, you will catch every OperationalError exception from anywhere in the code. Of course, your program then always exits anyway, because you can't return to the point where the the exception was thrown (or maybe you can, but not that I'm aware of. I wouldn't recommend it though). That I really didn't know at all. But yes, if the program exits, that's not going to work. > > > p.s. *I use the nice program SQLite Database Browser and if I edit a field in the database my Python app is accessing, click "Apply changes", but I do *not* save the changes (that is, I do not click the disk icon), when I go to write to that database from my Python app, I get a 'database is locked' error. > Sounds like somewhat odd behaviour to me: "apply changes" for me means "apply & commit", ie, it includes the save operation. Might > just be me. I guess "Apply changes" opens the database connection, but then "save" performs the actual commit to the database, and > in the meantime the database is locked. I don't know, either, but I was glad to find a way to reproduce the problem so that I could anticipate it for potential users. Thanks for your help, Che -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Thu Aug 5 05:23:58 2010 From: mehgcap at gmail.com (Alex Hall) Date: Wed, 4 Aug 2010 23:23:58 -0400 Subject: [Tutor] access class through indexing? In-Reply-To: <4C59EA20.3090108@ieee.org> References: <4C59EA20.3090108@ieee.org> Message-ID: On 8/4/10, Dave Angel wrote: > Alex Hall wrote: >> On 8/4/10, Evert Rol wrote: >> >>> >>> That depends how you create the Pile of 52 cards: list(52) also doesn't >>> generate 52 (random) items. >>> If you override __init__ to accept an integer that generates the cards >>> for >>> you, this should work. >>> >> Here is my init, not half as pretty as yours, but it should work. >> Maybe this will explain the problem. >> >> def __init__(self, size, cards=None, fill=False): >> #creates a pile of cards. If "fill"==true, it will auto-fill the >> pile starting from the Ace of Clubs up through the King of Spades, >> stopping if it exceeds the size arg. >> #if the cards arg is not null, it will populate the pile with the >> cards in the list. >> self=[] >> if fill: #auto-fill, useful to generate a new, unshuffled deck >> for i in range(1, 14): >> for j in range(1, 5): >> self.append(Card(i, j)) >> #end for >> #end for >> self=self[:size] #keep only the amount specified >> elif cards is not None: #fill the pile with the cards >> for c in cards: >> self.append(c) >> #end for >> #end if >> #end def __init__ >> >> >> > You have two serious problems here, and maybe others, I didn't keep looking. > > Since you never call super(), the init of the base class never happens. > It may happen to work, since you're apparently willing to take its > default behavior, but I don't know. But even worse, you never even talk > to your own object. The first parameter to __init__() is a ref to the > actual object you're supposed to be initializing, and you immediately > overwrite it (self) with another object. As a result, everything else > you do in that method is thrown out when the method returns. Remove > that line > > self = [] That makes sense, and doing so has fixed everything. I am still not clear on the whole super() thing; I saw it in another project and tried to find out about it, but what I found was very confusing, and super() did not seem terribly important, so I did not pursue the matter further. Apparently it is important... > > DaveA > > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From kpguy1975 at gmail.com Thu Aug 5 06:38:07 2010 From: kpguy1975 at gmail.com (Vikram K) Date: Thu, 5 Aug 2010 10:08:07 +0530 Subject: [Tutor] string to list Message-ID: Suppose i have this string: z = 'AT/CG' How do i get this list: zlist = ['A','T/C','G'] -------------- next part -------------- An HTML attachment was scrubbed... URL: From prologic at shortcircuit.net.au Thu Aug 5 09:25:55 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 5 Aug 2010 17:25:55 +1000 Subject: [Tutor] string to list In-Reply-To: References: Message-ID: On Thu, Aug 5, 2010 at 2:38 PM, Vikram K wrote: > Suppose i have this string: > z = 'AT/CG' > > How do i get this list: > > zlist = ['A','T/C','G'] >>> import re >>> z = 'AT/CG' >>> [x for x in re.split("([A-Z]\/[A-Z])|([A-Z])", z) if x] ['A', 'T/C', 'G'] >>> cheers James -- -- James Mills -- -- "Problems are solved by method" From sander.sweers at gmail.com Thu Aug 5 09:40:55 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Thu, 5 Aug 2010 09:40:55 +0200 Subject: [Tutor] string to list In-Reply-To: References: Message-ID: On 5 August 2010 06:38, Vikram K wrote: > Suppose i have this string: > z = 'AT/CG' > > How do i get this list: > > zlist = ['A','T/C','G'] If you know the format of the string is always the same you can do something like this. This fails when you have strings that do not have the '/' in the middle and has 2 characters on either side. def parseString(s): n = s.find('/') l = [] if n: l = [s[0],s[n-1:n+2], s[-1]] return l >>> parseString(s) ['A', 'T/C', 'G'] Greets Sander From paradox at pobox.com Thu Aug 5 12:13:55 2010 From: paradox at pobox.com (Thomas C. Hicks) Date: Thu, 5 Aug 2010 18:13:55 +0800 Subject: [Tutor] string to list In-Reply-To: References: Message-ID: <20100805181355.42ebdf6e@midgel> On Thu, 5 Aug 2010 03:40:55 -0400 Sander Sweers wrote: > On 5 August 2010 06:38, Vikram K wrote: > > Suppose i have this string: > > z = 'AT/CG' > > > > How do i get this list: > > > > zlist = ['A','T/C','G'] > > If you know the format of the string is always the same you can do > something like this. This fails when you have strings that do not have > the '/' in the middle and has 2 characters on either side. > > def parseString(s): > n = s.find('/') > l = [] > if n: > l = [s[0],s[n-1:n+2], s[-1]] > return l > > >>> parseString(s) > ['A', 'T/C', 'G'] > > Greets > Sander Much better than my original thought on this! If the data is stereotypic couldn't you simplify it though? ... z='AT/CG' zlist=[z[0],z[1:4],z[-1]] tom From alan.gauld at btinternet.com Thu Aug 5 12:25:43 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Aug 2010 11:25:43 +0100 Subject: [Tutor] how to get str() to use my function? References: Message-ID: "Alex Hall" wrote > It worked, thanks. Is there a list of these functions somewhere? Learn to use the dir() and help() functions in Python at the >>> prompt. dir(obj) will show all the standard methods for that object. For the math operators try dir(5) - or any other number, 5.0 for a float etc. The advantage of dir() is a nice short listing, easy to scan. For a detailed description use the help function: >>> help(5) Help on int object: class int(object) | int(x[, base]) -> integer | | Convert a string or number to an integer, if possible. A floating point | argument will be truncated towards zero (this does not include a string | representation of a floating point number!) When converting a string, use | the optional base. It is an error to supply a base when converting a | non-string. If the argument is outside the integer range a long object | will be returned instead. | | Methods defined here: | | __abs__(...) | x.__abs__() <==> abs(x) | | __add__(...) | x.__add__(y) <==> x+y | | __and__(...) | x.__and__(y) <==> x&y | | __cmp__(...) -- More -- HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Aug 5 12:40:15 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Aug 2010 11:40:15 +0100 Subject: [Tutor] access class through indexing? References: <4C59EA20.3090108@ieee.org> Message-ID: "Alex Hall" wrote >> Since you never call super(), the init of the base class never >> happens. ... >> actual object you're supposed to be initializing, and you >> immediately >> overwrite it (self) with another object. As a result, everything >> else >> you do in that method is thrown out when the method returns. > That makes sense, and doing so has fixed everything. I am still not > clear on the whole super() thing; I saw it in another project and > tried to find out about it, but what I found was very confusing, and > super() did not seem terribly important, so I did not pursue the > matter further. Apparently it is important... It is critical. Methods are not simply functions that happen to be defined in a class structure. They are intended to be part of a complete heirarchical calling mechanism. It is normal when writing a method of a derived class that over-rides an inherited method to call the inherited method somehwhere in the body of your method. class C(A): def myAmethod(self) # put local initialisation code here # call the superclass version of the method here # call local tidy-up code here The initialisation and tidy-up code is what is unique to your version of the class (and are optional but if neither exists you don't need to override the method!). But to get the inherited functionality (including init*() ) to work you must call the inherited method. If you don't you replace the inherited functionality and talke full responsibility for doing everything that it used to do yourself. Using super() is the approved way of doing it, but for single inheritance you can call the parent class directly A.myAmethod(self) if you find that less mind bending. But calling the superclass version of your method is vital if you want to get the benefits of inheritance. Finally, if you did want to replace what self was you can do that by writing your own __new__ method rather than an __init__ but you very rarely want to do that! Python gives you a lot of tools to mess with how objects work. Unless you really know what you are doing it's usually best to ignore the temptation! :-) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Aug 5 12:44:47 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Aug 2010 11:44:47 +0100 Subject: [Tutor] string to list References: Message-ID: "Vikram K" wrote > Suppose i have this string: > z = 'AT/CG' > > How do i get this list: > > zlist = ['A','T/C','G'] > There are lots of ways and it really needs a tighter specification of yhow you split. What would "AT/C/DGH" give for example? But in general there are several approaches, I suspect regex is the best solution here but for simple solutions splitting by the / then splitting the sublists then joining the last to the first element of each sublist using / might work too. But regex is probably faster, although more complex. And you could use a parser if the rules are very complex. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From wprins at gmail.com Thu Aug 5 13:28:44 2010 From: wprins at gmail.com (Walter Prins) Date: Thu, 5 Aug 2010 12:28:44 +0100 Subject: [Tutor] string to list In-Reply-To: References: Message-ID: Just a minor related/tangential suggestion -- O'Reilly had a stand at the recent EuroPython conference I attended and I was paging through "Bioinformatics Programming using Python", Book reference: http://oreilly.com/catalog/9780596154516 Just thought I'd mention it as it seems relevant to the current question/domain from which the question comes from. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From luhmann_br at yahoo.com Thu Aug 5 15:05:56 2010 From: luhmann_br at yahoo.com (Luhmann) Date: Thu, 5 Aug 2010 06:05:56 -0700 (PDT) Subject: [Tutor] =?iso-8859-1?q?R=E9p=2E_=3A__string_to_list?= In-Reply-To: Message-ID: <181922.99696.qm@web30903.mail.mud.yahoo.com> Try this: >>> def f(mystring): ??? charlist = list(mystring) ??? tmplist = [ [''] ] ??? for a in charlist: ??? ??? if tmplist[-1][-1] == '/' or a == '/': ??? ??? ??? tmplist[-1].append(a) ??? ??? else: ??? ??? ??? tmplist.append( [a] ) ??? return? [''.join(a) for a in tmplist][1:] >>>? #Thusly: >>> f('AT/CG') ['A', 'T/C', 'G'] >>> f('CATAT/T/CATA/C/AC/TACGAA/AGT/GGTC/GGGTCTACGATTT/A/A/GC/CCCCT/GA/C/A/T/GA/G/C/ACAAG/CC/GAGGTG/GACTCA/G/TTT/TAGT/AGAC/AT/CC/GG/CG/G/A') ['C', 'A', 'T', 'A', 'T/T/C', 'A', 'T', 'A/C/A', 'C/T', 'A', 'C', 'G', 'A', 'A/A', 'G', 'T/G', 'G', 'T', 'C/G', 'G', 'G', 'T', 'C', 'T', 'A', 'C', 'G', 'A', 'T', 'T', 'T/A/A/G', 'C/C', 'C', 'C', 'C', 'T/G', 'A/C/A/T/G', 'A/G/C/A', 'C', 'A', 'A', 'G/C', 'C/G', 'A', 'G', 'G', 'T', 'G/G', 'A', 'C', 'T', 'C', 'A/G/T', 'T', 'T/T', 'A', 'G', 'T/A', 'G', 'A', 'C/A', 'T/C', 'C/G', 'G/C', 'G/G/A'] --- En date de?: Mer, 4.8.10, Vikram K a ?crit?: De?: Vikram K Objet?: [Tutor] string to list ??: tutor at python.org Date: mercredi 4 ao?t 2010 21 h 38 Suppose i have this string: z = 'AT/CG' How do i get this list: zlist = ['A','T/C','G'] -----La pi?ce jointe associ?e suit----- _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From invincible_patriot at hotmail.com Thu Aug 5 16:08:59 2010 From: invincible_patriot at hotmail.com (invincible patriot) Date: Thu, 5 Aug 2010 14:08:59 +0000 Subject: [Tutor] how to do excel in python Message-ID: hi, can any one tell me how can I access MS excel worksheet in python and how can I access itz individual cells..?????? -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Aug 5 16:20:18 2010 From: bgailer at gmail.com (bob gailer) Date: Thu, 05 Aug 2010 10:20:18 -0400 Subject: [Tutor] getattr() In-Reply-To: References: <3502A2E1-994D-47E4-BA7E-28C5AF06348E@xs4all.nl> <4C59C057.7030705@gmail.com> <4C59C7E4.5090906@gmail.com> <4C59C8CA.8040709@gmail.com> Message-ID: <4C5AC8A2.9070906@gmail.com> On 8/4/2010 4:32 PM, Huy Ton That wrote: > I have a side question, > > I am using python 2.7. > > Why do you use class A: instead of class A(object): ? My example does not depend on old / new style classes. -- Bob Gailer 919-636-4239 Chapel Hill NC From mail at timgolden.me.uk Thu Aug 5 16:20:32 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 05 Aug 2010 15:20:32 +0100 Subject: [Tutor] how to do excel in python In-Reply-To: References: Message-ID: <4C5AC8B0.8030700@timgolden.me.uk> On 05/08/2010 15:08, invincible patriot wrote: > > hi, can any one tell me how can I access MS excel worksheet in python and how can I access itz individual cells..?????? http://www.python-excel.org/ (First hit for python excel in Google) TJG From huyslogic at gmail.com Thu Aug 5 16:28:39 2010 From: huyslogic at gmail.com (Huy Ton That) Date: Thu, 5 Aug 2010 10:28:39 -0400 Subject: [Tutor] string to list In-Reply-To: References: Message-ID: Speaking of which, is there some place you or anyone can recommend on picking up all the constructs for list comprehension & generator comprehension. I've perused the python.org documents and have just been building them according to example. How can I pick up more advanced usage? I mostly catch myself using it to return a list of functions like: >>> class foo(object): ... def __init__(self, bar): ... self.bar = bar ... >>> [(foo(i)) for i in range(0,10)] [<__main__.foo object at 0x00C54FD0>, <__main__.foo object at 0x00C54FF0>, <__ma in__.foo object at 0x00C54F50>, <__main__.foo object at 0x00C54F30>, <__main__.f oo object at 0x00C59050>, <__main__.foo object at 0x00C59070>, <__main__.foo obj ect at 0x00C590B0>, <__main__.foo object at 0x00C590D0>, <__main__.foo object at 0x00C59110>, <__main__.foo object at 0x00C59130>] On Thu, Aug 5, 2010 at 3:25 AM, James Mills wrote: > On Thu, Aug 5, 2010 at 2:38 PM, Vikram K wrote: > > Suppose i have this string: > > z = 'AT/CG' > > > > How do i get this list: > > > > zlist = ['A','T/C','G'] > > >>> import re > >>> z = 'AT/CG' > >>> [x for x in re.split("([A-Z]\/[A-Z])|([A-Z])", z) if x] > ['A', 'T/C', 'G'] > >>> > > cheers > James > > -- > -- James Mills > -- > -- "Problems are solved by method" > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From webtourist at gmail.com Thu Aug 5 16:29:46 2010 From: webtourist at gmail.com (Robert) Date: Thu, 5 Aug 2010 10:29:46 -0400 Subject: [Tutor] how to do excel in python In-Reply-To: References: Message-ID: > hi, > can any one tell me how can I access MS excel worksheet in python and how > can I access itz individual cells..?????? let me google that for you... From cfuller084 at thinkingplanet.net Thu Aug 5 16:58:14 2010 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 5 Aug 2010 09:58:14 -0500 Subject: [Tutor] how to do excel in python In-Reply-To: References: Message-ID: <201008050958.14962.cfuller084@thinkingplanet.net> There are many ways. The simplest is to export the file to CSV and load that, but you'll only get one worksheet, and it's a big hassle to update the Excel file that way. You can save the spreadsheet as an ODF file, which is a fully documented XML format that Python can read and write easily, but you might give up some Excel features (but a lot fewer than with CSV format). You can also have the spreadsheet open in excel and talk to it from Python via COM. If you're on Windows and have Excel, this approach can be the most flexible. http://docs.python.org/library/csv.html http://www.linuxjournal.com/article/9347 http://www.google.com/search?q=excel+com+python Cheers On Thursday 05 August 2010, invincible patriot wrote: > hi, can any one tell me how can I access MS excel worksheet in python and > how can I access itz individual cells..?????? From alan.gauld at btinternet.com Thu Aug 5 17:29:16 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Aug 2010 16:29:16 +0100 Subject: [Tutor] how to do excel in python References: Message-ID: "invincible patriot" wrote > hi, can any one tell me how can I access MS excel worksheet > in python and how can I access itz individual cells..?????? There are several Excel specific modules - try Google - or, using the standard library, and if its practical for your case, you can use CSV files - just save the spreadsheet as CSV - and manipulate it that way using the standard csv module. HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From sierra_mtnview at sbcglobal.net Fri Aug 6 01:33:17 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 05 Aug 2010 16:33:17 -0700 Subject: [Tutor] Finding the version # of a module, and py module problem Message-ID: <4C5B4A3D.1060105@sbcglobal.net> An HTML attachment was scrubbed... URL: From paradox at pobox.com Fri Aug 6 01:36:31 2010 From: paradox at pobox.com (Thomas C. Hicks) Date: Fri, 6 Aug 2010 07:36:31 +0800 Subject: [Tutor] how to do excel in python In-Reply-To: References: Message-ID: <20100806073631.09402d43@midgel> On Thu, 5 Aug 2010 10:08:59 -0400 invincible patriot wrote: > hi, > can any one tell me how can I access MS excel worksheet in python and > how can I access itz individual cells..?????? > I have had good luck with the xlrd and xlwt modules, you can get them at www.python-excel.org. The Google Group for those packages is reasonably helpful as well. tom From smokefloat at gmail.com Fri Aug 6 02:53:21 2010 From: smokefloat at gmail.com (David Hutto) Date: Thu, 5 Aug 2010 20:53:21 -0400 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: <4C5B4A3D.1060105@sbcglobal.net> References: <4C5B4A3D.1060105@sbcglobal.net> Message-ID: On Thu, Aug 5, 2010 at 7:33 PM, Wayne Watson wrote: > It's been awhile since I've used python, and I recall there is a way to find > the version number from the IDLE command line? prompt. dir, help, > __version.__? > > I made the most minimal change to a program, and it works for me, but not my > partner. He gets > > Traceback (most recent call last): > ? File "C:\Documents and > Settings\HP_Administrator.DavesDesktop\Desktop\NC-FireballReport20100729.py", > line 40, in > ??? from scipy import stats as stats # scoreatpercentile > ? File "C:\Python25\lib\site-packages\scipy\stats\__init__.py", line 7, in > > ??? from stats import * > ? File "C:\Python25\lib\site-packages\scipy\stats\stats.py", line 191, in > > ??? import scipy.special as special > ? File "C:\Python25\lib\site-packages\scipy\special\__init__.py", line 22, > in > ??? from numpy.testing import NumpyTest > ImportError: cannot import name NumpyTest > > Here are the first few lines of code. > > import sys, os, glob > import string > from numpy import * > from datetime import datetime, timedelta > import time > from scipy import stats as stats # scoreatpercentile > > I'm pretty sure he has the same version of Python, 2.5, but perhaps not the > numpy or scipy modules. I need to find out his version numbers. > > -- > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet > > "Republicans are always complaining that government is > out of control. If they get into power, they will > prove it." -- R. J. Rourke > > > Web Page: > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > I'm pretty sure their might be an easier way, but since no one has replied just yet. You can go into your command prompt and type pydoc -p 1234(noth the python interpreter, and you might have to cd to the Lib directory with pydoc in it). Then use a browser and go to localhost:1234, and in the sight packages section click on the numpy, or scipy, and it shows the version in parentheses beside the name at top. From smokefloat at gmail.com Fri Aug 6 03:30:42 2010 From: smokefloat at gmail.com (David Hutto) Date: Thu, 5 Aug 2010 21:30:42 -0400 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: <4C5B4A3D.1060105@sbcglobal.net> Message-ID: On Thu, Aug 5, 2010 at 8:53 PM, David Hutto wrote: > On Thu, Aug 5, 2010 at 7:33 PM, Wayne Watson > wrote: >> It's been awhile since I've used python, and I recall there is a way to find >> the version number from the IDLE command line? prompt. dir, help, >> __version.__? >> >> I made the most minimal change to a program, and it works for me, but not my >> partner. He gets >> >> Traceback (most recent call last): >> ? File "C:\Documents and >> Settings\HP_Administrator.DavesDesktop\Desktop\NC-FireballReport20100729.py", >> line 40, in >> ??? from scipy import stats as stats # scoreatpercentile >> ? File "C:\Python25\lib\site-packages\scipy\stats\__init__.py", line 7, in >> >> ??? from stats import * >> ? File "C:\Python25\lib\site-packages\scipy\stats\stats.py", line 191, in >> >> ??? import scipy.special as special >> ? File "C:\Python25\lib\site-packages\scipy\special\__init__.py", line 22, >> in >> ??? from numpy.testing import NumpyTest >> ImportError: cannot import name NumpyTest >> >> Here are the first few lines of code. >> >> import sys, os, glob >> import string >> from numpy import * >> from datetime import datetime, timedelta >> import time >> from scipy import stats as stats # scoreatpercentile >> >> I'm pretty sure he has the same version of Python, 2.5, but perhaps not the >> numpy or scipy modules. I need to find out his version numbers. >> >> -- >> ? ? ? ? ? ?Wayne Watson (Watson Adventures, Prop., Nevada City, CA) >> >> ? ? ? ? ? ? ?(121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) >> ? ? ? ? ? ? ? Obz Site: ?39? 15' 7" N, 121? 2' 32" W, 2700 feet >> >> ? ? ? ? ? ? ?"Republicans are always complaining that government is >> ? ? ? ? ? ? ? out of control. If they get into power, they will >> ? ? ? ? ? ? ? prove it." -- R. J. Rourke >> >> >> ? ? ? ? ? ? ? ? ? ? Web Page: >> >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > > I'm pretty sure their might be an easier way, but since no one has > replied just yet. You can go into your command prompt and type pydoc > -p 1234(noth the python interpreter, and you might have to cd to the > Lib directory with pydoc in it). Then use a browser and go to > localhost:1234, and in the sight packages section click on the numpy, > or scipy, and it shows the version in parentheses beside the name at > top. > And not sure if this works in 2.5, I only have 2.6, 2.7, and 3.1 to test on. >>> from setup import * >>> print __version__ $Revision: 77217 $ >>> So for you should be: from numpy import * print __version__ From sierra_mtnview at sbcglobal.net Fri Aug 6 03:56:12 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 05 Aug 2010 18:56:12 -0700 Subject: [Tutor] Finding the version # of a module, and py module problem In-Reply-To: References: <4C5B4A3D.1060105@sbcglobal.net> Message-ID: <4C5B6BBC.30200@sbcglobal.net> I should have mentioned I use windows. import numpy numpy.__version__ It's now written in my Py book! From rdmoores at gmail.com Fri Aug 6 15:11:53 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 6 Aug 2010 06:11:53 -0700 Subject: [Tutor] Seek suggestions for script for looking up extensions using C:\>assoc Message-ID: Python 3.1; Windows Vista. I just ran C:\>assoc and was amazed to see 658 associations roll by. Here's the top of the list: .001=jZip.file .386=vxdfile .3g2=QuickTime.3g2 .3gp=QuickTime.3gp .3gp2=QuickTime.3gp2 .3gpp=QuickTime.3gpp .7Z=jZip.file .aa=NeroShowTime.Files9.aa .aac=QuickTime.aac .ac3=QuickTime.ac3 .aca=Agent.Character.2 .acf=Agent.Character.2 .acl=ACLFile .acr=IrfanView.DCM .acrobatsecuritysettings=AcroExch.acrobatsecuritysettings .acs=Agent.Character2.2 .acsm=Adobe.ACSMessage .AddIn=VCExpress.AddIn.9.0 .adts=QuickTime.adts .aif=IrfanView.aif .aifc=WMP11.AssocFile.AIFF .aiff=WMP11.AssocFile.AIFF .air=AIR.InstallerPackage I thought it would be convenient to have a Python script I could use to look up unfamiliar file extensions. I assume one is possible, but have no idea where to start, and would appreciate hints and suggestions. Thanks, Dick Moores From davidheiserca at gmail.com Fri Aug 6 16:56:39 2010 From: davidheiserca at gmail.com (davidheiserca at gmail.com) Date: Fri, 6 Aug 2010 07:56:39 -0700 Subject: [Tutor] Seek suggestions for script for looking up extensions usingC:\>assoc References: Message-ID: <9C5927E386614F4C833B6141377CE905@dheiser> You wouldn't gain much with a Pyton script. You can specify the extension with "assoc". Try "assoc .zip". But if you want to try it anyway, look at the "popen2" module (depreciated) or the "subprocess" module to extract the data and assign it to a variable that you can parse any way you like. ----- Original Message ----- From: "Richard D. Moores" To: Sent: Friday, August 06, 2010 6:11 AM Subject: [Tutor] Seek suggestions for script for looking up extensions usingC:\>assoc > Python 3.1; Windows Vista. > > I just ran C:\>assoc and was amazed to see 658 associations roll by. > Here's the top of the list: > > .001=jZip.file > .386=vxdfile > .3g2=QuickTime.3g2 > .3gp=QuickTime.3gp > .3gp2=QuickTime.3gp2 > .3gpp=QuickTime.3gpp > .7Z=jZip.file > .aa=NeroShowTime.Files9.aa > .aac=QuickTime.aac > .ac3=QuickTime.ac3 > .aca=Agent.Character.2 > .acf=Agent.Character.2 > .acl=ACLFile > .acr=IrfanView.DCM > .acrobatsecuritysettings=AcroExch.acrobatsecuritysettings > .acs=Agent.Character2.2 > .acsm=Adobe.ACSMessage > .AddIn=VCExpress.AddIn.9.0 > .adts=QuickTime.adts > .aif=IrfanView.aif > .aifc=WMP11.AssocFile.AIFF > .aiff=WMP11.AssocFile.AIFF > .air=AIR.InstallerPackage > > I thought it would be convenient to have a Python script I could use > to look up unfamiliar file extensions. I assume one is possible, but > have no idea where to start, and would appreciate hints and > suggestions. > > Thanks, > > Dick Moores > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From rdmoores at gmail.com Fri Aug 6 17:28:35 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Fri, 6 Aug 2010 08:28:35 -0700 Subject: [Tutor] Seek suggestions for script for looking up extensions usingC:\>assoc In-Reply-To: <9C5927E386614F4C833B6141377CE905@dheiser> References: <9C5927E386614F4C833B6141377CE905@dheiser> Message-ID: On Fri, Aug 6, 2010 at 07:56, wrote: > > You wouldn't gain much with a Pyton script. You can specify the extension > with "assoc". > > Try "assoc .zip". > > But if you want to try it anyway, look at the "popen2" module (depreciated) > or the "subprocess" module to extract the data and assign it to a variable > that you can parse any way you like. Thanks! I think I will try it anyway, and am already reading the doc for the subprocess module. (Someone -- not this Tutoree -- is going to remind you not to top post.) Dick From ian at ianozsvald.com Fri Aug 6 18:19:46 2010 From: ian at ianozsvald.com (Ian Ozsvald) Date: Fri, 6 Aug 2010 17:19:46 +0100 Subject: [Tutor] Idea for a 'Weekly Python Tips' mailing list Message-ID: Hi all. I'm a long time Pythonista and co-founder of http://ShowMeDo.com/ (and author of 140 of the Python tutorials there), I'm here with an idea... Recently I've started to follow a couple of email lists that send me regular tip emails, I've found them to be rather nice - an easy to read tip that comes every week that I can digest when I'm ready and I can reference afterwards. I don't recall ever coming across a Python Learners tip series in this format and I'm guessing it would be well received. Could I get some feedback please? I've already planned a set of 10 weekly tips (each about 5 paragraphs of text plus code examples) covering a bunch of things that are useful for a new Python programmer. Some are about the 'right' way to write Python code, some introduce neat modules (like Excel, web scraping, processes), some show you how to do complex stuff (like 3D, web servers and faster mathematics) in just a few lines of Python. It would also be quite nice to wrap up some of the oft-asked Python Tutor questions into the tips (I always meant to create some ShowMeDo videos covering these problems but never had the time :-( ). Before proceeding I'd like to do a sanity check - has anyone done this already? I'd hate to re-invent the wheel! Assuming it hasn't been done - would *you* choose to subscribe to the list (it would be free, just an email, nothing complex and no spam/sillyness)? Just say 'yes' if so, that way I know there's an audience. If the interest is good then I'll extend the series of 10 and introduce some guest authors into the mix. Any takers? Ian. -- Ian Ozsvald (A.I. researcher, screencaster) ian at IanOzsvald.com http://IanOzsvald.com http://MorConsulting.com/ http://blog.AICookbook.com/ http://TheScreencastingHandbook.com http://FivePoundApp.com/ http://twitter.com/IanOzsvald From ehamiter at gmail.com Fri Aug 6 19:14:15 2010 From: ehamiter at gmail.com (Eric Hamiter) Date: Fri, 6 Aug 2010 12:14:15 -0500 Subject: [Tutor] Idea for a 'Weekly Python Tips' mailing list In-Reply-To: References: Message-ID: Your ideas are intriguing to me, and I wish to subscribe to your newsletter. Eric On Fri, Aug 6, 2010 at 11:19 AM, Ian Ozsvald wrote: > Hi all. I'm a long time Pythonista and co-founder of > http://ShowMeDo.com/ (and author of 140 of the Python tutorials > there), I'm here with an idea... > > Recently I've started to follow a couple of email lists that send me > regular tip emails, I've found them to be rather nice - an easy to > read tip that comes every week that I can digest when I'm ready and I > can reference afterwards. > > I don't recall ever coming across a Python Learners tip series in this > format and I'm guessing it would be well received. Could I get some > feedback please? > > I've already planned a set of 10 weekly tips (each about 5 paragraphs > of text plus code examples) covering a bunch of things that are useful > for a new Python programmer. Some are about the 'right' way to write > Python code, some introduce neat modules (like Excel, web scraping, > processes), some show you how to do complex stuff (like 3D, web > servers and faster mathematics) in just a few lines of Python. > > It would also be quite nice to wrap up some of the oft-asked Python > Tutor questions into the tips (I always meant to create some ShowMeDo > videos covering these problems but never had the time :-( ). > > Before proceeding I'd like to do a sanity check - has anyone done this > already? I'd hate to re-invent the wheel! > > Assuming it hasn't been done - would *you* choose to subscribe to the > list (it would be free, just an email, nothing complex and no > spam/sillyness)? Just say 'yes' if so, that way I know there's an > audience. > > If the interest is good then I'll extend the series of 10 and > introduce some guest authors into the mix. > > Any takers? > Ian. > > -- > Ian Ozsvald (A.I. researcher, screencaster) > ian at IanOzsvald.com > > http://IanOzsvald.com > http://MorConsulting.com/ > http://blog.AICookbook.com/ > http://TheScreencastingHandbook.com > http://FivePoundApp.com/ > http://twitter.com/IanOzsvald > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Fri Aug 6 19:51:12 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 07 Aug 2010 03:51:12 +1000 Subject: [Tutor] Idea for a 'Weekly Python Tips' mailing list In-Reply-To: References: Message-ID: On Fri, 6 Aug 2010 17:19:46 +0100, Ian Ozsvald wrote: > Recently I've started to follow a couple of email lists that send me > regular tip emails, I've found them to be rather nice - an easy to > read tip that comes every week that I can digest when I'm ready and I > can reference afterwards. In the main python list there is Python Weekly URL that summarizes the week's most interesting posts in c.l.py From sierra_mtnview at sbcglobal.net Fri Aug 6 19:51:50 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 06 Aug 2010 10:51:50 -0700 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? Message-ID: <4C5C4BB6.6040702@sbcglobal.net> Yes, porpoises was a (old) pun. Back in Feb. I raised a question related to Subject. I just wanted to know if Python code could be compiled in some sense. Robert Berman pitched in with some help. Although I was making progress, I put it off for a future date. I really don't want to get into py2exe here, but am wondering if there are Python vendors who in some way sell their product in compiled form? My intent though is really not to produce a commercial product. My question relates to difficulty my partner and I have to exchanging py programs w/o him stumbling. I send him a py program written using Windows Python 2.5. He has the same. I've executed it IDLE and it works fine. He executes, and it squawks per my post here on finding a version #, showing his output. We need to make sure we are on the same playing ground with numpy and scipy. I don't think we are. He barely knows Python, but did, supposedly, a install of it, numpy and scipy from the same written direction I use. I think he mistakenly installed a different version of numpy. So how can we make sure we or anyone are on the same playing field? Perhaps we should resort to command like execution. I am not confident that using py2exe will solve this problem. Is there a Python tool that provides some thorough description of a Python installation? -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "An experiment is a question which science poses to Nature, and a measurement is the recording of Nature?s answer." -- Max Planck Web Page: From cfuller084 at thinkingplanet.net Fri Aug 6 20:42:44 2010 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 6 Aug 2010 13:42:44 -0500 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? In-Reply-To: <4C5C4BB6.6040702@sbcglobal.net> References: <4C5C4BB6.6040702@sbcglobal.net> Message-ID: <201008061342.44812.cfuller084@thinkingplanet.net> It sounds like maybe you could use Enthought Python, which is a bundle of most of the popular numerical libraries by the scipy sponsors. Not free, however, there's a trial version. http://enthought.com/products/epd.php The problem of bundling stuff is a real thorny one and has been beaten to death many times in this list and elsewhere. It really doesn't solve the problem, anyway, if you want your friend to be able to play with and rerun the code. Another idea is to make a virtual machine that you can duplicate or even mail back and forth with just the stuff required. Then you'd need an OS license for it (or use a minimal Linux, like Arch or DSL, but you probably want to stick to the Windows platform, I'd guess.) Cheers On Friday 06 August 2010, Wayne Watson wrote: > Yes, porpoises was a (old) pun. > > Back in Feb. I raised a question related to Subject. I just wanted to > know if Python code could be compiled in some sense. Robert Berman > pitched in with some help. Although I was making progress, I put it off > for a future date. I really don't want to get into py2exe here, but am > wondering if there are Python vendors who in some way sell their product > in compiled form? > > My intent though is really not to produce a commercial product. My > question relates to difficulty my partner and I have to exchanging py > programs w/o him stumbling. I send him a py program written using > Windows Python 2.5. He has the same. I've executed it IDLE and it works > fine. He executes, and it squawks per my post here on finding a version > #, showing his output. We need to make sure we are on the same playing > ground with numpy and scipy. I don't think we are. He barely knows > Python, but did, supposedly, a install of it, numpy and scipy from the > same written direction I use. I think he mistakenly installed a > different version of numpy. So how can we make sure we or anyone are on > the same playing field? Perhaps we should resort to command like > execution. I am not confident that using py2exe will solve this problem. > Is there a Python tool that provides some thorough description of a > Python installation? From emile at fenx.com Fri Aug 6 23:18:50 2010 From: emile at fenx.com (Emile van Sebille) Date: Fri, 06 Aug 2010 14:18:50 -0700 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? In-Reply-To: <4C5C4BB6.6040702@sbcglobal.net> References: <4C5C4BB6.6040702@sbcglobal.net> Message-ID: On 8/6/2010 10:51 AM Wayne Watson said... > Yes, porpoises was a (old) pun. > > Back in Feb. I raised a question related to Subject. I just wanted to > know if Python code could be compiled in some sense. Robert Berman > pitched in with some help. Although I was making progress, I put it off > for a future date. I really don't want to get into py2exe here, but am > wondering if there are Python vendors who in some way sell their product > in compiled form? > I think you're making it harder. Go to your partners site, build an appropriate base environment, document and leave instructions on where to put new *.py modules you send him, run through it, and you're done. A little education will likely go a lot further than delving deeper into heavier technologies in an attempt to 'simplfy'. HTH, Emile From alan.gauld at btinternet.com Sat Aug 7 02:18:05 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 7 Aug 2010 01:18:05 +0100 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? References: <4C5C4BB6.6040702@sbcglobal.net> Message-ID: "Wayne Watson" wrote > programs w/o him stumbling. I send him a py program written using > Windows Python 2.5. He has the same. I've executed it IDLE and it > works fine. He executes, and it squawks IDLE is a development environment. Never, ever test final code in a development environment, test it as it should be run. Double click the file in explorer. Better still install a separate copy wherever the file will go on the target system - usually somewhere different to where you develop it - and run it there. > same written direction I use. I think he mistakenly installed a > different version of numpy. So how can we make sure we or anyone are > on the same playing field? Perhaps we should resort to command like > execution. You should definitely not run it from IDLE, that's inefficient and likely to hide errors. Run it from a command prompt or by double clicking in explorer, or create a shortcut on the desktop. To check the versions of your packages you could write a short test program that simply imports all needed modules and prints out the version info (if available) and file details xxx.__file__ You could even use the __file__ info to check the size of the files by using the os module functions. > Is there a Python tool that provides some thorough description of a > Python installation? I'm not aware of such but it should not be hard to check the basics. One of the best thins about Python is the high level of portability of programs across versions and OS. Its most likely a location or PATH setting HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From galaxywatcher at gmail.com Sat Aug 7 04:35:32 2010 From: galaxywatcher at gmail.com (TGW) Date: Fri, 6 Aug 2010 22:35:32 -0400 Subject: [Tutor] modify csv textfile Message-ID: <64671117-9283-423D-815A-8347D3E60FEC@gmail.com> I have a pipe delimited text file with 5 columns which looks like this: 12345|some text|some more text|example125 oo3 3456|example32423 11223|more text|and more|example/73d 77665|example455667 12677|text|more|anotherexample 123|anotherexample45 What I want to output is: 12345|some text|some more text|example|example32423 11223|more text|and more|example|example455667 ... 12677|text|more|anotherexample 123|anotherexample45 So column 4 is where the change occurs, but only if the beginning of the string in column 4 =~ /^example/i # and it should be case insensitive #!/usr/bin/env python import csv import re filename = raw_input("Enter the filename to edit: ") reader = csv.reader(open(filename, 'rb'), delimiter='|', quoting=csv.QUOTE_NONE) for row in reader: print row .... I can print the file, I just need a little help searching and replacing the column 4 data element. Thanks From buggyballs at gmail.com Sat Aug 7 05:14:59 2010 From: buggyballs at gmail.com (j ram) Date: Fri, 6 Aug 2010 20:14:59 -0700 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? In-Reply-To: References: <4C5C4BB6.6040702@sbcglobal.net> Message-ID: > > My intent though is really not to produce a commercial product. My question > relates to difficulty my partner and I have to exchanging py programs w/o > him stumbling. I send him a py program written using Windows Python 2.5. He > has the same. I've executed it IDLE and it works fine. He executes, and it > squawks per my post here on finding a version #, showing his output. We need > to make sure we are on the same playing ground with numpy and scipy. > > Why not try bundling your .py modules in a zip file and then importing the run modules from this zip file? In that way, the package integrity is ensured. You'd just have to ship your collaborator the zip archive and also make sure that both of you are running the same versions of numpy, scipy, python and other packages. http://docs.python.org/library/zipimport.html http://www.doughellmann.com/PyMOTW/zipimport/ Regards, Iyer -------------- next part -------------- An HTML attachment was scrubbed... URL: From pine508 at hotmail.com Sat Aug 7 05:38:04 2010 From: pine508 at hotmail.com (Che M) Date: Fri, 6 Aug 2010 23:38:04 -0400 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? In-Reply-To: <4C5C4BB6.6040702@sbcglobal.net> References: <4C5C4BB6.6040702@sbcglobal.net> Message-ID: > #, showing his output. We need to make sure we are on the same playing > ground with numpy and scipy. I don't think we are. He barely knows > Python, but did, supposedly, a install of it, numpy and scipy from the > same written direction I use. I think he mistakenly installed a > different version of numpy. So how can we make sure we or anyone are on > the same playing field? Both of you do this from IDLE: import numpy help(numpy) Read the version # at the end. -------------- next part -------------- An HTML attachment was scrubbed... URL: From prologic at shortcircuit.net.au Sat Aug 7 08:40:33 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Sat, 7 Aug 2010 16:40:33 +1000 Subject: [Tutor] modify csv textfile In-Reply-To: <64671117-9283-423D-815A-8347D3E60FEC@gmail.com> References: <64671117-9283-423D-815A-8347D3E60FEC@gmail.com> Message-ID: On Sat, Aug 7, 2010 at 12:35 PM, TGW wrote: > I have a pipe delimited text file with 5 columns which looks like this: > 12345|some text|some more text|example125 oo3 3456|example32423 > 11223|more text|and more|example/73d 77665|example455667 > 12677|text|more|anotherexample 123|anotherexample45 > > What I want to output is: > 12345|some text|some more text|example|example32423 > 11223|more text|and more|example|example455667 > ... > 12677|text|more|anotherexample 123|anotherexample45 > > So column 4 is where the change occurs, but only if the beginning of the string in column 4 ?=~ /^example/i ?# and it should be case insensitive So do it :) > #!/usr/bin/env python > import csv > import re > > filename = raw_input("Enter the filename to edit: ") > > reader = csv.reader(open(filename, 'rb'), delimiter='|', quoting=csv.QUOTE_NONE) > for row in reader: > ? ?print row > > .... > I can print the file, I just need a little help searching and replacing the column 4 data element. Use re.match to match the column. Use csv.writer to write our a new csv file based on the one you're reading, filtering and modifying. cheers James -- -- James Mills -- -- "Problems are solved by method" From sander.sweers at gmail.com Sat Aug 7 12:31:44 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 7 Aug 2010 12:31:44 +0200 Subject: [Tutor] modify csv textfile In-Reply-To: <64671117-9283-423D-815A-8347D3E60FEC@gmail.com> References: <64671117-9283-423D-815A-8347D3E60FEC@gmail.com> Message-ID: On 7 August 2010 04:35, TGW wrote: > I have a pipe delimited text file with 5 columns which looks like this: > 12345|some text|some more text|example125 oo3 3456|example32423 > 11223|more text|and more|example/73d 77665|example455667 > 12677|text|more|anotherexample 123|anotherexample45 > > What I want to output is: > 12345|some text|some more text|example|example32423 > 11223|more text|and more|example|example455667 > ... > 12677|text|more|anotherexample 123|anotherexample45 > > So column 4 is where the change occurs, but only if the beginning of the string in column 4 ?=~ /^example/i ?# and it should be case insensitive > > #!/usr/bin/env python > import csv > import re > > filename = raw_input("Enter the filename to edit: ") > > reader = csv.reader(open(filename, 'rb'), delimiter='|', quoting=csv.QUOTE_NONE) > for row in reader: > ? ?print row > > .... > I can print the file, I just need a little help searching and replacing the column 4 data element. You can test if one item in your list begins with example like: ' example125 oo3 3456'.lstrip()[:7].lower() == 'example' lstrip() will remove any unwanted white space on the left side of the string. slice [:7] will give you the first 7 characters from the string. lower() will make the string lower case so your requirement for case insensitive is met. Then your loop would look like (untested): for row in reader: if row[3].lstrip()[0:7].lower() == 'example': row[3] = row[3].lstrip()[:7] #we replace the fourth item. print row Greets Sander From galaxywatcher at gmail.com Sat Aug 7 13:45:16 2010 From: galaxywatcher at gmail.com (TGW) Date: Sat, 7 Aug 2010 07:45:16 -0400 Subject: [Tutor] modify csv textfile In-Reply-To: References: <64671117-9283-423D-815A-8347D3E60FEC@gmail.com> Message-ID: > You can test if one item in your list begins with example like: > ' example125 oo3 3456'.lstrip()[:7].lower() == 'example' I think I need to use regex here. Perhaps you will agree. Input file: 1119|Avail|53|Potato Chips 1234|Avail|53|Potato Chips and salse 1399|Avail|53|potato chips 1445|Avail|64|Pretzels 1490|Avail|64|Pretzels and mustard etc... #!/usr/bin/env python import csv import re filename = raw_input("Enter the filename to edit: ") reader = csv.reader(open(filename, 'rb'), delimiter='|', quoting=csv.QUOTE_NONE) for row in reader: if re.match('potato chips.*', row[4].lower()): row[4] = 'Potato Chips' if re.match('^pretzels.*', row[4].lower()): row[4] = 'Pretzels' print row Row will be variable length, so strip() will not work for me. But neither does my latest attempt ^^ From alan.gauld at btinternet.com Sat Aug 7 13:26:34 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 7 Aug 2010 12:26:34 +0100 Subject: [Tutor] modify csv textfile References: <64671117-9283-423D-815A-8347D3E60FEC@gmail.com> Message-ID: "TGW" wrote > > What I want to output is: > 12345|some text|some more text|example|example32423 > 11223|more text|and more|example|example455667 > > So column 4 is where the change occurs, but only if the beginning > of the string in column 4 =~ /^example/i # and it should be case > insensitive > > reader = csv.reader(open(filename, 'rb'), delimiter='|', > quoting=csv.QUOTE_NONE) > for row in reader: > print row > > .... > I can print the file, I just need a little help searching and > replacing the column 4 data element. OK, so I'm not sure which bit is confusing you. The reader returns a list of fields per row. You want the fourth column which is element 3 in row - ie. row[3] You can use startswith() or a regex to test the value You can replace the string with whatever you like since lists are mutable You can then store/write the modified list to whatever/wherever you like. Now which bit of that is causing you grief? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From smokefloat at gmail.com Sat Aug 7 14:26:19 2010 From: smokefloat at gmail.com (David Hutto) Date: Sat, 7 Aug 2010 08:26:19 -0400 Subject: [Tutor] modify csv textfile In-Reply-To: References: <64671117-9283-423D-815A-8347D3E60FEC@gmail.com> Message-ID: On Sat, Aug 7, 2010 at 7:26 AM, Alan Gauld wrote: > > "TGW" wrote >> >> What I want to output is: >> 12345|some text|some more text|example|example32423 >> 11223|more text|and more|example|example455667 >> >> So column 4 is where the change occurs, but only if the beginning >> of the string in column 4 ?=~ /^example/i ?# and it should be case >> insensitive >> > >> reader = csv.reader(open(filename, 'rb'), delimiter='|', >> quoting=csv.QUOTE_NONE) >> for row in reader: >> ? print row >> >> .... >> I can print the file, I just need a little help searching and replacing >> the column 4 data element. > > OK, so I'm not sure which bit is confusing you. > The reader returns a list of fields per row. > You want the fourth column which is element 3 in row - ie. row[3] > You can use startswith() or a regex to test the value > You can replace the string with whatever you like since lists are mutable > You can then store/write the modified list to whatever/wherever you like. > > Now which bit of that is causing you grief? Probably the explanation. Mainly because of lack of documentation than google terms, and appropriate questions > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From smokefloat at gmail.com Sat Aug 7 14:27:37 2010 From: smokefloat at gmail.com (David Hutto) Date: Sat, 7 Aug 2010 08:27:37 -0400 Subject: [Tutor] modify csv textfile In-Reply-To: References: <64671117-9283-423D-815A-8347D3E60FEC@gmail.com> Message-ID: On Sat, Aug 7, 2010 at 8:26 AM, David Hutto wrote: > On Sat, Aug 7, 2010 at 7:26 AM, Alan Gauld wrote: >> >> "TGW" wrote >>> >>> What I want to output is: >>> 12345|some text|some more text|example|example32423 >>> 11223|more text|and more|example|example455667 >>> >>> So column 4 is where the change occurs, but only if the beginning >>> of the string in column 4 ?=~ /^example/i ?# and it should be case >>> insensitive >>> >> >>> reader = csv.reader(open(filename, 'rb'), delimiter='|', >>> quoting=csv.QUOTE_NONE) >>> for row in reader: >>> ? print row >>> >>> .... >>> I can print the file, I just need a little help searching and replacing >>> the column 4 data element. >> >> OK, so I'm not sure which bit is confusing you. >> The reader returns a list of fields per row. >> You want the fourth column which is element 3 in row - ie. row[3] >> You can use startswith() or a regex to test the value >> You can replace the string with whatever you like since lists are mutable >> You can then store/write the modified list to whatever/wherever you like. >> >> Now which bit of that is causing you grief? > > Probably the explanation. Mainly because of lack of documentation than > google terms, Not to say that docs are laccking to the proportion of want. and appropriate questions >> >> -- >> Alan Gauld >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> >> >> _______________________________________________ >> Tutor maillist ?- ?Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > From sander.sweers at gmail.com Sat Aug 7 16:19:05 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Sat, 7 Aug 2010 16:19:05 +0200 Subject: [Tutor] modify csv textfile In-Reply-To: References: <64671117-9283-423D-815A-8347D3E60FEC@gmail.com> Message-ID: On 7 August 2010 13:45, TGW wrote: >> You can test if one item in your list begins with example like: >> ' example125 oo3 3456'.lstrip()[:7].lower() == 'example' > > I think I need to use regex here. Perhaps you will agree. You could but you don't have to, consider this. r = '1234|Avail|53|Potato Chips and salse'.split('|') s = 'potato chips' if r[3].lstrip().lower().startswith(s): r[3] = r[3].lstrip()[:len(s)] print r > Input file: > 1119|Avail|53|Potato Chips > 1234|Avail|53|Potato Chips and salse > 1399|Avail|53|potato chips > 1445|Avail|64|Pretzels > 1490|Avail|64|Pretzels and mustard > etc... > > #!/usr/bin/env python > import csv > import re > > filename = raw_input("Enter the filename to edit: ") > > reader = csv.reader(open(filename, 'rb'), delimiter='|', quoting=csv.QUOTE_NONE) > for row in reader: > ? ?if re.match('potato chips.*', row[4].lower()): > ? ? ? ?row[4] = 'Potato Chips' > > ? ?if re.match('^pretzels.*', row[4].lower()): > ? ? ? ?row[4] = 'Pretzels' > > ? ?print row Python start numbering indexes at 0 so row[4] is the *5th* item item in your list. > Row will be variable length, so strip() will not work for me. I did not use strip() but lstrip() and only to remove leading whitespace..? However strip only removes the _leading and trailing_ whitespace or character(s) you pass it. > But neither does my latest attempt ^^ With the info and example data provided this would surely have given an IndexError. So if you run into an exception you need to provide them as they will be giving clues where it is going wrong. Greets Sander From sierra_mtnview at sbcglobal.net Sat Aug 7 17:05:48 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 07 Aug 2010 08:05:48 -0700 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? In-Reply-To: <201008061342.44812.cfuller084@thinkingplanet.net> References: <4C5C4BB6.6040702@sbcglobal.net> <201008061342.44812.cfuller084@thinkingplanet.net> Message-ID: <4C5D764C.7040001@sbcglobal.net> Thanks, but my partner has enough difficulty with a simple Python install, let alone VM or anything beyond Windows. On 8/6/2010 11:42 AM, Chris Fuller wrote: > It sounds like maybe you could use Enthought Python, which is a bundle of most > of the popular numerical libraries by the scipy sponsors. Not free, however, > there's a trial version. > > http://enthought.com/products/epd.php > > The problem of bundling stuff is a real thorny one and has been beaten to death > many times in this list and elsewhere. It really doesn't solve the problem, > anyway, if you want your friend to be able to play with and rerun the code. > > Another idea is to make a virtual machine that you can duplicate or even mail > back and forth with just the stuff required. Then you'd need an OS license for > it (or use a minimal Linux, like Arch or DSL, but you probably want to stick > to the Windows platform, I'd guess.) > > Cheers > > On Friday 06 August 2010, Wayne Watson wrote: > >> Yes, porpoises was a (old) pun. >> >> Back in Feb. I raised a question related to Subject. I just wanted to >> know if Python code could be compiled in some sense. Robert Berman >> pitched in with some help. Although I was making progress, I put it off >> for a future date. I really don't want to get into py2exe here, but am >> wondering if there are Python vendors who in some way sell their product >> in compiled form? >> >> My intent though is really not to produce a commercial product. My >> question relates to difficulty my partner and I have to exchanging py >> programs w/o him stumbling. I send him a py program written using >> Windows Python 2.5. He has the same. I've executed it IDLE and it works >> fine. He executes, and it squawks per my post here on finding a version >> #, showing his output. We need to make sure we are on the same playing >> ground with numpy and scipy. I don't think we are. He barely knows >> Python, but did, supposedly, a install of it, numpy and scipy from the >> same written direction I use. I think he mistakenly installed a >> different version of numpy. So how can we make sure we or anyone are on >> the same playing field? Perhaps we should resort to command like >> execution. I am not confident that using py2exe will solve this problem. >> Is there a Python tool that provides some thorough description of a >> Python installation? >> > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "An experiment is a question which science poses to Nature, and a measurement is the recording of Nature?s answer." -- Max Planck Web Page: From sierra_mtnview at sbcglobal.net Sat Aug 7 17:16:17 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 07 Aug 2010 08:16:17 -0700 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? In-Reply-To: References: <4C5C4BB6.6040702@sbcglobal.net> Message-ID: <4C5D78C1.5050803@sbcglobal.net> Yes, that might work, but it gets into other issues that I would rather avoid. I hope I mentioned in my original msg that this is a Windows envirnoment. I don't know much about dsutils, but it might work for these situations. Just enough to mention it seems like it package an environment. An easy way out might be to ask him to uninstall Python and any modules like numpy. I'm not even sure how to do that. I don't think there's an uninstaller for all the Python stuff, so it's probably a matter of simply uninstalling Py 2.5 via MS control panel, and then directly deleting the modules like numpy and scipy. After that, he should be able to follow the instructions written by the sponsor. On 8/6/2010 2:18 PM, Emile van Sebille wrote: > On 8/6/2010 10:51 AM Wayne Watson said... >> Yes, porpoises was a (old) pun. >> >> Back in Feb. I raised a question related to Subject. I just wanted to >> know if Python code could be compiled in some sense. Robert Berman >> pitched in with some help. Although I was making progress, I put it off >> for a future date. I really don't want to get into py2exe here, but am >> wondering if there are Python vendors who in some way sell their product >> in compiled form? >> > > I think you're making it harder. Go to your partners site, build an > appropriate base environment, document and leave instructions on where > to put new *.py modules you send him, run through it, and you're done. > > A little education will likely go a lot further than delving deeper > into heavier technologies in an attempt to 'simplfy'. > > HTH, > > Emile > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "An experiment is a question which science poses to Nature, and a measurement is the recording of Nature?s answer." -- Max Planck Web Page: From g.nius.ck at gmail.com Sat Aug 7 17:43:25 2010 From: g.nius.ck at gmail.com (Chris King) Date: Sat, 07 Aug 2010 11:43:25 -0400 Subject: [Tutor] Word to Sound Message-ID: <4C5D7F1D.3030809@gmail.com> Dear Tutors, How do you convert a string into a sound object. Sincerely, Chris From steve at pearwood.info Sat Aug 7 17:46:57 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 8 Aug 2010 01:46:57 +1000 Subject: [Tutor] Word to Sound In-Reply-To: <4C5D7F1D.3030809@gmail.com> References: <4C5D7F1D.3030809@gmail.com> Message-ID: <201008080146.58449.steve@pearwood.info> On Sun, 8 Aug 2010 01:43:25 am Chris King wrote: > Dear Tutors, > How do you convert a string into a sound object. What do you mean by "sound object"? Can you give an example of what you want to do? -- Steven D'Aprano From sierra_mtnview at sbcglobal.net Sat Aug 7 17:54:10 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 07 Aug 2010 08:54:10 -0700 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? In-Reply-To: References: <4C5C4BB6.6040702@sbcglobal.net> Message-ID: <4C5D81A2.7050907@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sat Aug 7 17:54:45 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 07 Aug 2010 08:54:45 -0700 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? In-Reply-To: References: <4C5C4BB6.6040702@sbcglobal.net> Message-ID: <4C5D81C5.4050505@sbcglobal.net> An HTML attachment was scrubbed... URL: From g.nius.ck at gmail.com Sat Aug 7 17:59:14 2010 From: g.nius.ck at gmail.com (Chris King) Date: Sat, 07 Aug 2010 11:59:14 -0400 Subject: [Tutor] LOCATION ISSUES In-Reply-To: References: Message-ID: <4C5D82D2.3070804@gmail.com> On 7/13/2010 2:13 AM, Dipo Elegbede wrote: > Hello All, > Kindly help me with the location for the files created by this codes. > I have already compiled the codes and it has no error. > I copied the code from the following url: > http://www.pythonware.com/library/pil/handbook/image.htm > This is supposed to create thumbnails of picture in the directory > where I saved my file. > Please Help. > Thank You. > > -- > Elegbede Muhammed Oladipupo > OCA > +2348077682428 > +2347042171716 > www.dudupay.com > Mobile Banking Solutions | Transaction Processing | Enterprise > Application Development > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Well I don't have the module on this computer, but, try using the help function. It will show the description of any object, made by the creator. Its built in so it doesn't need imported. It is always will tell you what something is. It is like X-ray vision. Sincerely, Me (P.S. Its funny, techinicly help is a function, its just a callable object.) -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Sat Aug 7 18:22:05 2010 From: emile at fenx.com (Emile van Sebille) Date: Sat, 07 Aug 2010 09:22:05 -0700 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? In-Reply-To: <4C5D78C1.5050803@sbcglobal.net> References: <4C5C4BB6.6040702@sbcglobal.net> <4C5D78C1.5050803@sbcglobal.net> Message-ID: On 8/7/2010 8:16 AM Wayne Watson said... > > An easy way out might be to ask him to uninstall Python and any modules > like numpy. I'm not even sure how to do that. More reasons to start out simpler. Have your partner install one of the remote access tools (GoToMyPC, LogMeIn, VNC, etc) and do the work yourself. And then install the changes yourself. Again, the practice on both systems will probably benefit you more at this stage than advanced technologies. Familiarizing yourself with the actions automated installation is required to perform will help you understand the tools better, and provides clues debugging the results when it doesn't quite work right. Don't make it any harder than it needs to be. Ultimately, a single byte update to a .py file shouldn't be any more involved than replacing the old file with the new revised file. I'd use the links below -- there doesn't yet seem to be a 2.7 compatible released version of scipy yet, so this lists the most current compatible set of installable binaries. As others have mentioned, don't use idle as you're doing. Give pythonwin (included with the activestate distribution) a try. Or try one of the free versions of Komodo or Wing. HTH, Emile http://downloads.activestate.com/ActivePython/releases/2.6.5.14/ActivePython-2.6.5.14-win32-x86.msi http://sourceforge.net/projects/numpy/files/NumPy/1.5.0b1/numpy-1.5.0b1-win32-superpack-python2.6.exe/download http://sourceforge.net/projects/scipy/files/scipy/0.8.0/scipy-0.8.0-win32-superpack-python2.6.exe/download From sierra_mtnview at sbcglobal.net Sat Aug 7 18:38:20 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 07 Aug 2010 09:38:20 -0700 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? In-Reply-To: References: <4C5C4BB6.6040702@sbcglobal.net> Message-ID: <4C5D8BFC.5000000@sbcglobal.net> (I cancelled the post, since the file was 120K, and unacceptable. It's now 27K, so everyone should see it, but the print might be a bit tiny.) Sounds like a plan. I'll give it a go. For what it's worth, our sponsor has suggested it was the way to go, i.e., use IDLE to execute it, his large app. Over the last 24 months though I've discovered our sponsor, while able to produce good python code, is not real deep in understanding the Python world, environment. Worse they decided to improve the app Actually, I stumbled across the code you mention below to reveal version and dependencies. I may have it operational soon. OK, I just ran it with the double click method, and am attaching a snapshot of what I got. I was unable to copy it from the command window. I think I can fix that, but it would just take too much time now. In the event the attachment doesn't get to you or not posted, the program generated warning messages about NumpyTest().test, but opened cleanly with a prompt. The code I posted in the other thread results in a similar result, but the program dies immediately. The output also shows NumpyTest will be removed in the next release (of Numpy?), and that may be where my partner went wrong. I'm pretty sure he jumped ahead of my versions despite my cautions. On 8/6/2010 5:18 PM, Alan Gauld wrote: > "Wayne Watson" wrote > >> programs w/o him stumbling. I send him a py program written using >> Windows Python 2.5. He has the same. I've executed it IDLE and it >> works fine. He executes, and it squawks > > IDLE is a development environment. Never, ever test final code in > a development environment, test it as it should be run. Double click > the file in explorer. Better still install a separate copy wherever the > file will go on the target system - usually somewhere different to > where you develop it - and run it there. > >> same written direction I use. I think he mistakenly installed a >> different version of numpy. So how can we make sure we or anyone are >> on the same playing field? Perhaps we should resort to command like >> execution. > > You should definitely not run it from IDLE, that's inefficient and > likely to hide errors. Run it from a command prompt or by double > clicking in explorer, or create a shortcut on the desktop. > > To check the versions of your packages you could write a short > test program that simply imports all needed modules and prints > out the version info (if available) and file details xxx.__file__ > > You could even use the __file__ info to check the size of the files > by using the os module functions. > >> Is there a Python tool that provides some thorough description of a >> Python installation? > > I'm not aware of such but it should not be hard to check the basics. > One of the best thins about Python is the high level of portability > of programs across versions and OS. Its most likely a location > or PATH setting > > HTH, > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "An experiment is a question which science poses to Nature, and a measurement is the recording of Nature?s answer." -- Max Planck Web Page: -------------- next part -------------- A non-text attachment was scrubbed... Name: py_cmdline_testx.jpg Type: image/jpeg Size: 27379 bytes Desc: not available URL: From shurui.liu at hotmail.com Sat Aug 7 21:17:50 2010 From: shurui.liu at hotmail.com (Shurui Liu) Date: Sat, 7 Aug 2010 15:17:50 -0400 Subject: [Tutor] word_probles.py Message-ID: print \ """ If a pregnant hippo, weighing 2,000 pounds, gives birth to a 100 pound calf, but then eats 50 pounds of food, how much does she weigh?""" raw_input("Press the enter key to find out.") print "2000 - 100 + 50 = ", print 2000 - 100 + 50 print \ """ If an adventurer returns from a successful quest and buys each of 6 companions 3 bottles of ale, how many bottles does the adventurer buy?""" raw_input("Press the enter key to find out.") print "6 * 3 = ", print 6 * 3 print \ """ If a kid has 24 pieces of Halloween candy and eats 6 pieces a day, how many days will the stash last?""" raw_input("Press the enter key to find out.") print "24 / 6 = ", print 24 / 6 print \ """ If a group of 4 pirates finds a chest full of 107 gold coins, and they divide the booty evenly, how many coins will be left over?""" raw_input("Press the enter key to find out.") print "107 % 4 = ", print 107 % 4 print \ """ If a restaurant check comes to 19 dollars with tip, and you and your friends split it evenly 4 ways, how much do you each throw in?""" raw_input("Press the enter key to find out.") print "19 / 4 = ", print 19 / 4 print "WRONG!" raw_input("Press the enter key for the right answer.") print 19.0 / 4 raw_input("\n\nPress the enter key to exit.") Here is a code named "word_problems.py". I can run it on putty.exe, but I don't understand why I cannot run it on IDLE or pyscripter.exe. Both of these two platform show that there are syntax errors in the code, errors are on those red lines. Thanks! ############################## Never had, never will. -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Sat Aug 7 22:25:55 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Sat, 7 Aug 2010 15:25:55 -0500 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? In-Reply-To: <4C5D8BFC.5000000@sbcglobal.net> References: <4C5C4BB6.6040702@sbcglobal.net> <4C5D8BFC.5000000@sbcglobal.net> Message-ID: I just noticed this thread - if you want a great version of python that has numpy/scipy so you can be sure to have the same version, use Python XY: http://www.pythonxy.com/ It's got a host of scientific packages such as matplotlib, numpy, and scipy. Then it has all sorts of other bells and whistles, as well. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Sat Aug 7 22:28:30 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Sat, 7 Aug 2010 15:28:30 -0500 Subject: [Tutor] word_probles.py In-Reply-To: References: Message-ID: On Sat, Aug 7, 2010 at 2:17 PM, Shurui Liu wrote: > > Here is a code named "word_problems.py". I can run it on putty.exe, but I > don't understand why I cannot run it on IDLE or pyscripter.exe. Both of > these two platform show that there are syntax errors in the code, errors > are on those red lines. Thanks! > Please post the traceback when asking about errors - they're incredibly useful! -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sat Aug 7 22:34:12 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 07 Aug 2010 13:34:12 -0700 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? In-Reply-To: References: <4C5C4BB6.6040702@sbcglobal.net> <4C5D8BFC.5000000@sbcglobal.net> Message-ID: <4C5DC344.9070909@sbcglobal.net> Thanks. Looks interesting. On 8/7/2010 1:25 PM, Wayne Werner wrote: > I just noticed this thread - if you want a great version of python > that has numpy/scipy so you can be sure to have the same version, use > Python XY: http://www.pythonxy.com/ > > It's got a host of scientific packages such as matplotlib, numpy, and > scipy. Then it has all sorts of other bells and whistles, as well. > > HTH, > Wayne -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "An experiment is a question which science poses to Nature, and a measurement is the recording of Nature?s answer." -- Max Planck Web Page: From rdmoores at gmail.com Sat Aug 7 23:04:33 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 7 Aug 2010 14:04:33 -0700 Subject: [Tutor] os.urandom() Message-ID: using Vista, Python 3.1: >>> import os >>> os.urandom(6) b'\xd1\xfc\xb0\x14\xeaL' So what is this output? What in ascii? What in hex? Do those questions even make sense? I've tried 2 things to get at it: >>> import binascii >>> binascii.b2a_qp(b'\xd1\xfc\xb0\x14\xeaL') b'=D1=FC=B0=14=EAL' >>> binascii.b2a_hex(b'\xd1\xfc\xb0\x14\xeaL') b'd1fcb014ea4c' Help, please. Dick Moores >>> import binascii >>> binascii.b2a_qp(b'\x05\x8aU\x92\xf3R') b'=05=8AU=92=F3R' >>> binascii.b2a_hex(b'\x05\x8aU\x92\xf3R') b'058a5592f352' From alan.gauld at btinternet.com Sun Aug 8 00:26:57 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 7 Aug 2010 23:26:57 +0100 Subject: [Tutor] os.urandom() References: Message-ID: "Richard D. Moores" wrote >>>> import os >>>> os.urandom(6) > b'\xd1\xfc\xb0\x14\xeaL' > > So what is this output? What in ascii? What in hex? Do those > questions even make sense? The documentation tells you: os.urandom(n)? Return a string of n random bytes suitable for cryptographic use. So its a string of 5 bytes(*) generated at random by some random generator function in your OS. What do you not understand? What did you expect? Python is telling you its bytes with the b at the front. The \x tells you they are hex values. (*)The fact its 5 is odd since you seem to pass 6 as an argument! When I try it I get 6 bytes back. Does that help? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From evert.rol at gmail.com Sun Aug 8 00:29:25 2010 From: evert.rol at gmail.com (Evert Rol) Date: Sun, 8 Aug 2010 00:29:25 +0200 Subject: [Tutor] os.urandom() In-Reply-To: References: Message-ID: > > > using Vista, Python 3.1: > >>>> import os >>>> os.urandom(6) > b'\xd1\xfc\xb0\x14\xeaL' > > So what is this output? What in ascii? What in hex? Do those > questions even make sense? It returns just what it says in the docs: "a string of [6] random bytes" You can convert the bytes to characters using eg chr(): >>> [a for a in map(chr, os.urandom(6))] ['?', '?', 'P', '?', '?', 'C'] Not all converted bytes will be printable characters, so some may appear with the \x still prepended (eg, control characters). Does that help? What actually do you wish to achieve in the first place? > I've tried 2 things to get at it: >>>> import binascii >>>> binascii.b2a_qp(b'\xd1\xfc\xb0\x14\xeaL') > b'=D1=FC=B0=14=EAL' >>>> binascii.b2a_hex(b'\xd1\xfc\xb0\x14\xeaL') > b'd1fcb014ea4c' > > Help, please. > > Dick Moores > > > > > >>>> import binascii >>>> binascii.b2a_qp(b'\x05\x8aU\x92\xf3R') > b'=05=8AU=92=F3R' >>>> binascii.b2a_hex(b'\x05\x8aU\x92\xf3R') > b'058a5592f352' > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Sun Aug 8 00:33:03 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 7 Aug 2010 23:33:03 +0100 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? References: <4C5C4BB6.6040702@sbcglobal.net> <4C5D78C1.5050803@sbcglobal.net> Message-ID: "Emile van Sebille" wrote > As others have mentioned, don't use idle as you're doing. Give > pythonwin (included with the activestate distribution) a try. Or > try one of the free versions of Komodo or Wing. In fact I'd strongly recommend not to use ANY development tool to run your programs. These tools are designed to make life easy while writing code, they are not intended to be used to execute final code. They trap errors, they redirect output, they ignore signals and all manner of things intended to prevent you from having to restart your development tool while developing. But those traps are hiding errors that will crop up in the real world. Always test deployable code in a real, native execution environment - outside the development tool and outside the development folder structure too. Include the installation process (whether automated or manual) in your test. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rdmoores at gmail.com Sun Aug 8 01:32:02 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 7 Aug 2010 16:32:02 -0700 Subject: [Tutor] os.urandom() In-Reply-To: References: Message-ID: On Sat, Aug 7, 2010 at 15:26, Alan Gauld wrote: > Python is telling you its bytes with the b at the front. > The \x tells you they are hex values. > > (*)The fact its 5 is odd since you seem to pass 6 as an argument! > When I try it I get 6 bytes back. Yes, the number of bytes seems to <= 6, or is it?: >>> os.urandom(6) b'\xf1\x1c\x15\x83\x14\x0e' >>> os.urandom(6) b'l\xbb\xae\xb7\x0ft' >>> os.urandom(6) b'\x1f\x00~\xfbz\x98' >>> os.urandom(6) b'\x98\xd2\xb2\xaa\x9bv' >>> os.urandom(6) b'2\x07\x81v\n-' >>> os.urandom(6) b'\x93\x1d\x1a\xa1\x0e\x1d' >>> os.urandom(6) b'`G\xa9_\xbab' >>> os.urandom(6) b'\r\xb0?p\x85\xc7' >>> os.urandom(6) b'\xb5\x1cn!\x93\xf4' >>> os.urandom(6) b'M\x0f\x1f34B' And what's with the l in b'l\xbb\xae\xb7\x0ft' ? the 2 in b'2\x07\x81v\n-' ? the `G in b'`G\xa9_\xbab' ? the \r in b'\r\xb0?p\x85\xc7' ? the M in b'M\x0f\x1f34B' ? Alan, are you using Windows, as I am? I apologize to all for not explaining what I'm trying to accomplish. I just ran across os.urandom() and am trying to understand it. I have a script that I use to create passwords for my various website accounts, , but wondered if website-permitted, but stronger passwords could be generated with the use of os.urandom(). At this point, I think not. (To Steven D'Aprano: yeah I know now, thanks to you, that the organization and modularization of > is woefully deficient :) ) Dick From bgailer at gmail.com Sun Aug 8 01:34:32 2010 From: bgailer at gmail.com (bob gailer) Date: Sat, 07 Aug 2010 19:34:32 -0400 Subject: [Tutor] os.urandom() In-Reply-To: References: Message-ID: <4C5DED88.2060903@gmail.com> On 8/7/2010 6:29 PM, Evert Rol wrote: > [a for a in map(chr, os.urandom(6))] > Overkill! map(chr, os.urandom(6)) is sufficient. Or [chr(x) for x in os.urandom(6))] The latter is easier to read. -- Bob Gailer 919-636-4239 Chapel Hill NC From rdmoores at gmail.com Sun Aug 8 01:47:26 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 7 Aug 2010 16:47:26 -0700 Subject: [Tutor] os.urandom() In-Reply-To: References: Message-ID: On Sat, Aug 7, 2010 at 15:01, Dominik Danter wrote: > You could try something like binascii.hexlify(os.urandom(6)) to create hex. >>> os.urandom(6) b'f\xc8rnr\xea' >>> binascii.hexlify(b'f\xc8rnr\xea') b'66c8726e72ea' >>> os.urandom(6) b'D\xe9?\xda\xd80' >>> binascii.hexlify(b'D\xe9?\xda\xd80') b'44e93fdad830' Thanks, but I'm not sure what to do with that.. What I am now sure of, is that I'm multiple steps ahead of myself with os.urandom() ! Dick From rdmoores at gmail.com Sun Aug 8 01:55:43 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 7 Aug 2010 16:55:43 -0700 Subject: [Tutor] os.urandom() In-Reply-To: <4C5DED88.2060903@gmail.com> References: <4C5DED88.2060903@gmail.com> Message-ID: On Sat, Aug 7, 2010 at 16:34, bob gailer wrote: > [chr(x) for x in os.urandom(6))] Correcting this to [chr(x) for x in os.urandom(6)], most of the time I get an error: >>> [chr(x) for x in os.urandom(6)] Traceback (most recent call last): File "", line 1, in File "C:\Python31\lib\encodings\cp437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\xb9' in position 12: character maps to But once in a while it works: >>> [chr(x) for x in os.urandom(6)] ['\x9d', '\x9b', '\x0e', '?', '^', 'N'] (remember, I'm using Windows) Dick From alan.gauld at btinternet.com Sun Aug 8 02:00:30 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 8 Aug 2010 01:00:30 +0100 Subject: [Tutor] os.urandom() References: Message-ID: "Richard D. Moores" wrote > Yes, the number of bytes seems to <= 6, or is it?: >>>> os.urandom(6) > b'\xf1\x1c\x15\x83\x14\x0e' ok >>>> os.urandom(6) > b'l\xbb\xae\xb7\x0ft' still ok - the l and t at the ends are valid characters so Python prints the letter >>>> os.urandom(6) > b'\x1f\x00~\xfbz\x98' Same here with the ~ and z characters >>>> os.urandom(6) > b'\x98\xd2\xb2\xaa\x9bv' and the (second) a and v >>>> os.urandom(6) > b'2\x07\x81v\n-' and the 2, v and - Also notice the eol character in there(\n) Hopefully you get the picture? > Alan, are you using Windows, as I am? Yes. XP. > website-permitted, but stronger passwords could be generated with > the > use of os.urandom(). At this point, I think not. You probably could but it would take a lot of work for very little benefit. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Aug 8 02:02:20 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 8 Aug 2010 01:02:20 +0100 Subject: [Tutor] os.urandom() References: Message-ID: "Richard D. Moores" wrote >> (*)The fact its 5 is odd since you seem to pass 6 as an argument! >> When I try it I get 6 bytes back. For some reason I never spotted the L at the end of the string last time. So it was 6 bytes. I suspect the L was read (by me) as the L at the end of a Long integer... even though you don't get them in v3! Alan G. From shurui.liu at hotmail.com Sun Aug 8 02:12:36 2010 From: shurui.liu at hotmail.com (Shurui Liu) Date: Sat, 7 Aug 2010 20:12:36 -0400 Subject: [Tutor] word_probles.py In-Reply-To: References: , Message-ID: There is no tracebacks. I can run this program on putty.exe. That means the code is correct, but I cannot run it on IDLE or PyScripter.exe. Both of these two platforms only told me "Syntax Error" without tracebacks or something. ############################## Never had, never will. From: waynejwerner at gmail.com Date: Sat, 7 Aug 2010 15:28:30 -0500 Subject: Re: [Tutor] word_probles.py To: shurui.liu at hotmail.com CC: tutor at python.org On Sat, Aug 7, 2010 at 2:17 PM, Shurui Liu wrote: Here is a code named "word_problems.py". I can run it on putty.exe, but I don't understand why I cannot run it on IDLE or pyscripter.exe. Both of these two platform show that there are syntax errors in the code, errors are on those red lines. Thanks! Please post the traceback when asking about errors - they're incredibly useful! -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Sun Aug 8 03:09:04 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sat, 7 Aug 2010 20:09:04 -0500 Subject: [Tutor] word_probles.py In-Reply-To: References: Message-ID: On Sat, Aug 7, 2010 at 7:12 PM, Shurui Liu wrote: > There is no tracebacks. > > I can run this program on putty.exe. That means the code is correct, but I > cannot run it on IDLE or PyScripter.exe. Both of these two platforms only > told me "Syntax Error" without tracebacks or something. > We'll need to know python versions. The machine you're running it on through putty might have 2.x while your local machine has 3.x, that would cause a problem like this. Hugo From sierra_mtnview at sbcglobal.net Sun Aug 8 03:43:45 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 07 Aug 2010 18:43:45 -0700 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? In-Reply-To: References: <4C5C4BB6.6040702@sbcglobal.net> <4C5D78C1.5050803@sbcglobal.net> Message-ID: <4C5E0BD1.1080000@sbcglobal.net> I think I'll print this and paste into the inside cover of my Python book. :-) I find it interesting that any Python book I've seen doesn't deal with distributing programs in some form or another. On 8/7/2010 3:33 PM, Alan Gauld wrote: > "Emile van Sebille" wrote >> As others have mentioned, don't use idle as you're doing. Give >> pythonwin (included with the activestate distribution) a try. Or try >> one of the free versions of Komodo or Wing. > > In fact I'd strongly recommend not to use ANY development tool to > run your programs. These tools are designed to make life easy while > writing code, they are not intended to be used to execute final code. > They trap errors, they redirect output, they ignore signals and all > manner of things intended to prevent you from having to restart > your development tool while developing. But those traps are > hiding errors that will crop up in the real world. > > Always test deployable code in a real, native execution environment > - outside the development tool and outside the development folder > structure too. Include the installation process (whether automated > or manual) in your test. > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "An experiment is a question which science poses to Nature, and a measurement is the recording of Nature?s answer." -- Max Planck Web Page: From steve at pearwood.info Sun Aug 8 07:47:16 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 8 Aug 2010 15:47:16 +1000 Subject: [Tutor] os.urandom() In-Reply-To: References: Message-ID: <201008081547.17553.steve@pearwood.info> On Sun, 8 Aug 2010 09:32:02 am Richard D. Moores wrote: > On Sat, Aug 7, 2010 at 15:26, Alan Gauld wrote: > > Python is telling you its bytes with the b at the front. > > The \x tells you they are hex values. > > > > (*)The fact its 5 is odd since you seem to pass 6 as an argument! > > When I try it I get 6 bytes back. > > Yes, the number of bytes seems to <= 6, or is it?: No, it's 6. The underlying urandom generator *can* run out of entropy, but it will pause until there is enough entropy to generate sufficient random bytes rather than just supply too few bytes. In the worst case, where your computer has just started up (and hence has very little entropy), hasn't yet given you a GUI (and hence can't gather more entropy from mouse and keyboard events), and you've just asked for a wacking great pile of random bytes, urandom can lock up for *ages* waiting for more entropy so it can meet your request. > >>> os.urandom(6) > b'\xf1\x1c\x15\x83\x14\x0e' Six bytes, each written in hex format \xNN. > And what's with the l in b'l\xbb\xae\xb7\x0ft' ? It's just a byte that happens to match the character "l" and therefore is printed as "l" instead of \x6c. > I apologize to all for not explaining what I'm trying to accomplish. > I just ran across os.urandom() and am trying to understand it. I have > a script that I use to create passwords for my various website > accounts, , but wondered if > website-permitted, but stronger passwords could be generated with the > use of os.urandom(). At this point, I think not. Extreme randomness of passwords is not actually a good thing. Generally people want to remember their passwords, in which case you want passwords which are random enough to be hard for others to guess while non-random enough for the owner to remember them. -- Steven D'Aprano From rdmoores at gmail.com Sun Aug 8 07:57:39 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sat, 7 Aug 2010 22:57:39 -0700 Subject: [Tutor] os.urandom() In-Reply-To: References: Message-ID: On Sat, Aug 7, 2010 at 17:00, Alan Gauld wrote: > > "Richard D. Moores" wrote > >> Yes, the number of bytes seems to <= 6, or is it?: >>>>> >>>>> os.urandom(6) >> >> b'\xf1\x1c\x15\x83\x14\x0e' > > ok > >>>>> os.urandom(6) >> >> b'l\xbb\xae\xb7\x0ft' > > still ok - the l and t at the ends are valid characters so Python > prints the letter >>> hex(ord('t')) '0x74' >>> hex(ord('l')) '0x6c' So if os.urandom() had been written so that it printed only hex, b'l\xbb\xae\xb7\x0ft' would have been b'\x6c\xbb\xae\xb7\x0f\x74' , right? Thanks very much for that, Alan. How were we supposed to know that all the hexes have 2 digits? How did you? Dick From augdawg09 at gmail.com Sun Aug 8 01:35:38 2010 From: augdawg09 at gmail.com (aug dawg) Date: Sat, 7 Aug 2010 19:35:38 -0400 Subject: [Tutor] Trouble with sys.path.append Message-ID: Hey all, Earlier today, I tried to add a folder to my PYTHONPATH. When I tried sys.path.app('location/of/folder'), the command successfully executed it, but then when I did sys.path to check to see if it was now in my PYTHONPATH, it was not there. Does anyone know what might be causing this? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Aug 8 10:05:19 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 8 Aug 2010 09:05:19 +0100 Subject: [Tutor] os.urandom() References: Message-ID: "Richard D. Moores" wrote > So if os.urandom() had been written so that it printed only hex, > b'l\xbb\xae\xb7\x0ft' would have been > > b'\x6c\xbb\xae\xb7\x0f\x74' , right? Yes except that its not urandomthat is printing those values. urandom returns a string of bytes. Its the Python interpreter calling the repr() function on those bytes that is deciding to print either hex or character. Try this: >>> '\x6c\xbb\xae\xb7\x0f\x74' 'l\xbb\xae\xb7\x0ft' >>> print '\x6c\xbb\xae\xb7\x0f\x74' l????t >>> In the first case its the repr() of the string that gets printed in the second its the str(). Its the conversion function that determines what gets printed not urandom() > How were we supposed to know that all the hexes have 2 digits? How > did you? Simple arithmetic... Its the hex representation of a byte. A byte is 8 bits long. A hex digit represents 4 bits (0000-1111) so you need 2 hex digits to represent 8 bits or one byte. Alan G. From alan.gauld at btinternet.com Sun Aug 8 10:10:20 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 8 Aug 2010 09:10:20 +0100 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? References: <4C5C4BB6.6040702@sbcglobal.net> <4C5D78C1.5050803@sbcglobal.net> <4C5E0BD1.1080000@sbcglobal.net> Message-ID: "Wayne Watson" wrote > I find it interesting that any Python book I've seen doesn't deal > with distributing programs in some form or another. Yes thats a good point. Most books (including mine) focus on how to write code. Very few tell you how to distrubute it! And that's not just in Python, most programming books are the same. Interesting. Alan G. From steve at pearwood.info Sun Aug 8 10:15:42 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 8 Aug 2010 18:15:42 +1000 Subject: [Tutor] os.urandom() In-Reply-To: References: Message-ID: <201008081815.42983.steve@pearwood.info> On Sun, 8 Aug 2010 03:57:39 pm Richard D. Moores wrote: > So if os.urandom() had been written so that it printed only hex, > b'l\xbb\xae\xb7\x0ft' would have been os.urandom() doesn't *print* anything. It RETURNS a byte string. What you do with it is your business. In your case, you fail to save the return result in a variable, or put it in a list, or do anything else with it, so the interactive interpreter prints it. All that the interpreter sees is bytes. They could have come from a hard-coded literal: >>> 'l\xbb\xae\xb7\x0ft' 'l\xbb\xae\xb7\x0ft' or a list: >>> L = ['l\xbb\xae\xb7\x0ft', None, None] >>> L[0] 'l\xbb\xae\xb7\x0ft' or some function call: >>> (lambda c: c + '\xbb'[:] + '\xae\xb7' + 1*'\x0ft')('l') 'l\xbb\xae\xb7\x0ft' (The above examples are from Python 2.5 rather than 3.1, where byte strings aren't flagged with a leading b.) > How were we supposed to know that all the hexes have 2 digits? How > did you? Because that's what they do. Numbers between 0 and 255 inclusive can be written in two hex digits 00..FF, just like numbers between 0 and 99 inclusive can be written in two decimal digits. -- Steven D'Aprano From steve at pearwood.info Sun Aug 8 10:21:08 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 8 Aug 2010 18:21:08 +1000 Subject: [Tutor] Trouble with sys.path.append In-Reply-To: References: Message-ID: <201008081821.09136.steve@pearwood.info> On Sun, 8 Aug 2010 09:35:38 am aug dawg wrote: > Hey all, > > Earlier today, I tried to add a folder to my PYTHONPATH. When I tried > sys.path.app('location/of/folder'), the command successfully executed > it, but then when I did sys.path to check to see if it was now in my > PYTHONPATH, it was not there. Does anyone know what might be causing > this? Modifying sys.path doesn't update PYTHONPATH. If you modify sys.path, the changes disappear when you exit and re-enter and the unmodified PYTHONPATH is read. -- Steven D'Aprano From lie.1296 at gmail.com Sun Aug 8 10:29:46 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 08 Aug 2010 18:29:46 +1000 Subject: [Tutor] Word to Sound In-Reply-To: <4C5D7F1D.3030809@gmail.com> References: <4C5D7F1D.3030809@gmail.com> <4C5D7F1D.3030809@gmail.com> Message-ID: On Sat, 07 Aug 2010 11:43:25 -0400, Chris King wrote: > How do you convert a string into a sound object. Do you mean as in text-to-speech or playing byte string that contain sound data in a certain encoding to the speaker? From lie.1296 at gmail.com Sun Aug 8 10:46:24 2010 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 8 Aug 2010 08:46:24 +0000 (UTC) Subject: [Tutor] Trouble with sys.path.append References: Message-ID: aug dawg gmail.com> writes: > > Earlier today, I tried to add a folder to my PYTHONPATH. When > I tried sys.path.app('location/of/folder'), the command successfully > executed it, but then when I did sys.path to check to see if it was > now in my PYTHONPATH, it was not there. Does anyone know what might > be causing this? > Appending to sys.path will only change the module search directory for the current *python* session. If you want to add a directory to the current *terminal* session, then export PYTHONPATH environment variable into your shell. If you want to *permanently* add a directory to the module search directory, add a .pth file to a directory that is already inside a search path (typically in /site-packages). Alternatively, modify the site.py file. See here for details: http://docs.python.org/install/#inst-search-path From rdmoores at gmail.com Sun Aug 8 12:14:25 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 8 Aug 2010 03:14:25 -0700 Subject: [Tutor] os.urandom() In-Reply-To: References: Message-ID: On Sun, Aug 8, 2010 at 01:05, Alan Gauld wrote: > > "Richard D. Moores" wrote > >> So if os.urandom() had been written so that it printed only hex, >> b'l\xbb\xae\xb7\x0ft' would have been >> >> b'\x6c\xbb\xae\xb7\x0f\x74' , right? > > Yes except that its not urandomthat is printing those values. > urandom returns a string of bytes. > Its the Python interpreter calling the repr() function on > those bytes that is deciding to print either hex or character. > Try this: > >>>> '\x6c\xbb\xae\xb7\x0f\x74' > > 'l\xbb\xae\xb7\x0ft' >>>> >>>> print '\x6c\xbb\xae\xb7\x0f\x74' > > l????t >>>> > > In the first case its the repr() of the string that gets > printed in the second its the str(). Its the conversion > function that determines what gets printed not urandom() Ah. Here are some more (from Python 2.6): >>> s = os.urandom(6);s;print s 'Y\xce\x01\xc6\xd3\xe7' Y????? >>> s = os.urandom(6);s;print s '\xd2$\xa1\x03B\xba' ?$??B? >>> s = os.urandom(6);s;print s '\xc6\x93C\xca\xc3\x18' ??C??? >>> s = os.urandom(6);s;print s '`DTzL\x98' `DTzL? >> How were we supposed to know that all the hexes have 2 digits? How did >> you? > > Simple arithmetic... > Its the hex representation of a byte. A byte is 8 bits long. > A hex digit represents 4 bits (0000-1111) so you need 2 hex digits to > represent 8 bits or one byte. Got it. Thanks again. And to Steven as well. Dick From nitinchandra1 at gmail.com Sun Aug 8 14:04:21 2010 From: nitinchandra1 at gmail.com (nitin chandra) Date: Sun, 8 Aug 2010 17:34:21 +0530 Subject: [Tutor] Reading every 5th line Message-ID: Hello Everyone, I am to make a small programme for a friend of mine where i am to start reading from 14th (string) from a file and then read every 5th row. ie. in 1st read it reads the 14 row in a File, write to an OUTPUT-1 file Next reads 19th row, write to the OUTPUT-1 file then 24th row,... so on. and the second loop does is reads the 15th line as the first line from same input file and write to OUTPUT-2 file next reads 20th line / row, write to the OUTPUT-2 file I have tried various ways but some how i am ONLY able to do i simple read from one file and write to another. There are 3024 rows / lines PER file and there are 24 such file I need to run the programme on. I really need this on an urgent basis. can some one please help me in this. Thanks in Advance Nitin From davidheiserca at gmail.com Sun Aug 8 16:20:39 2010 From: davidheiserca at gmail.com (davidheiserca at gmail.com) Date: Sun, 8 Aug 2010 07:20:39 -0700 Subject: [Tutor] Reading every 5th line References: Message-ID: <8B1F80FAA2594B60B1037A5EEEDDBBDD@dheiser> ----- Original Message ----- From: "nitin chandra" To: Sent: Sunday, August 08, 2010 5:04 AM Subject: [Tutor] Reading every 5th line > Hello Everyone, > > I am to make a small programme for a friend of mine > where i am to start reading from 14th (string) from a file and then > read every 5th row. > > ie. > > in 1st read it reads the 14 row in a File, write to an OUTPUT-1 file > Next reads 19th row, write to the OUTPUT-1 file > then 24th row,... so on. > > and the second loop does is > > reads the 15th line as the first line from same input file and write > to OUTPUT-2 file > next reads 20th line / row, write to the OUTPUT-2 file > > > I have tried various ways but some how i am ONLY able to do i simple > read from one file and write to another. > > There are 3024 rows / lines PER file and there are 24 such file I need > to run the programme on. > > I really need this on an urgent basis. can some one please help me in > this. > > Thanks in Advance > > Nitin > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Try using "range(start, end, step)". If this is for a class exercise, it would be unfair to say more. If it's not for an assignment, I can show you more. Dave From davidheiserca at gmail.com Sun Aug 8 16:49:41 2010 From: davidheiserca at gmail.com (davidheiserca at gmail.com) Date: Sun, 8 Aug 2010 07:49:41 -0700 Subject: [Tutor] Reading every 5th line References: <8B1F80FAA2594B60B1037A5EEEDDBBDD@dheiser> Message-ID: <2DBCB85232F54B22A53515F62D607BE2@dheiser> ----- Original Message ----- From: "nitin chandra" To: Sent: Sunday, August 08, 2010 7:29 AM Subject: Re: [Tutor] Reading every 5th line > Thank you all. > > @Dave - Thank you for the tip. No this is not a class exercise, that > is assured. > > Will let know how much progress i made. > > Truly, I am still foggy, as to how to include it in code. > > Thanks > > Nitin > >> >> >> Try using "range(start, end, step)". >> >> If this is for a class exercise, it would be unfair to say more. If it's >> not >> for an assignment, I can show you more. >> >> Dave >> >> This may help you get started. FileNames = ["FileName01", "FileName02", ..., "FileName24"] for File in FileNames: List = open(File, 'r').readlines() for Start in [[14, "%s-1" % File], [15,"%s-2" % File]]: OutList = [] for Line in range(Start[0]-1, 3024, 5): OutList.append(List[Line]) open(("%s.txt" % Start[1]), 'w').writelines(OutList) P.S. My code writing style isn't very conventional. From bgailer at gmail.com Sun Aug 8 17:11:33 2010 From: bgailer at gmail.com (bob gailer) Date: Sun, 08 Aug 2010 11:11:33 -0400 Subject: [Tutor] os.urandom() In-Reply-To: References: Message-ID: <4C5EC925.5050200@gmail.com> On 8/8/2010 1:57 AM, Richard D. Moores wrote: > On Sat, Aug 7, 2010 at 17:00, Alan Gauld wrote: > >> "Richard D. Moores" wrote >> >> >>> Yes, the number of bytes seems to<= 6, or is it?: >>> >>>>>> os.urandom(6) >>>>>> >>> b'\xf1\x1c\x15\x83\x14\x0e' >>> >> ok >> >> >>>>>> os.urandom(6) >>>>>> >>> b'l\xbb\xae\xb7\x0ft' >>> >> still ok - the l and t at the ends are valid characters so Python >> prints the letter >> > >>>> hex(ord('t')) >>>> > '0x74' > >>>> hex(ord('l')) >>>> > '0x6c' > > So if os.urandom() had been written so that it printed only hex, > b'l\xbb\xae\xb7\x0ft' would have been > > b'\x6c\xbb\xae\xb7\x0f\x74' , right? > > Thanks very much for that, Alan. > > How were we supposed to know that all the hexes have 2 digits? In version 2.6.5 Language Reference 2.4.1 - String literals: \xhh Character with hex value hh -- Bob Gailer 919-636-4239 Chapel Hill NC From steve at pearwood.info Sun Aug 8 17:18:41 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 9 Aug 2010 01:18:41 +1000 Subject: [Tutor] Reading every 5th line In-Reply-To: References: Message-ID: <201008090118.42077.steve@pearwood.info> On Sun, 8 Aug 2010 10:04:21 pm nitin chandra wrote: > Hello Everyone, > > I am to make a small programme for a friend of mine > where i am to start reading from 14th (string) from a file and then > read every 5th row. There are many variations, here's one: Write a loop that executes 14 times. Inside that loop, read one line from the input file, and write it to the output file. Now write a second loop that executes forever. (Don't worry, you'll break out of the loop at some point.) Inside the loop, read one line from the input file, and write it to the output file. Then read four more lines, and throw them away. If you read a line, and it's empty, then you've reached End Of File (EOF) and you can break out of the loop. -- Steven D'Aprano From bgailer at gmail.com Sun Aug 8 17:19:42 2010 From: bgailer at gmail.com (bob gailer) Date: Sun, 08 Aug 2010 11:19:42 -0400 Subject: [Tutor] Reading every 5th line In-Reply-To: References: Message-ID: <4C5ECB0E.4080702@gmail.com> On 8/8/2010 8:04 AM, nitin chandra wrote: > Hello Everyone, > > I am to make a small programme for a friend of mine > where i am to start reading from 14th (string) from a file and then > read every 5th row. > > ie. > > in 1st read it reads the 14 row in a File, write to an OUTPUT-1 file > Next reads 19th row, write to the OUTPUT-1 file > then 24th row,... so on. > > and the second loop does is > > reads the 15th line as the first line from same input file and write > to OUTPUT-2 file > next reads 20th line / row, write to the OUTPUT-2 file > > > I have tried various ways but some how i am ONLY able to do i simple > read from one file and write to another. > Please show us the attempts you have made. > There are 3024 rows / lines PER file That is irrelevant. > and there are 24 such file I need to run the programme on. > Several unknowns here. Do you process one file at a time? Where does the output from the other files go? -- Bob Gailer 919-636-4239 Chapel Hill NC From asmosis.asterix at gmail.com Sun Aug 8 19:04:19 2010 From: asmosis.asterix at gmail.com (Daniel) Date: Sun, 8 Aug 2010 20:04:19 +0300 Subject: [Tutor] Questions regarding strings Message-ID: Hello everyone! I would like to ask you two questions regarding strings which I do not know. Excuse me in advance if the questions may seem a bit dumb. I'm a beginner. So let's get back to the point, this is my string: msg= 'Hello world' If I do, msg[:3] I get the following output, 'Hel' If I do, msg[6:] I get the following output, 'World' Ok, so I understand why this is happening. What I do not understand is why I get the following output in this cases. 1) msg[:-1] which has the output 'Hello Worl' 2) msg[0:6:2] 'Hlo' 3) msg[::-1] 'dlroW olleH' Can someone please explain this to me? Thank you so much and I wish everyone a great day! -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Sun Aug 8 19:13:02 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sun, 8 Aug 2010 12:13:02 -0500 Subject: [Tutor] Questions regarding strings In-Reply-To: References: Message-ID: On Sun, Aug 8, 2010 at 12:04 PM, Daniel wrote: > Hello everyone! I would like to ask you two questions regarding strings > which I do not know. Excuse me in advance if the questions may seem a bit > dumb. I'm a beginner. So let's get back to the point, this is my string: > > msg= 'Hello world' > If I do, msg[:3] I get the following output, 'Hel' > If I do, msg[6:] I get the following output, 'World' > Ok, so I understand why this is happening. What I do not understand is why I > get the following output in this cases. > > > 1) msg[:-1] which has the output 'Hello Worl' negative indexes start from the end of the string. So msg[-1] == 'd', and the slice there means "start at the first character, and go up to the last. > 2) msg[0:6:2]? 'Hlo' This means start at the first, up to the sixth, making steps of 2. Steps of two means every other letter is skipped, of course. > 3) msg[::-1] 'dlroW olleH' This slice catches the whole string, but makes steps of -1, which essentially means you'll go through the strings backwards. Hugo From eike.welk at gmx.net Sun Aug 8 20:41:20 2010 From: eike.welk at gmx.net (Eike Welk) Date: Sun, 8 Aug 2010 20:41:20 +0200 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? In-Reply-To: References: <4C5C4BB6.6040702@sbcglobal.net> <4C5E0BD1.1080000@sbcglobal.net> Message-ID: <201008082041.20446.eike.welk@gmx.net> Hello Alan! On Sunday August 8 2010 10:10:20 Alan Gauld wrote: > Yes thats a good point. Most books (including mine) focus on how to > write code. Very few tell you how to distrubute it! And that's not > just > in Python, most programming books are the same. > > Interesting. > > Alan G. Yes, I want to endorse that! Distributing your software is IMHO a worthy subject for any Python website or book. Especially because there is this idea, that all important components for software development are included in Python. With Distutils, EasyInstall (*.egg), and Python Package Index there really exist an integrated build system with installer, a package manager, and a networked software repository. Additionally with Virtualenv or Buildout one can build encapsulated environments for testing or deployment, without fear for conflicting library versions. Someone however needs to find out how these components fit together, and then write a nice introduction on the subject. Eike. Links to the mentioned projects for reference: Distutils: http://docs.python.org/distutils/ EasyInstall: http://pypi.python.org/pypi/setuptools http://pypi.python.org/pypi/distribute Virtualenv: http://pypi.python.org/pypi/virtualenv Buildout: http://www.buildout.org/ Python Package Index: http://pypi.python.org/pypi From smokefloat at gmail.com Sun Aug 8 20:44:37 2010 From: smokefloat at gmail.com (David Hutto) Date: Sun, 8 Aug 2010 14:44:37 -0400 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? In-Reply-To: <201008082041.20446.eike.welk@gmx.net> References: <4C5C4BB6.6040702@sbcglobal.net> <4C5E0BD1.1080000@sbcglobal.net> <201008082041.20446.eike.welk@gmx.net> Message-ID: On Sun, Aug 8, 2010 at 2:41 PM, Eike Welk wrote: > Hello Alan! > > On Sunday August 8 2010 10:10:20 Alan Gauld wrote: >> Yes thats a good point. Most books (including mine) focus on how to >> write code. Very few tell you how to distrubute it! And that's not >> just >> in Python, most programming books are the same. >> >> Interesting. >> >> Alan G. > > Yes, I want to endorse that! > > Distributing your software is IMHO a worthy subject for any Python website or > book. Especially because there is this idea, that all important components for > software development are included in Python. Four words... Software is python's propaganda. > > With Distutils, EasyInstall (*.egg), and Python Package Index there really > exist an integrated build system with installer, a package manager, and a > networked software repository. > > Additionally with Virtualenv or Buildout one can build encapsulated > environments for testing or deployment, without fear for conflicting library > versions. > > Someone however needs to find out how these components fit together, and then > write a nice introduction on the subject. > > > Eike. > > > Links to the mentioned projects for reference: > > Distutils: ? http://docs.python.org/distutils/ > EasyInstall: http://pypi.python.org/pypi/setuptools > ? ? ? ? ? ? http://pypi.python.org/pypi/distribute > Virtualenv: ?http://pypi.python.org/pypi/virtualenv > Buildout: ? ?http://www.buildout.org/ > Python Package Index: http://pypi.python.org/pypi > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From shurui.liu at hotmail.com Sun Aug 8 21:01:25 2010 From: shurui.liu at hotmail.com (Shurui Liu) Date: Sun, 8 Aug 2010 15:01:25 -0400 Subject: [Tutor] word_probles.py In-Reply-To: References: , , Message-ID: Okay. I am using WinXP, Python 3.1 on my workstation. And this is the Python version information I got from putty.exe: Python 2.5.4 (r254:67916, Apr 13 2009, 18:09:11) [GCC 4.2.1 20070719 [FreeBSD]] on freebsd7 Thanks! ############################## Never had, never will. > From: hugo.yoshi at gmail.com > Date: Sat, 7 Aug 2010 20:09:04 -0500 > Subject: Re: [Tutor] word_probles.py > To: shurui.liu at hotmail.com > CC: waynejwerner at gmail.com; tutor at python.org > > On Sat, Aug 7, 2010 at 7:12 PM, Shurui Liu wrote: > > There is no tracebacks. > > > > I can run this program on putty.exe. That means the code is correct, but I > > cannot run it on IDLE or PyScripter.exe. Both of these two platforms only > > told me "Syntax Error" without tracebacks or something. > > > > We'll need to know python versions. The machine you're running it on > through putty might have 2.x while your local machine has 3.x, that > would cause a problem like this. > > Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Sun Aug 8 21:43:00 2010 From: davea at ieee.org (Dave Angel) Date: Sun, 08 Aug 2010 15:43:00 -0400 Subject: [Tutor] Reading every 5th line In-Reply-To: References: Message-ID: <4C5F08C4.5060503@ieee.org> nitin chandra wrote: > Hello Everyone, > > I am to make a small programme for a friend of mine > where i am to start reading from 14th (string) from a file and then > read every 5th row. > > ie. > > in 1st read it reads the 14 row in a File, write to an OUTPUT-1 file > Next reads 19th row, write to the OUTPUT-1 file > then 24th row,... so on. > > and the second loop does is > > reads the 15th line as the first line from same input file and write > to OUTPUT-2 file > next reads 20th line / row, write to the OUTPUT-2 file > > > I have tried various ways but some how i am ONLY able to do i simple > read from one file and write to another. > > There are 3024 rows / lines PER file and there are 24 such file I need > to run the programme on. > > I really need this on an urgent basis. can some one please help me in this. > > Thanks in Advance > > Nitin > > Write a function that takes a pair of filenames and the starting line # to begin reading. Then call it in a loop from 14 through 19. And call that loop for each input file. The loop inside the function body could be as simple as (untested): for line in itertools.islice(infile, startnum, 10**6, 5): outfile.write(line) DaveA From davea at ieee.org Sun Aug 8 22:00:47 2010 From: davea at ieee.org (Dave Angel) Date: Sun, 08 Aug 2010 16:00:47 -0400 Subject: [Tutor] word_probles.py In-Reply-To: References: , , Message-ID: <4C5F0CEF.7090008@ieee.org> Shurui Liu wrote: > Okay. I am using WinXP, Python 3.1 on my workstation. > And this is the Python version information I got from putty.exe: > Python 2.5.4 (r254:67916, Apr 13 2009, 18:09:11) > [GCC 4.2.1 20070719 [FreeBSD]] on freebsd7 > > You cannot use the same python source on 2.5 as you do in 3.1, regardless of OS platform. For just about any non-trivial program, the differences will get you compile errors on one or the other. If you're targeting 2.5 on the remote machine, you'd better be developing/testing with 2.5 on your own. You still might have OS differences, but they're more likely to be manageable. For an example of a gross difference, look at print. In 2.5, print is a statement, and takes particular syntax following the word print. In 3.x, print() is a function, and must have a standard argument list. This means that some options that you might have used in 2.5 will just be syntax errors. And conversely, it means the print function may be called inside an expression, which would be totally illegal on 2.5. It is possible to build a string ahead of time, and enclose a single string in parentheses (effectively ignored on 2.5), and get something that works on both platforms. Alternatively, there's the 2to3 converter, but that's a nuisance at best. Useful for one-time conversion, and for those situations that absolutely must run on both platforms, but otherwise a pain to keep both versions of the source up to date. And you'd still have to test with 2.5 before deploying to an unsuspecting user. DaveA From wprins at gmail.com Mon Aug 9 00:50:00 2010 From: wprins at gmail.com (Walter Prins) Date: Sun, 08 Aug 2010 23:50:00 +0100 Subject: [Tutor] word_probles.py In-Reply-To: References: , , Message-ID: <4C5F3498.40604@gmail.com> Hi, On 08/08/10 20:01, Shurui Liu wrote: > Okay. I am using WinXP, Python 3.1 on my workstation. > And this is the Python version information I got from putty.exe: > Python 2.5.4 (r254:67916, Apr 13 2009, 18:09:11) > [GCC 4.2.1 20070719 [FreeBSD]] on freebsd7 To add a small comment to what Dave's already said, please refer to the official documentation here: http://docs.python.org/release/3.0.1/whatsnew/3.0.html The net result for you is, I think, that you should be using Python 2.x on your Windows XP box, and not Python 3.x. Regards, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Aug 9 01:57:55 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 9 Aug 2010 09:57:55 +1000 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? In-Reply-To: References: <4C5C4BB6.6040702@sbcglobal.net> <201008082041.20446.eike.welk@gmx.net> Message-ID: <201008090957.55496.steve@pearwood.info> On Mon, 9 Aug 2010 04:44:37 am David Hutto wrote: > Four words... Software is python's propaganda. Four more words: please trim unnecessary quoting. -- Steven D'Aprano From ranjithtenz at gmail.com Mon Aug 9 04:16:11 2010 From: ranjithtenz at gmail.com (Ranjith Kumar) Date: Mon, 9 Aug 2010 07:46:11 +0530 Subject: [Tutor] Need a mentor Message-ID: Hi all, I`m doing a python based project, I need a mentor who can guide me and help me to complete the project. the idea is fully based upon application programming. What I want is just suggest me how to implement so that I write the code and send it back to you. And there you can check the codes and find the better solution or giving me some other ideas so that we can optimize the code and bring a better solution. I`m glad to work on python if anyone interested in this please kindly let me know it. Awaiting for your reply. -- Cheers Ranjith, http://ranjith10z.wordpress.com http://ranjithtenz.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdmoores at gmail.com Mon Aug 9 06:14:32 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 8 Aug 2010 21:14:32 -0700 Subject: [Tutor] os.urandom() In-Reply-To: <4C5EC925.5050200@gmail.com> References: <4C5EC925.5050200@gmail.com> Message-ID: On Sun, Aug 8, 2010 at 08:11, bob gailer wrote: > On 8/8/2010 1:57 AM, Richard D. Moores wrote: >> How were we supposed to know that all the hexes have 2 digits? > > In version 2.6.5 Language Reference 2.4.1 - String literals: > \xhh Character with hex value hh But >>> os.urandom(6) b'\x13\xf1\x138a\xcc' In my Active Python 3.1 docs, Language Ref 2.4.1. String and Bytes literals, I have The same as what you quoted, plus a couple of footnotes: \xhh Character with hex value hh (2,3) That footnote 2, "Unlike in Standard C, at most two hex digits are accepted.", seems necessary; otherwise that \x138a could be seen by my former, byte-ignorant self as a \xhhhh, and puzzled about why I got only 4 bytes, not 6. :) But I never would have thought to have looked in the docs where you did. Dick From rdmoores at gmail.com Mon Aug 9 06:25:32 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 8 Aug 2010 21:25:32 -0700 Subject: [Tutor] Idea for a 'Weekly Python Tips' mailing list In-Reply-To: References: Message-ID: On Fri, Aug 6, 2010 at 10:51, Lie Ryan wrote: > In the main python list there is Python Weekly URL that summarizes the > week's most interesting posts in c.l.py The latest of these I have received is dated June 22. Summer vacation? Or discontinued? Dick Moores From rdmoores at gmail.com Mon Aug 9 06:47:39 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Sun, 8 Aug 2010 21:47:39 -0700 Subject: [Tutor] Idea for a 'Weekly Python Tips' mailing list In-Reply-To: References: Message-ID: On Sun, Aug 8, 2010 at 21:25, Richard D. Moores wrote: > On Fri, Aug 6, 2010 at 10:51, Lie Ryan wrote: > >> In the main python list there is Python Weekly URL that summarizes the >> week's most interesting posts in c.l.py > > The latest of these I have received is dated June 22. Summer vacation? > Or discontinued? A Gmane search shows that there are frequent gaps. Dick Moores From nitinchandra1 at gmail.com Mon Aug 9 07:46:36 2010 From: nitinchandra1 at gmail.com (nitin chandra) Date: Mon, 9 Aug 2010 11:16:36 +0530 Subject: [Tutor] Reading every 5th line In-Reply-To: <2DBCB85232F54B22A53515F62D607BE2@dheiser> References: <8B1F80FAA2594B60B1037A5EEEDDBBDD@dheiser> <2DBCB85232F54B22A53515F62D607BE2@dheiser> Message-ID: Hello Dave, Thank you very much. This solution worked out very well. And I liked your style of coding .... ' In less DO more '. Thank You once again. Nitin PS :- I tried to use a file pointer with raw_input, but that did not work. > > This may help you get started. > > FileNames = ["FileName01", "FileName02", ..., "FileName24"] > for File in FileNames: > ? List = open(File, 'r').readlines() > ? for Start in [[14, "%s-1" % File], [15,"%s-2" % File]]: > ? ? ? OutList = [] > ? ? ? for Line in range(Start[0]-1, 3024, 5): > ? ? ? ? ? OutList.append(List[Line]) > ? ? ? open(("%s.txt" % Start[1]), 'w').writelines(OutList) > > P.S. My code writing style isn't very conventional. > > From ranjithtenz at gmail.com Mon Aug 9 08:32:48 2010 From: ranjithtenz at gmail.com (Ranjith Kumar) Date: Mon, 9 Aug 2010 12:02:48 +0530 Subject: [Tutor] Fwd: Need mentor In-Reply-To: References: Message-ID: Hi all, I have described the theme of my project here, When the script is runned a configuring window has to be displayed where the user has to configure for there desired Web Browser, Audio Player, Video Player, Text Editor (Each Specified in separate SS Tab). Here the script should retrieve all installed Web Browser, Audio Player, Video Player and Text Editor and categorized and displayed in their corresponding tab`s. Here the user has to choose and set their preferred Web Browser, Video Player, Audio Player, Text Editor and update the configure file. note 1: configuring window should run automatically only first if the user wants to reconfigure the file again they should run configuring module alone note 2: This script is to start it on every login and stay running on background until i shut download the machine. For an example, this is complete real time behavior of the script. Let us consider I`m the user I downloaded the script and runned it, It should check for a configuring file if there is no configure file is created means it should automatically create a new configure file and displays a configuring window in that window I will be offered by whatever the web browsers, audio player, video player, text editor installed on my machine will has to be shown to me in their corresponding tab`s I have to set my desired web browser if I choose chrome has my prefered web browser and whenever I press the key "w" on desktop screen the chrome browser should be opened, I have to set my desired Audio player if I choose exaile has my preferred audio player and whenever I press the key "a" on desktop screen the Exaile audio player should be opened,I have to set my desired video player if I choose vlc has my prefered video player and whenever I press the key "v" on desktop screen the vlc player should be opened, I have to set my desired text editor if I choose gedit has my prefered text editor and whenever I press the key "t" on desktop screen the Gedit text editor should be opened, this just like creating hotkeys and all these configured details should be updated when I click on apply and exits the configuring windows and runs the script at the desktop background while i`m in desktop when i just hit "w" chrome browser should opened -- Cheers Ranjith, http://ranjith10z.wordpress.com http://ranjithtenz.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Aug 9 08:53:29 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 9 Aug 2010 16:53:29 +1000 Subject: [Tutor] Need a mentor In-Reply-To: References: Message-ID: <201008091653.29281.steve@pearwood.info> On Mon, 9 Aug 2010 12:16:11 pm Ranjith Kumar wrote: > Hi all, > I`m doing a python based project, I need a mentor who can guide > me and help me to complete the project. Are you offering to pay for professional help for a commercial project, looking for volunteers to work on an open-source project with you, or just looking for a kind and generous soul who is happy to donate many, many hours of work teaching you application development in Python? -- Steven D'Aprano From smokefloat at gmail.com Mon Aug 9 09:43:35 2010 From: smokefloat at gmail.com (David Hutto) Date: Mon, 9 Aug 2010 03:43:35 -0400 Subject: [Tutor] Distributing Python Code for Commercial Porpoises? In-Reply-To: <201008090957.55496.steve@pearwood.info> References: <4C5C4BB6.6040702@sbcglobal.net> <201008082041.20446.eike.welk@gmx.net> <201008090957.55496.steve@pearwood.info> Message-ID: On Sun, Aug 8, 2010 at 7:57 PM, Steven D'Aprano wrote: > On Mon, 9 Aug 2010 04:44:37 am David Hutto wrote: > >> Four words... Software is python's propaganda. > > Four more words: please trim unnecessary quoting. No problem buddy pal. > > > -- > Steven D'Aprano > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From ranjithtenz at gmail.com Mon Aug 9 11:21:03 2010 From: ranjithtenz at gmail.com (Ranjith Kumar) Date: Mon, 9 Aug 2010 14:51:03 +0530 Subject: [Tutor] Need a mentor In-Reply-To: <201008091653.29281.steve@pearwood.info> References: <201008091653.29281.steve@pearwood.info> Message-ID: On Mon, Aug 9, 2010 at 12:23 PM, Steven D'Aprano wrote: > On Mon, 9 Aug 2010 12:16:11 pm Ranjith Kumar wrote: > > Hi all, > > I`m doing a python based project, I need a mentor who can guide > > me and help me to complete the project. > Sorry Mr. Steven I think u caught it wrong I`m not asking to trainee me I almost completed this script Are you offering to pay for professional help for a commercial project, > First thing is this is not a commercial Project, I`m just trying to take my writing of python scripts to next level. > looking for volunteers to work on an open-source project with you, After I complete this project I will send the code so any volunteers can optimize the code so that we can provide better solution for open source world and I will definitely upload this project under GPL Licence in code.google.com and sourceforgue.net. > or just looking for a kind and generous soul who is happy to donate many, > many hours of work teaching you application development in Python? > I think here comes the little bit misunderstanding I don`t want to waste your several hours the thing I post is just a core of my project a small part like. These are the four things, I need to know is this 1) Configuring window should runs automatically only first time if the user wants to reconfigure the file again they should run configuring module separately. 2) This script is to start it automatically on every login and stay running on background until i shut download the machine. 3) I need a best alternative way for switch case statement 4) Lastly I need to know is how to print the list of web browsers installed on a machine. Thats it, Thank you and sorry for trouble I gave you Mr.Steven -- Cheers Ranjith, http://ranjith10z.wordpress.com http://ranjithtenz.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Mon Aug 9 11:23:56 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 09 Aug 2010 05:23:56 -0400 Subject: [Tutor] os.urandom() In-Reply-To: References: <4C5EC925.5050200@gmail.com> Message-ID: <4C5FC92C.5010907@ieee.org> Richard D. Moores wrote: > On Sun, Aug 8, 2010 at 08:11, bob gailer wrote: > >> On 8/8/2010 1:57 AM, Richard D. Moores wrote: >> > > >>> How were we supposed to know that all the hexes have 2 digits? >>> >> In version 2.6.5 Language Reference 2.4.1 - String literals: >> \xhh Character with hex value hh >> > > But > >>>> os.urandom(6) >>>> > b'\x13\xf1\x138a\xcc' > > In my Active Python 3.1 docs, Language Ref 2.4.1. String and Bytes > literals, I have > > The same as what you quoted, plus a couple of footnotes: > \xhh Character with hex value hh (2,3) > > That footnote 2, "Unlike in Standard C, at most two hex digits are > accepted.", seems necessary; otherwise that \x138a could be seen by my > former, byte-ignorant self as a \xhhhh, and puzzled about why I got > only 4 bytes, not 6. :) > > But I never would have thought to have looked in the docs where you did. > > Dick > > Big difference between 2.x and 3.x. In 3.x, strings are Unicode, and may be stored either in 16bit or 32bit form (Windows usually compiled using the former, and Linux the latter). Presumably in 3.x, urandom returns a byte string (see the b'xxxx' form), which is 8 bits each, same as 2.x strings. So you'd expect only two hex digits for each character. DaveA From steve at pearwood.info Mon Aug 9 11:58:38 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 9 Aug 2010 19:58:38 +1000 Subject: [Tutor] Need a mentor In-Reply-To: References: <201008091653.29281.steve@pearwood.info> Message-ID: <201008091958.39937.steve@pearwood.info> On Mon, 9 Aug 2010 07:21:03 pm Ranjith Kumar wrote: > On Mon, Aug 9, 2010 at 12:23 PM, Steven D'Aprano wrote: > > On Mon, 9 Aug 2010 12:16:11 pm Ranjith Kumar wrote: > > > Hi all, > > > I`m doing a python based project, I need a mentor who can > > > guide me and help me to complete the project. > > Sorry Mr. Steven I think u caught it wrong I`m not asking to trainee > me I almost completed this script It's not clear exactly what you want. Lists like this work best when you ask *specific* questions like "how do I set a cookies from Python?" or "what's the difference between a list and a tuple?", not vague requests for a mentor. After reading both your posts, I'm still not entirely sure I understand what you want, but I'll try... [...] > After I complete this project I will send the code so any volunteers > can optimize the code so that we can provide better solution for open > source world and I will definitely upload this project under GPL > Licence in code.google.com and sourceforgue.net. It's not compulsory :) I don't understand why you think you need to optimize the code. Is it too slow? [...] > These are the four things, I need to know is this > 1) Configuring window should runs automatically only first > time if the user wants to reconfigure the file again they should run > configuring module separately. That's a statement, not a question. What do you want to know? "Is this a good idea?" Depends on the application. Most applications give the user a Preferences or Settings menu so they can reconfigure the app at any time. But since I don't really know what your application does, I'm not sure if this is appropriate. "How do I do it?" The usual way is to have the application look for a configuration file in some place. If it is missing, then create a new one. If it is present, then read the file and use it as the config. > 2) This script is to start it automatically on every login and stay > running on background until i shut download the machine. Again, that's not a question, it's a statement. What do you want to know? "Is this a good idea?" Who knows? What does your program do? "How do I do it?" That depends. What operating system is your application supposed to run under? > 3) I need a best alternative way for switch case statement There is no "best alternative", it depends on the nature of the case statement you are replacing. If it is only a few cases, or if each test is a different sort of test: # pseudo-code case: x == 1: spam(arg) x > 2: ham(arg) y/x < 0: cheese(arg) otherwise: pickles(arg) the best alternative is a series of if...elif tests. If you have a series of simple equality comparisons, and you can write the case clause as a single function call: # pseudo-code case of x: 1: spam(arg) 2: ham(arg) 3: cheese(arg) otherwise: pickles(arg) it is probably better re-writing it as a dispatch table: # python table = {1: spam, 2: ham, 3: cheese} func = table.get(x, pickles) func(arg) There are probably other alternatives that will be better depending on exactly what you are trying to do. > 4) Lastly I need to know is how to print the list of web browsers > installed on a machine. Printing it is easy: you print it the same way you print anything else: call print to output to the terminal, or generate a print job to send to a physical printer. The hard part is finding out what web browsers are installed on a machine. That's a hard problem, because there's no canonical list of "web browsers" for a computer. Take my machine, for example. I have: firefox 2.x firefox 3.x epiphany galeon konquorer links lynx and they're just the ones I know of. The problems are: * It is hard to tell what is a web browser and what isn't. If Adobe Acrobat lets you embed clickable links to http:// URLs in PDF files, does that make Acrobat a web browser? I suppose it does, but some people will say not. If Outlook displays web pages, is it a web browser? You can click on a link in a Word document, and Word will open that web page for you -- is it a browser? * Even if you decide exactly what is a web browser, there's no list of them anywhere. To find out which they are, you would need to start with a list of all the applications on the computer (what's an application? what if there are thousands of them?), and then somehow inspect each one and try to recognise whether or not it is a web browser or not. How? You probably can get the name of the *registered* web browser, but the way you do that will depend on the operating system and desktop environment. E.g. under Windows there is probably a registry setting that specifies which application to use as the default web browser. Or you can keep a list of possibilities, and search for them, ignoring anything else. Or you can ask the user. Or you can look at Python's webbrowser module and see what it does. So the answer will depend on why you want to print this list of web browsers, how accurate you want to be, and what system you are running under. -- Steven D'Aprano From davea at ieee.org Mon Aug 9 12:02:27 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 09 Aug 2010 06:02:27 -0400 Subject: [Tutor] Reading every 5th line In-Reply-To: References: <8B1F80FAA2594B60B1037A5EEEDDBBDD@dheiser> <2DBCB85232F54B22A53515F62D607BE2@dheiser> Message-ID: <4C5FD233.8010101@ieee.org> nitin chandra wrote: > >> This may help you get started. >> >> FileNames ="FileName01", "FileName02", ..., "FileName24"] >> for File in FileNames: >> List =pen(File, 'r').readlines() >> for Start in [[14, "%s-1" % File], [15,"%s-2" % File]]: >> OutList =] >> for Line in range(Start[0]-1, 3024, 5): >> OutList.append(List[Line]) >> open(("%s.txt" % Start[1]), 'w').writelines(OutList) >> >> P.S. My code writing style isn't very conventional. >> >> >> Note that three of those lines may be replaced with a slice (untested) OutList =] for Line in range(Start[0]-1, 3024, 5): OutList.append(List[Line]) OutList = List[Start[0]-1: 3024: 5] From anand.shashwat at gmail.com Mon Aug 9 12:08:24 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Mon, 9 Aug 2010 15:38:24 +0530 Subject: [Tutor] Need a mentor In-Reply-To: <201008091958.39937.steve@pearwood.info> References: <201008091653.29281.steve@pearwood.info> <201008091958.39937.steve@pearwood.info> Message-ID: On Mon, Aug 9, 2010 at 3:28 PM, Steven D'Aprano wrote: > On Mon, 9 Aug 2010 07:21:03 pm Ranjith Kumar wrote: > > On Mon, Aug 9, 2010 at 12:23 PM, Steven D'Aprano > wrote: > > > On Mon, 9 Aug 2010 12:16:11 pm Ranjith Kumar wrote: > > > > Hi all, > > > > I`m doing a python based project, I need a mentor who can > > > > guide me and help me to complete the project. > > > > Sorry Mr. Steven I think u caught it wrong I`m not asking to trainee > > me I almost completed this script > You need a mentor to help you :-/ . What is the problem is you work upon your script and ask doubts here? You are confusing university projects with real-life projects I think. In universities you choose a mentor and he help you out. Here you work on your project, ask doubts and community help you out. Isn't it good to have whole of the community helping you rather than one single person. > > It's not clear exactly what you want. Lists like this work best when you > ask *specific* questions like "how do I set a cookies from Python?" > or "what's the difference between a list and a tuple?", not vague > requests for a mentor. > > After reading both your posts, I'm still not entirely sure I understand > what you want, but I'll try... > > [...] > > After I complete this project I will send the code so any volunteers > > can optimize the code so that we can provide better solution for open > > source world and I will definitely upload this project under GPL > > Licence in code.google.com and sourceforgue.net. > > It's not compulsory :) > > I don't understand why you think you need to optimize the code. Is it > too slow? > I think he means that after his project is over, he will open-source the code so that other's may improve upon it. > > > > [...] > > These are the four things, I need to know is this > > 1) Configuring window should runs automatically only first > > time if the user wants to reconfigure the file again they should run > > configuring module separately. > > That's a statement, not a question. What do you want to know? > > "Is this a good idea?" > > Depends on the application. Most applications give the user a > Preferences or Settings menu so they can reconfigure the app at any > time. But since I don't really know what your application does, I'm not > sure if this is appropriate. > > "How do I do it?" > > The usual way is to have the application look for a configuration file > in some place. If it is missing, then create a new one. If it is > present, then read the file and use it as the config. > > > > 2) This script is to start it automatically on every login and stay > > running on background until i shut download the machine. > > Again, that's not a question, it's a statement. What do you want to > know? > > "Is this a good idea?" > > Who knows? What does your program do? > > "How do I do it?" > > That depends. What operating system is your application supposed to run > under? > > > > > > 3) I need a best alternative way for switch case statement > > There is no "best alternative", it depends on the nature of the case > statement you are replacing. > > If it is only a few cases, or if each test is a different sort of test: > > # pseudo-code > case: > x == 1: > spam(arg) > x > 2: > ham(arg) > y/x < 0: > cheese(arg) > otherwise: > pickles(arg) > > > the best alternative is a series of if...elif tests. > > If you have a series of simple equality comparisons, and you can write > the case clause as a single function call: > > > # pseudo-code > case of x: > 1: > spam(arg) > 2: > ham(arg) > 3: > cheese(arg) > otherwise: > pickles(arg) > > > it is probably better re-writing it as a dispatch table: > > # python > table = {1: spam, 2: ham, 3: cheese} > func = table.get(x, pickles) > func(arg) > > > There are probably other alternatives that will be better depending on > exactly what you are trying to do. > > > > > 4) Lastly I need to know is how to print the list of web browsers > > installed on a machine. > > Printing it is easy: you print it the same way you print anything else: > call print to output to the terminal, or generate a print job to send > to a physical printer. > > The hard part is finding out what web browsers are installed on a > machine. That's a hard problem, because there's no canonical list > of "web browsers" for a computer. > > Take my machine, for example. I have: > > firefox 2.x > firefox 3.x > epiphany > galeon > konquorer > links > lynx > > and they're just the ones I know of. The problems are: > > * It is hard to tell what is a web browser and what isn't. If Adobe > Acrobat lets you embed clickable links to http:// URLs in PDF files, > does that make Acrobat a web browser? I suppose it does, but some > people will say not. If Outlook displays web pages, is it a web > browser? You can click on a link in a Word document, and Word will open > that web page for you -- is it a browser? > > * Even if you decide exactly what is a web browser, there's no list of > them anywhere. To find out which they are, you would need to start with > a list of all the applications on the computer (what's an application? > what if there are thousands of them?), and then somehow inspect each > one and try to recognise whether or not it is a web browser or not. > How? > > You probably can get the name of the *registered* web browser, but the > way you do that will depend on the operating system and desktop > environment. E.g. under Windows there is probably a registry setting > that specifies which application to use as the default web browser. Or > you can keep a list of possibilities, and search for them, ignoring > anything else. Or you can ask the user. Or you can look at Python's > webbrowser module and see what it does. > > > So the answer will depend on why you want to print this list of web > browsers, how accurate you want to be, and what system you are running > under. > > > > > -- > Steven D'Aprano > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- ~l0nwlf -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Aug 9 12:39:23 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 9 Aug 2010 20:39:23 +1000 Subject: [Tutor] os.urandom() In-Reply-To: <4C5FC92C.5010907@ieee.org> References: <4C5FC92C.5010907@ieee.org> Message-ID: <201008092039.25030.steve@pearwood.info> On Mon, 9 Aug 2010 07:23:56 pm Dave Angel wrote: > Big difference between 2.x and 3.x. In 3.x, strings are Unicode, and > may be stored either in 16bit or 32bit form (Windows usually compiled > using the former, and Linux the latter). That's an internal storage that you (generic you) the Python programmer doesn't see, except perhaps indirectly via memory consumption. Do you know how many bits are used to store floats? If you try: >>> sys.getsizeof(1.1) 16 in Python 2.6 or better, it tells you that a float *object* takes 16 bytes, but it doesn't tell you anything about the underlying C-level floating point data. And a float that prints like: 1.0 takes up exactly the same storage as one that prints like: 1.234567890123456789 We can do a bit better with unicode strings: >>> sys.getsizeof(u'a') - sys.getsizeof(u'') 2 but frankly, who cares? It doesn't *mean* anything. Whether a character takes up two bytes, or twenty-two bytes, is irrelevant to how it prints. > Presumably in 3.x, urandom returns a byte string (see the b'xxxx' > form), which is 8 bits each, same as 2.x strings. So you'd expect > only two hex digits for each character. It looks like you've missed the point that bytes don't always display as two hex digits. Using Python 3.1, we can see some bytes display in hex-escape form, e.g.: >>> bytes([0, 1, 20, 30, 200]) b'\x00\x01\x14\x1e\xc8' some will display in character-escape form: >>> bytes([9, 10, 13]) b'\t\n\r' and some will display as unescaped ASCII characters: >>> bytes([40, 41, 80, 90, 110]) b'()PZn' So you can't make any definitive statement that the output of urandom will be displayed in hex form. Because the output is random, you might, by some incredible fluke, get: >>> os.urandom(6) b'hello ' >>> os.urandom(6) b'world!' I wouldn't like to bet on it though. By my calculation, the odds of that exact output is 1 in 79228162514264337593543950336. The odds of getting nothing but hex-escaped characters is a bit better. By my estimate, the odds of getting 12 hex-escaped characters in a row is about 1 in 330. For six in a row, it's about 1 in 18 or so. By the way, an interesting aside... bytes aren't always 8 bits. Of course, on just about all machines that have Python on them, they will be, but there are still machines and devices such as signal processors where bytes are something other than 8 bits. Historically, common values included 5, 6, 7, 9, or 16 bits, and the C and C++ standards still define a constant CHAR_BIT to specify the number of bits in a byte. -- Steven D'Aprano From davea at ieee.org Mon Aug 9 15:51:34 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 09 Aug 2010 09:51:34 -0400 Subject: [Tutor] os.urandom() In-Reply-To: <201008092039.25030.steve@pearwood.info> References: <4C5FC92C.5010907@ieee.org> <201008092039.25030.steve@pearwood.info> Message-ID: <4C6007E6.4000009@ieee.org> Steven D'Aprano wrote: > On Mon, 9 Aug 2010 07:23:56 pm Dave Angel wrote: > > >> Big difference between 2.x and 3.x. In 3.x, strings are Unicode, and >> may be stored either in 16bit or 32bit form (Windows usually compiled >> using the former, and Linux the latter). >> > > That's an internal storage that you (generic you) the Python programmer > doesn't see, except perhaps indirectly via memory consumption. > > Do you know how many bits are used to store floats? If you try: > You've missed including the context that I was responding to. I'm well aware of many historical architectures, and have dealt with the differences between the coding on an IBM 26 keypunch and an IBM 29. As well as converting the 12 bit raw bits coming from a hollerith card into various forms compatible with the six characters per word storage of the CDC 6400. I doubt however that Python could be ported to a machine with a 9 bit byte or a 7 bit byte, and remain fully compatible. The OP was talking about the display of \xhh and thought he had discovered a discrepancy between the docs on 2.x and 3.x. And for that purpose it is quite likely relevant that 3.x has characters that won't fit in 8 bits, and thus be describable in two hex digits. I was trying to point out that characters in 3.x are more than 16 bits, and thus would require more than two hex digits. But a b'' string does not. I don't usually use 3.1, but I was curious to discover that repr() won't display a string with an arbitrary Unicode character in it. ++a = chr(300) ++repr(a) File "c:\progfiles\python31\lib\encodings\cp437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u012c' in position 2: character maps to I would have expected it to use something like: "x\012c" I realize that it can't produce a pair of bytes without a (non-ASCII) decoding, but it doesn't make sense to me that repr() doesn't display something reasonable, like hex. FWIW, my sys.stdout.encoding is cp437. DaveA From rabidpoobear at gmail.com Mon Aug 9 16:26:51 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 9 Aug 2010 09:26:51 -0500 Subject: [Tutor] Fwd: Need mentor In-Reply-To: References: Message-ID: On Mon, Aug 9, 2010 at 1:32 AM, Ranjith Kumar wrote: > Hi all, > > I have?described?the theme of my project here, > Cheers > Ranjith, > This sounds kind of like homework. Is it homework? If not, where did you get this spec from? Thanks, -Luke From asmosis.asterix at gmail.com Mon Aug 9 18:02:01 2010 From: asmosis.asterix at gmail.com (Daniel) Date: Mon, 9 Aug 2010 19:02:01 +0300 Subject: [Tutor] Question about strings Message-ID: Hi, I'm trying to solve an exercise, a beginners one but I have a question. So the exercise sounds like this: Define a string s = ?colorless?. Write a Python statement that changes this to ?colour- less?, using only the slice and concatenation operations. So I did wrote this: *1)s = 'colorless' 2)ss = s[:4] + 'u' + s[4:] 3)print(ss) *I do not understand something. So on the second line, the slicing lasts from the start of the s string to the forth character. But from were does the counting start? 0 or 1? From this code it's obvious that it starts from one, but how, strings counting doesn't start from 0? If I do len(s) i get 9 but if I do s[9] I get an error, out of range. Can please someone clear me this indexing thing? It's so frustrating and confusing. * * -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Mon Aug 9 18:15:42 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 9 Aug 2010 11:15:42 -0500 Subject: [Tutor] Question about strings In-Reply-To: References: Message-ID: <82F0F8F7-D4DE-4AC5-949C-F6EC8DE7ADB8@gmail.com> Hey email in plain text in the future, HTML is not kind to mobile screens and in general you should plaintext reply to tech lists. All list indices start from 0. But you don't get the last value. So slice[1:5] would skip the first char and then include the next 3. It's the same as range. Range(1,100) returns 1,2,....,99. Hope that helps -luke Sent from my iPhone On Aug 9, 2010, at 11:02 AM, Daniel <.asterix at gmail.com> wrote: > Hi, I'm trying to solve an exercise, a beginners one but I have a question. So the exercise sounds like this: > > Define a string s = ?colorless?. Write a Python statement that changes this to ?colour- > less?, using only the slice and concatenation operations. > > So I did wrote this: > 1)s = 'colorless' > 2)ss = s[:4] + 'u' + s[4:] > > 3)print(ss) > > I do not understand something. So on the second line, the slicing lasts from the start of the s string to the forth character. But from were > > does the counting start? 0 or 1? From this code it's obvious that it starts from one, but how, strings counting doesn't start from 0? If I do > len(s) i get 9 but if I do s[9] I get an error, out of range. Can please someone clear me this indexing thing? It's so frustrating and > > confusing. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Aug 9 19:32:31 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Aug 2010 18:32:31 +0100 Subject: [Tutor] Question about strings References: Message-ID: "Daniel" wrote > *1)s = 'colorless' > 2)ss = s[:4] + 'u' + s[4:] > > *I do not understand something. So on the second line, the slicing > lasts from the start of the s string to the forth character. Correct, slices include the first index but not the last. > does the counting start? 0 or 1? It starts with 0. [:4] means 0,1,2,3 > From this code it's obvious that it starts from one, > but how, strings counting doesn't start from 0? No, it starts from 0. > len(s) i get 9 but if I do s[9] I get an error, > out of range. Yes but if you do range(0,len(s)) you get the right set of values to index s. - 0...(9-1) A slice works like range() > please someone clear me this indexing thing? It's so frustrating and > confusing. It is confusing until you get used to it. You will find over time that it is actually more convenient that way, but it is very strange for newbies. There are some languages that start indexing at 1 but they get into all sorts of complications in other areas, most language designers have settled for zero based indexes as the best overall solution. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From ian at ianozsvald.com Mon Aug 9 20:46:49 2010 From: ian at ianozsvald.com (Ian Ozsvald) Date: Mon, 9 Aug 2010 19:46:49 +0100 Subject: [Tutor] Weekly Python Tips mailing list is ready to join Message-ID: I asked a few days ago if there'd be interest in a Python Tips list that sends out Python tips to your inbox each week - I've had a lovely response over the weekend so I'll proceed with creating the list. Thanks for the replies! As I mentioned I have a whole set of tips planned. They'll cover useful stuff (like "how to write Pythonically"), cool stuff (including some 3D, gaming, web-dev and maths), links to modules you probably haven't heard of yet and guest tips from known Pythonistas. I'll be sending out one tip per week, it'll include some source code and links to useful resources. There will definitely be links back to useful ShowMeDo videos to illustrate the ideas. I'll publish the first set of tips when I have 50 people on the list - this way I'll get good feedback on what's required which will guide which tips I cover next. To join the list send an email here: weeklypytips at aweber.com and accept the opt-in message you receive. It is an Aweber mailing list (they're a well known mailing list host) and you can unsubscribe at any time if it isn't helpful. I promise no spam or foolishness (and I certainly won't pass on your email address to 3rd parties), you'll just get helpful Python tips. It'll be quiet for a week or two whilst I gather the first 50 sign-ups and then I'll start posting out the tips. Looking forward to building the list and getting some feedback, Ian. -- Ian Ozsvald (A.I. researcher, screencaster) ian at IanOzsvald.com http://IanOzsvald.com http://ShowMeDo.com http://MorConsulting.com/ http://blog.AICookbook.com/ http://TheScreencastingHandbook.com http://FivePoundApp.com/ http://twitter.com/IanOzsvald From bgailer at gmail.com Mon Aug 9 21:32:25 2010 From: bgailer at gmail.com (bob gailer) Date: Mon, 09 Aug 2010 15:32:25 -0400 Subject: [Tutor] Fwd: Need mentor In-Reply-To: References: Message-ID: <4C6057C9.1010107@gmail.com> Exactly what do you want your mentor to do? -- Bob Gailer 919-636-4239 Chapel Hill NC From steve at pearwood.info Tue Aug 10 02:24:03 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 10 Aug 2010 10:24:03 +1000 Subject: [Tutor] os.urandom() In-Reply-To: <4C6007E6.4000009@ieee.org> References: <201008092039.25030.steve@pearwood.info> <4C6007E6.4000009@ieee.org> Message-ID: <201008101024.04651.steve@pearwood.info> On Mon, 9 Aug 2010 11:51:34 pm you wrote: > Steven D'Aprano wrote: > > On Mon, 9 Aug 2010 07:23:56 pm Dave Angel wrote: > >> Big difference between 2.x and 3.x. In 3.x, strings are Unicode, > >> and may be stored either in 16bit or 32bit form (Windows usually > >> compiled using the former, and Linux the latter). > > > > That's an internal storage that you (generic you) the Python > > programmer doesn't see, except perhaps indirectly via memory > > consumption. > > > > Do you know how many bits are used to store floats? If you try: > > > > You've missed including the context that I was responding to. Possibly so, but I didn't miss *reading* the context, and it wasn't clear to me exactly what you were trying to get across to Richard. Maybe that was just my poor reading comprehension, or maybe the two of you had gone of on a tangent that was confusing. At least to me. > I'm > well aware of many historical architectures, and have dealt with the > differences between the coding on an IBM 26 keypunch and an IBM 29. I only know of these ancient machines second or third hand. In any case, my mention of non-8-bit bytes was clearly marked as an aside, and not meant to imply that the number of bits in a byte will vary from one Python implementation to another. The point of my post was that the internal storage of Unicode strings is virtually irrelevant to the Python programmer. Strings are strings, and the way Python stores them in memory is as irrelevant as the way it stores tuples, or floats, or long ints, or None. That is to say, the way they are stored will effect speed and memory consumption, but as a Python programmer, we have very little say in the matter. We deal with high-level objects. Unless we hack the Python compiler, or possibly do strange and dangerous things with ctypes, we don't have any access to the internal format of those objects. [...] > The OP was talking about the display of \xhh and thought he had > discovered a discrepancy between the docs on 2.x and 3.x. And for > that purpose it is quite likely relevant that 3.x has characters that > won't fit in 8 bits, and thus be describable in two hex digits. I > was trying to point out that characters in 3.x are more than 16 bits, > and thus would require more than two hex digits. The number of bytes used for the in-memory unicode implementations does *not* relate to the number of bytes used when decoded to bytes. They're independent. Unicode strings are sequences of code points, integers between 0 and 10ffff in base-16, or 0 and 1114111 in base 10. The in-memory storage of those code points is an implementation detail. The two most common implementations are the 2-byte and 4-byte version, but even there it will depend on whether your platform is big-endian or little-endian or something else. Take code point 61 (base-16), or the character 'a'. Does it matter whether that is stored in memory as a two-byte chunk 0061 or 6100, or a four-byte chunk 00000061, 00006100, 00610000 or 61000000, or something else? No. When you print the character 'a', it prints as character 'a' regardless of what the internal storage looks like. Characters are characters, and the internal storage doesn't matter. We could, if we wanted, write an implementation of Unicode in Python, where the code points are 16 byte (128 bit) int objects. It would be horribly slow, but it would still be Unicode, and the character 'a' would be represented in memory by whatever the PyIntObject C data structure happens to be. (Whatever it is, it won't be pretty.) To get bytes, the internal storage of Unicode doesn't matter. You need to specify an encoding, and the result you get depends on that encoding, not the internal storage in memory: >>> s = 'a' + chr(220) >>> print(s) a? >>> s.encode('latin-1') b'a\xdc' >>> s.encode('utf-8') b'a\xc3\x9c' >>> s.encode('utf-16') b'\xff\xfea\x00\xdc\x00' > But a b'' string does not. Naturally. By definition, each byte in a sequence of bytes is a single byte. > I don't usually use 3.1, but I was curious to discover that repr() > won't display a string with an arbitrary Unicode character in it. repr() doesn't display anything. repr() returns the string representation, not the byte representation. Try this: a = chr(300) b = repr(a) My prediction is that it will succeed, and not fail. Then try this: print(a) My prediction is that it will fail with UnicodeEncodeError. It is is your terminal that can't display arbitrary Unicode characters, because your terminal have a weird encoding set. Fix the terminal, and you won't have the problem: >>> a = chr(300) >>> print(a, repr(a)) ? '?' >>> sys.stdout.encoding 'UTF-8' There's almost never any good reason for using an encoding other than utf-8. > I realize that it can't produce a pair of bytes without a (non-ASCII) > decoding, No, you have that backwards. Strings encode to bytes. Bytes decode to strings. > but it doesn't make sense to me that repr() doesn't display > something reasonable, like hex. You are confused. repr() doesn't display anything, any more than len() displays things. repr() returns a string, not bytes. What happens next depends on what you do with it. > FWIW, my sys.stdout.encoding is cp437. Well, there's your problem. -- Steven D'Aprano From malaclypse2 at gmail.com Tue Aug 10 02:46:55 2010 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 9 Aug 2010 20:46:55 -0400 Subject: [Tutor] Questions regarding strings In-Reply-To: References: Message-ID: On Sun, Aug 8, 2010 at 1:04 PM, Daniel wrote: > > Can someone please explain this to me? Thank you so much and I wish everyone a great day! Beyond what Hugo mentioned in his message, take a look at the tutorial: http://docs.python.org/tutorial/introduction.html#strings I don't see a way to directly link to the section about subscripting and slicing strings, but it's a bit below that link, and starts with "Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0" -- Jerry From wallenpb at gmail.com Tue Aug 10 04:55:35 2010 From: wallenpb at gmail.com (Bill Allen) Date: Mon, 9 Aug 2010 21:55:35 -0500 Subject: [Tutor] problem loading and array from an external file Message-ID: Hi, my name is Bill and I am completely stuck. I have a little bit of code I am working with for the sole purpose of coding in order to learn Python. In order to learn a programming language, I very often use a little text based map of rooms traversal game. So far, so good. However, this time I decided to learn some file operations so I am trying to read the data in from an external file rather than preloading an array inside the code itself. I am able to open the file and read from it. However, I am getting unexpected results when filling the array. Instead of each row in the array being loaded with the matching line in the data file, by the end of the loops all the rows in the array end up being filled with the last line of the data file. I have stepped and traced through it and cannot figure out where I am going wrong. This may not be a Python issue at all, but is likely me being way off in the weeds on my algorithm. This is only the portion of the code for loading the array from the file. I am writing this in Python 3. I believe my problem is somewhere in the read_maze_data_file() function. There are lots of unnecessary extra print statements in this code because I was trying to carefully follow the state of the variables as the code ran. If anyone can point out where I am going wrong, I would really appreciate it. The code: # N S E W U D room0 = [0,0,0,0,0,0,0] room1 = [0,0,0,0,0,0,0] #Pad the first place so that rooms may room2 = [0,0,0,0,0,0,0] #be referenced naturally room3 = [0,0,0,0,0,0,0] room4 = [0,0,0,0,0,0,0] #First places will have special purposes room5 = [0,0,0,0,0,0,0] room6 = [0,0,0,0,0,0,0] #initialize the array with zeros room7 = [0,0,0,0,0,0,0] room = [room0,room1,room2,room3,room4,room5,room6,room7] def clearscreen(numlines=100): """Clear the console. numlines is an optional argument used only as a fall-back. """ import os if os.name == "posix": # Unix/Linux/MacOS/BSD/etc os.system('clear') elif os.name in ("nt", "dos", "ce"): # DOS/Windows os.system('CLS') else: # Fallback for other operating systems. print('\n' * numlines) print(os.name) def print_map(): print("+-------------+") print('|','MAP: ','N','S','E','W','U','D','|', sep="", end="") for x in range(1,8): print() print("|","room",x,"> ", sep="", end="") for y in range(1,7): print(room[x][y], end="") print("|", end="") print() print("+-------------+", end="") def read_maze_data_file(): roomx = [0,0,0,0,0,0,0] n, m = 0, 0 try: filename = 'mazegame.dat' textf = open(filename, 'r') except IOError: print ('Cannot open file %s for reading' % filename) import sys sys.exit(0) # reads one line at a time for line in textf: print("raw line in file: ",line, end="") tempwords = line.split(None) print ("line as read from file: ",tempwords) for n in range(0, len(room)-1): roomx[n] = tempwords[n] #print(roomx[n]) print("roomx",roomx) room[m] = roomx print("room ",m,room[m]) print("current state of room array") print("room 0",room[0]) print("room 1",room[1]) print("room 2",room[2]) print("room 3",room[3]) print("room 4",room[4]) print("room 5",room[5]) print("room 6",room[6]) print("room 7",room[7]) m += 1 textf.close() return(room) #----END read_maze_data_file() #---------MAIN SECTION--------- clearscreen() print("LOAD AN ARRARY FROM A FILE") print(" by Bill Allen") print() print("initial state of room array") print(room) print() print("data from file") room_final = read_maze_data_file() print("from MAIN") print(room_final) print() print("a PRINT_MAP call from MAIN") print_map() print() print() ======================= partial sample output showing the current incorrect results: a PRINT_MAP call from MAIN +-------------+ |MAP: NSEWUD| |room1> 000050| |room2> 000050| |room3> 000050| |room4> 000050| |room5> 000050| |room6> 000050| |room7> 000050| +-------------+ ========================= the contents of the data file, mazegame.dat 0 0 0 0 0 0 0 0 0 4 2 0 0 0 0 0 0 1 3 6 0 0 0 5 0 2 0 0 0 1 0 5 0 0 0 0 3 0 0 4 0 7 0 0 0 0 0 0 2 0 0 0 0 0 5 0 From bgailer at gmail.com Tue Aug 10 05:08:36 2010 From: bgailer at gmail.com (bob gailer) Date: Mon, 09 Aug 2010 23:08:36 -0400 Subject: [Tutor] problem loading and array from an external file In-Reply-To: References: Message-ID: <4C60C2B4.5000007@gmail.com> On 8/9/2010 10:55 PM, Bill Allen wrote: > Hi, my name is Bill and I am completely stuck. I have a little bit of > code I am working with for the sole purpose of coding in order to > learn Python. In order to learn a programming language, I very often > use a little text based map of rooms traversal game. So far, so good. > However, this time I decided to learn some file operations so I am > trying to read the data in from an external file rather than > preloading an array inside the code itself. I am able to open the > file and read from it. However, I am getting unexpected results when > filling the array. Instead of each row in the array being loaded with > the matching line in the data file, by the end of the loops all the > rows in the array end up being filled with the last line of the data > file. I have stepped and traced through it and cannot figure out > where I am going wrong. How did you step thru it? If you do it very precisely the problem will be evident. I'd prefer you discover it by careful step-thru rather than feeding you the answer. > This may not be a Python issue at all, but is > likely me being way off in the weeds on my algorithm. This is only > the portion of the code for loading the array from the file. I am > writing this in Python 3. I believe my problem is somewhere in the > read_maze_data_file() function. That is accurate. > There are lots of unnecessary extra > print statements in this code because I was trying to carefully follow > the state of the variables as the code ran. If anyone can point out > where I am going wrong, I would really appreciate it. > As mentioned above you have a bug in your step-throuogh process. Write down the variables that are affected by each statement and note their new values. > The code: > # N S E W U D > room0 = [0,0,0,0,0,0,0] > room1 = [0,0,0,0,0,0,0] #Pad the first place so that rooms may > room2 = [0,0,0,0,0,0,0] #be referenced naturally > room3 = [0,0,0,0,0,0,0] > room4 = [0,0,0,0,0,0,0] #First places will have special purposes > room5 = [0,0,0,0,0,0,0] > room6 = [0,0,0,0,0,0,0] #initialize the array with zeros > room7 = [0,0,0,0,0,0,0] > > room = [room0,room1,room2,room3,room4,room5,room6,room7] > > > def clearscreen(numlines=100): > """Clear the console. > numlines is an optional argument used only as a fall-back. > """ > import os > if os.name == "posix": > # Unix/Linux/MacOS/BSD/etc > os.system('clear') > elif os.name in ("nt", "dos", "ce"): > # DOS/Windows > os.system('CLS') > else: > # Fallback for other operating systems. > print('\n' * numlines) > print(os.name) > > def print_map(): > print("+-------------+") > print('|','MAP: ','N','S','E','W','U','D','|', sep="", end="") > for x in range(1,8): > print() > print("|","room",x,"> ", sep="", end="") > for y in range(1,7): > print(room[x][y], end="") > print("|", end="") > print() > print("+-------------+", end="") > > > def read_maze_data_file(): > > roomx = [0,0,0,0,0,0,0] > n, m = 0, 0 > > try: > filename = 'mazegame.dat' > textf = open(filename, 'r') > except IOError: > print ('Cannot open file %s for reading' % filename) > import sys > sys.exit(0) > > # reads one line at a time > > for line in textf: > print("raw line in file: ",line, end="") > tempwords = line.split(None) > print ("line as read from file: ",tempwords) > > for n in range(0, len(room)-1): > roomx[n] = tempwords[n] > #print(roomx[n]) > > print("roomx",roomx) > room[m] = roomx > print("room ",m,room[m]) > print("current state of room array") > print("room 0",room[0]) > print("room 1",room[1]) > print("room 2",room[2]) > print("room 3",room[3]) > print("room 4",room[4]) > print("room 5",room[5]) > print("room 6",room[6]) > print("room 7",room[7]) > > m += 1 > > textf.close() > return(room) > > #----END read_maze_data_file() > > > #---------MAIN SECTION--------- > > clearscreen() > > > print("LOAD AN ARRARY FROM A FILE") > print(" by Bill Allen") > print() > print("initial state of room array") > print(room) > print() > > print("data from file") > room_final = read_maze_data_file() > print("from MAIN") > print(room_final) > print() > > print("a PRINT_MAP call from MAIN") > print_map() > print() > print() > > > ======================= > partial sample output showing the current incorrect results: > a PRINT_MAP call from MAIN > +-------------+ > |MAP: NSEWUD| > |room1> 000050| > |room2> 000050| > |room3> 000050| > |room4> 000050| > |room5> 000050| > |room6> 000050| > |room7> 000050| > +-------------+ > ========================= > the contents of the data file, mazegame.dat > 0 0 0 0 0 0 0 > 0 0 4 2 0 0 0 > 0 0 0 1 3 6 0 > 0 0 5 0 2 0 0 > 0 1 0 5 0 0 0 > 0 3 0 0 4 0 7 > 0 0 0 0 0 0 2 > 0 0 0 0 0 5 0 > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Bob Gailer 919-636-4239 Chapel Hill NC From Tom_Roche at pobox.com Tue Aug 10 05:11:25 2010 From: Tom_Roche at pobox.com (Tom Roche) Date: Mon, 09 Aug 2010 23:11:25 -0400 Subject: [Tutor] extending a VS python with cygwin Message-ID: <87zkwvxiua.fsf@pobox.com> summary: how to fix ... me at cygwinBox ~/bin/duplicity-0.6.09$ python setup.py install ... > error: Python was built with Visual Studio 2003; > extensions must be built with a compiler than can generate > compatible binaries. Visual Studio 2003 was not found on this > system. If you have Cygwin installed, you can try compiling with > MingW32, by passing "-c mingw32" to setup.py. me at cygwinBox ~/bin/duplicity-0.6.09$ python -c mingw32 setup.py install > Traceback (most recent call last): > File "", line 1, in > NameError: name 'mingw32' is not defined me at cygwinBox ~/bin/duplicity-0.6.09$ python setup.py -c mingw32 install > usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] > or: setup.py --help [cmd1 cmd2 ...] > or: setup.py --help-commands > or: setup.py cmd --help > error: option -c not recognized me at cygwinBox ~/bin/duplicity-0.6.09$ python setup.py install -c mingw32 > usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] > or: setup.py --help [cmd1 cmd2 ...] > or: setup.py --help-commands > or: setup.py cmd --help > error: invalid command 'mingw32' details: What's the appropriate syntax to solve the above python build problem? Why I ask: I mostly run linux, and I've been using python-based `duplicity` http://duplicity.nongnu.org/ to back that up. I've got an older winxp box (SP3, uptodate with WU) which I keep mostly to run ArcGIS, which has happily run many versions of cygwin (which I keep uptodate) over the years. I'd like to be able to restore my linux home to my cygwin home for the rare occasions when I need to use the winxp box. To do that, I'd like to install duplicity on the cygwin box. That install process (best described by the somewhat downlevel http://blog.khorun.com/2008/09/using-duplicity-on-windows-under-cygwin.html ) works for the install of the prerequisite GnuPGInterface and boto python modules (process=[download tarball, tar xfz, python setup.py install]) but fails for the install of duplicity itself, with the error above: me at cygwinBox ~/bin/duplicity-0.6.09$ python setup.py install ... > error: Python was built with Visual Studio 2003; Note that I'd cheerfully replace that version of python (the 2.5.2 that shipped with my ArcGIS 9.3), except that I use some ArcGIS extensions which seem to choke on other pythons :-( so I'd prefer to build against that if at all possible. > extensions must be built with a compiler than can generate > compatible binaries. Visual Studio 2003 was not found on this > system. If you have Cygwin installed, you can try compiling with > MingW32, by passing "-c mingw32" to setup.py. I try to take the advice offered, but either it's wrong or I'm missing something: me at cygwinBox ~/bin/duplicity-0.6.09$ python -c mingw32 setup.py install > Traceback (most recent call last): > File "", line 1, in > NameError: name 'mingw32' is not defined me at cygwinBox ~/bin/duplicity-0.6.09$ python setup.py -c mingw32 install > usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] > or: setup.py --help [cmd1 cmd2 ...] > or: setup.py --help-commands > or: setup.py cmd --help > error: option -c not recognized me at cygwinBox ~/bin/duplicity-0.6.09$ python setup.py install -c mingw32 > usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] > or: setup.py --help [cmd1 cmd2 ...] > or: setup.py --help-commands > or: setup.py cmd --help > error: invalid command 'mingw32' What's the appropriate syntax here? Or how else should I fix this? Apologies if this is a FAQ. If this is the wrong list/forum/whatever for this query, please direct me appropriately. Note that the duplicity list is apparently not the place, though :-( TIA, Tom Roche From davea at ieee.org Tue Aug 10 06:24:00 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 10 Aug 2010 00:24:00 -0400 Subject: [Tutor] os.urandom() In-Reply-To: <201008101024.04651.steve@pearwood.info> References: <201008092039.25030.steve@pearwood.info> <4C6007E6.4000009@ieee.org> <201008101024.04651.steve@pearwood.info> Message-ID: <4C60D460.9070701@ieee.org> Steven D'Aprano wrote: > On Mon, 9 Aug 2010 11:51:34 pm you wrote: > >> (Context: Python 3.x, where strings are unicode.) > repr() returns the string > representation, not the byte representation. Try this: > > That's what I was missing. Somehow I assumed it was converting to byte strings. I had assumed that it reverted to /uxxxx or /Uxxxxxxxx whenever a character was outside the ASCII range. That would be a direct analog to what seems to happen on byte strings. Does it only escape newlines and single quotes ? > a = chr(300) > b = repr(a) > > My prediction is that it will succeed, and not fail. Then try this: > > print(a) > > My prediction is that it will fail with UnicodeEncodeError. It is is > your terminal that can't display arbitrary Unicode characters, because > your terminal have a weird encoding set. Fix the terminal, and you > won't have the problem: > > Any suggestions how to fix the Windows console to interpret utf8? > FWIW, my sys.stdout.encoding is cp437. > > Well, there's your problem. > > From bgailer at gmail.com Tue Aug 10 15:21:43 2010 From: bgailer at gmail.com (bob gailer) Date: Tue, 10 Aug 2010 09:21:43 -0400 Subject: [Tutor] problem loading and array from an external file In-Reply-To: References: <4C60C2B4.5000007@gmail.com> Message-ID: <4C615267.9080306@gmail.com> On 8/9/2010 11:13 PM, Bill Allen wrote: > Bob, > > Thanks for the feedback. I have been stepping through it in the IDLE > debugger. However, it may be that I am letting the debugger get in my > way as I am new to it also. You are right. I'll get out the old > yellow legal pad and step through it by hand. In fact, I think I will > process the loop entirely by hand, just the logic, and see how the > variables look that way. > > Glad I could help. PLEASE remember to always reply-all so a copy goes to the list. > Thanks, > Bill > > > On Mon, Aug 9, 2010 at 10:08 PM, bob gailer wrote: > >> On 8/9/2010 10:55 PM, Bill Allen wrote: >> >>> Hi, my name is Bill and I am completely stuck. I have a little bit of >>> code I am working with for the sole purpose of coding in order to >>> learn Python. In order to learn a programming language, I very often >>> use a little text based map of rooms traversal game. So far, so good. >>> However, this time I decided to learn some file operations so I am >>> trying to read the data in from an external file rather than >>> preloading an array inside the code itself. I am able to open the >>> file and read from it. However, I am getting unexpected results when >>> filling the array. Instead of each row in the array being loaded with >>> the matching line in the data file, by the end of the loops all the >>> rows in the array end up being filled with the last line of the data >>> file. I have stepped and traced through it and cannot figure out >>> where I am going wrong. >>> >> How did you step thru it? If you do it very precisely the problem will be >> evident. >> I'd prefer you discover it by careful step-thru rather than feeding you the >> answer. >> >> >>> This may not be a Python issue at all, but is >>> likely me being way off in the weeds on my algorithm. This is only >>> the portion of the code for loading the array from the file. I am >>> writing this in Python 3. I believe my problem is somewhere in the >>> read_maze_data_file() function. >>> >> That is accurate. >> >> >>> There are lots of unnecessary extra >>> print statements in this code because I was trying to carefully follow >>> the state of the variables as the code ran. If anyone can point out >>> where I am going wrong, I would really appreciate it. >>> >>> >> As mentioned above you have a bug in your step-throuogh process. Write down >> the variables that are affected by each statement and note their new values. >> >>> The code: >>> # N S E W U D >>> room0 = [0,0,0,0,0,0,0] >>> room1 = [0,0,0,0,0,0,0] #Pad the first place so that rooms may >>> room2 = [0,0,0,0,0,0,0] #be referenced naturally >>> room3 = [0,0,0,0,0,0,0] >>> room4 = [0,0,0,0,0,0,0] #First places will have special purposes >>> room5 = [0,0,0,0,0,0,0] >>> room6 = [0,0,0,0,0,0,0] #initialize the array with zeros >>> room7 = [0,0,0,0,0,0,0] >>> >>> room = [room0,room1,room2,room3,room4,room5,room6,room7] >>> >>> >>> def clearscreen(numlines=100): >>> """Clear the console. >>> numlines is an optional argument used only as a fall-back. >>> """ >>> import os >>> if os.name == "posix": >>> # Unix/Linux/MacOS/BSD/etc >>> os.system('clear') >>> elif os.name in ("nt", "dos", "ce"): >>> # DOS/Windows >>> os.system('CLS') >>> else: >>> # Fallback for other operating systems. >>> print('\n' * numlines) >>> print(os.name) >>> >>> def print_map(): >>> print("+-------------+") >>> print('|','MAP: ','N','S','E','W','U','D','|', sep="", end="") >>> for x in range(1,8): >>> print() >>> print("|","room",x,"> ", sep="", end="") >>> for y in range(1,7): >>> print(room[x][y], end="") >>> print("|", end="") >>> print() >>> print("+-------------+", end="") >>> >>> >>> def read_maze_data_file(): >>> >>> roomx = [0,0,0,0,0,0,0] >>> n, m = 0, 0 >>> >>> try: >>> filename = 'mazegame.dat' >>> textf = open(filename, 'r') >>> except IOError: >>> print ('Cannot open file %s for reading' % filename) >>> import sys >>> sys.exit(0) >>> >>> # reads one line at a time >>> >>> for line in textf: >>> print("raw line in file: ",line, end="") >>> tempwords = line.split(None) >>> print ("line as read from file: ",tempwords) >>> >>> for n in range(0, len(room)-1): >>> roomx[n] = tempwords[n] >>> #print(roomx[n]) >>> >>> print("roomx",roomx) >>> room[m] = roomx >>> print("room ",m,room[m]) >>> print("current state of room array") >>> print("room 0",room[0]) >>> print("room 1",room[1]) >>> print("room 2",room[2]) >>> print("room 3",room[3]) >>> print("room 4",room[4]) >>> print("room 5",room[5]) >>> print("room 6",room[6]) >>> print("room 7",room[7]) >>> >>> m += 1 >>> >>> textf.close() >>> return(room) >>> >>> #----END read_maze_data_file() >>> >>> >>> #---------MAIN SECTION--------- >>> >>> clearscreen() >>> >>> >>> print("LOAD AN ARRARY FROM A FILE") >>> print(" by Bill Allen") >>> print() >>> print("initial state of room array") >>> print(room) >>> print() >>> >>> print("data from file") >>> room_final = read_maze_data_file() >>> print("from MAIN") >>> print(room_final) >>> print() >>> >>> print("a PRINT_MAP call from MAIN") >>> print_map() >>> print() >>> print() >>> >>> >>> ======================= >>> partial sample output showing the current incorrect results: >>> a PRINT_MAP call from MAIN >>> +-------------+ >>> |MAP: NSEWUD| >>> |room1> 000050| >>> |room2> 000050| >>> |room3> 000050| >>> |room4> 000050| >>> |room5> 000050| >>> |room6> 000050| >>> |room7> 000050| >>> +-------------+ >>> ========================= >>> the contents of the data file, mazegame.dat >>> 0 0 0 0 0 0 0 >>> 0 0 4 2 0 0 0 >>> 0 0 0 1 3 6 0 >>> 0 0 5 0 2 0 0 >>> 0 1 0 5 0 0 0 >>> 0 3 0 0 4 0 7 >>> 0 0 0 0 0 0 2 >>> 0 0 0 0 0 5 0 >>> _______________________________________________ >>> Tutor maillist - Tutor at python.org >>> To unsubscribe or change subscription options: >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> >> >> -- >> Bob Gailer >> 919-636-4239 >> Chapel Hill NC >> >> >> > -- Bob Gailer 919-636-4239 Chapel Hill NC From steve at pearwood.info Tue Aug 10 16:33:11 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 11 Aug 2010 00:33:11 +1000 Subject: [Tutor] os.urandom() In-Reply-To: <4C60D460.9070701@ieee.org> References: <201008101024.04651.steve@pearwood.info> <4C60D460.9070701@ieee.org> Message-ID: <201008110033.14220.steve@pearwood.info> On Tue, 10 Aug 2010 02:24:00 pm Dave Angel wrote: > > repr() returns the string > > representation, not the byte representation. Try this: > > That's what I was missing. Somehow I assumed it was converting to > byte strings. > > I had assumed that it reverted to /uxxxx or /Uxxxxxxxx whenever a > character was outside the ASCII range. That would be a direct analog > to what seems to happen on byte strings. Does it only escape > newlines and single quotes ? It seems to escape control characters, such as \x00 \x11 \x88 or \x99, but nothing else. There's probably something in the Unicode standard that specifies which characters need to be escaped and which don't. [...] > Any suggestions how to fix the Windows console to interpret utf8? I don't know about Windows, but under Linux there is a menu command for most xterms that let you set it. Googling led me to this page: which, if I've read it right, suggests that you should be able to type: chcp 65001 at the DOS prompt before launching Python, and it theoretically will use UTF-8. Good luck. -- Steven D'Aprano From mail at timgolden.me.uk Tue Aug 10 16:38:02 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 10 Aug 2010 15:38:02 +0100 Subject: [Tutor] os.urandom() In-Reply-To: <201008110033.14220.steve@pearwood.info> References: <201008101024.04651.steve@pearwood.info> <4C60D460.9070701@ieee.org> <201008110033.14220.steve@pearwood.info> Message-ID: <4C61644A.9000206@timgolden.me.uk> On 10/08/2010 15:33, Steven D'Aprano wrote: > On Tue, 10 Aug 2010 02:24:00 pm Dave Angel wrote: > > [...] >> Any suggestions how to fix the Windows console to interpret utf8? There are several tracker issues relating to this one. The current position seems to be: it's not easy. I've done no more than play with it myself. Steven's suggestions about chcp 65001 look good but Python doesn't supply a 65001 codec so you have to play about with aliases and even then it doesn't work :( Feel free to search the tracker and research a solution :) TJG From steve at pearwood.info Tue Aug 10 16:41:29 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 11 Aug 2010 00:41:29 +1000 Subject: [Tutor] os.urandom() In-Reply-To: <201008110033.14220.steve@pearwood.info> References: <4C60D460.9070701@ieee.org> <201008110033.14220.steve@pearwood.info> Message-ID: <201008110041.41043.steve@pearwood.info> On Wed, 11 Aug 2010 12:33:11 am Steven D'Aprano wrote: > > Any suggestions how to fix the Windows console to interpret utf8? > > I don't know about Windows, but under Linux there is a menu command > for most xterms that let you set it. > > Googling led me to this page: Oops, forgot to paste the link. http://illegalargumentexception.blogspot.com/2009/04/i18n-unicode-at-windows-command-prompt.html#charsets_unicodeconsole -- Steven D'Aprano From wallenpb at gmail.com Tue Aug 10 16:42:24 2010 From: wallenpb at gmail.com (Bill Allen) Date: Tue, 10 Aug 2010 09:42:24 -0500 Subject: [Tutor] problem loading and array from an external file In-Reply-To: <4C615267.9080306@gmail.com> References: <4C60C2B4.5000007@gmail.com> <4C615267.9080306@gmail.com> Message-ID: On Tue, Aug 10, 2010 at 8:21 AM, bob gailer wrote: > On 8/9/2010 11:13 PM, Bill Allen wrote: >> >> Bob, >> >> Thanks for the feedback. ?I have been stepping through it in the IDLE >> debugger. ?However, it may be that I am letting the debugger get in my >> way as I am new to it also. ?You are right. ? I'll get out the old >> yellow legal pad and step through it by hand. ?In fact, I think I will >> process the loop entirely by hand, just the logic, and see how the >> variables look that way. >> >> > > Glad I could help. > Bob, I was really off on that algorithm and had way over complicated it. I have it working correctly now, but for the sake of those who saw my earlier really botched code, here is the resultant code that works. The entire inner loop and intermediate variables are removed, but shown commented out. I had somehow thought I needed to read each member of each subarray in individually. That was not the case and that inner loop was overwriting the array. # reads one line at a time from file and puts data into array for line in textf: #tempwords = line.split(None) #for n in range(0, len(room)-1): # roomx[n] = tempwords[n] #room[m] = roomx room[m] = line.split(None) m += 1 > >> Thanks, >> Bill >> >> >> On Mon, Aug 9, 2010 at 10:08 PM, bob gailer ?wrote: >> >>> >>> On 8/9/2010 10:55 PM, Bill Allen wrote: >>> >>>> >>>> Hi, my name is Bill and I am completely stuck. ?I have a little bit of >>>> code I am working with for the sole purpose of coding in order to >>>> learn Python. ?In order to learn a programming language, I very often >>>> use a little text based map of rooms traversal game. ?So far, so good. >>>> ?However, this time I decided to learn some file operations so I am >>>> trying to read the data in from an external file rather than >>>> preloading an array inside the code itself. ?I am able to open the >>>> file and read from it. ?However, I am getting unexpected results when >>>> filling the array. ?Instead of each row in the array being loaded with >>>> the matching line in the data file, by the end of the loops all the >>>> rows in the array end up being filled with the last line of the data >>>> file. ? I have stepped and traced through it and cannot figure out >>>> where I am going wrong. >>>> >>> >>> How did you step thru it? If you do it very precisely the problem will be >>> evident. >>> I'd prefer you discover it by careful step-thru rather than feeding you >>> the >>> answer. >>> >>> >>>> >>>> This may not be a Python issue at all, but is >>>> likely me being way off in the weeds on my algorithm. ?This is only >>>> the portion of the code for loading the array from the file. ?I am >>>> writing this in Python 3. ?I believe my problem is somewhere in the >>>> read_maze_data_file() function. >>>> >>> >>> That is accurate. >>> >>> >>>> >>>> There are lots of unnecessary extra >>>> print statements in this code because I was trying to carefully follow >>>> the state of the variables as the code ran. ?If anyone can point out >>>> where I am going wrong, I would really appreciate it. >>>> >>>> >>> >>> As mentioned above you have a bug in your step-throuogh process. Write >>> down >>> the variables that are affected by each statement and note their new >>> values. >>> >>>> >>>> The code: >>>> # ? ? ? ? ?N S E W U D >>>> room0 = [0,0,0,0,0,0,0] >>>> room1 = [0,0,0,0,0,0,0] ? ? #Pad the first place so that rooms may >>>> room2 = [0,0,0,0,0,0,0] ? ? #be referenced naturally >>>> room3 = [0,0,0,0,0,0,0] >>>> room4 = [0,0,0,0,0,0,0] ? ? ? ? ?#First places will have special >>>> purposes >>>> room5 = [0,0,0,0,0,0,0] >>>> room6 = [0,0,0,0,0,0,0] ? ? ? ? ?#initialize the array with zeros >>>> room7 = [0,0,0,0,0,0,0] >>>> >>>> room = [room0,room1,room2,room3,room4,room5,room6,room7] >>>> >>>> >>>> def clearscreen(numlines=100): >>>> ? ?"""Clear the console. >>>> ? ?numlines is an optional argument used only as a fall-back. >>>> ? ?""" >>>> ? ?import os >>>> ? ?if os.name == "posix": >>>> ? ? ? ?# Unix/Linux/MacOS/BSD/etc >>>> ? ? ? ?os.system('clear') >>>> ? ?elif os.name in ("nt", "dos", "ce"): >>>> ? ? ? ?# DOS/Windows >>>> ? ? ? ?os.system('CLS') >>>> ? ?else: >>>> ? ? ? ?# Fallback for other operating systems. >>>> ? ? ? ?print('\n' * numlines) >>>> ? ?print(os.name) >>>> >>>> def print_map(): >>>> ? ?print("+-------------+") >>>> ? ?print('|','MAP: ? ','N','S','E','W','U','D','|', sep="", end="") >>>> ? ?for x in range(1,8): >>>> ? ? ? ?print() >>>> ? ? ? ?print("|","room",x,"> ? ?", sep="", end="") >>>> ? ? ? ?for y in range(1,7): >>>> ? ? ? ? ? ?print(room[x][y], end="") >>>> ? ? ? ?print("|", end="") >>>> ? ?print() >>>> ? ?print("+-------------+", end="") >>>> >>>> >>>> def read_maze_data_file(): >>>> >>>> ? ?roomx = [0,0,0,0,0,0,0] >>>> ? ?n, m = 0, 0 >>>> >>>> ? ?try: >>>> ? ? ?filename = 'mazegame.dat' >>>> ? ? ?textf = open(filename, 'r') >>>> ? ?except IOError: >>>> ? ? ?print ('Cannot open file %s for reading' % filename) >>>> ? ? ?import sys >>>> ? ? ?sys.exit(0) >>>> >>>> # reads one line at a time >>>> >>>> ? ?for line in textf: >>>> ? ? ? ?print("raw line in file: ",line, end="") >>>> ? ? ? ?tempwords = line.split(None) >>>> ? ? ? ?print ("line as read from file: ",tempwords) >>>> >>>> ? ? ? ?for n in range(0, len(room)-1): >>>> ? ? ? ? ? ?roomx[n] = tempwords[n] >>>> ? ? ? ? ? ?#print(roomx[n]) >>>> >>>> ? ? ? ?print("roomx",roomx) >>>> ? ? ? ?room[m] = roomx >>>> ? ? ? ?print("room ",m,room[m]) >>>> ? ? ? ?print("current state of room array") >>>> ? ? ? ?print("room 0",room[0]) >>>> ? ? ? ?print("room 1",room[1]) >>>> ? ? ? ?print("room 2",room[2]) >>>> ? ? ? ?print("room 3",room[3]) >>>> ? ? ? ?print("room 4",room[4]) >>>> ? ? ? ?print("room 5",room[5]) >>>> ? ? ? ?print("room 6",room[6]) >>>> ? ? ? ?print("room 7",room[7]) >>>> >>>> ? ? ? ?m += 1 >>>> >>>> ? ?textf.close() >>>> ? ?return(room) >>>> >>>> #----END read_maze_data_file() >>>> >>>> >>>> #---------MAIN SECTION--------- >>>> >>>> clearscreen() >>>> >>>> >>>> print("LOAD AN ARRARY FROM A FILE") >>>> print(" ? ? ? ? ? ? ?by Bill Allen") >>>> print() >>>> print("initial state of room array") >>>> print(room) >>>> print() >>>> >>>> print("data from file") >>>> room_final = read_maze_data_file() >>>> print("from MAIN") >>>> print(room_final) >>>> print() >>>> >>>> print("a PRINT_MAP call from MAIN") >>>> print_map() >>>> print() >>>> print() >>>> >>>> >>>> ======================= >>>> partial sample output showing the current incorrect results: >>>> a PRINT_MAP call from MAIN >>>> +-------------+ >>>> |MAP: ? NSEWUD| >>>> |room1> ? ?000050| >>>> |room2> ? ?000050| >>>> |room3> ? ?000050| >>>> |room4> ? ?000050| >>>> |room5> ? ?000050| >>>> |room6> ? ?000050| >>>> |room7> ? ?000050| >>>> +-------------+ >>>> ========================= >>>> the contents of the data file, mazegame.dat >>>> 0 0 0 0 0 0 0 >>>> 0 0 4 2 0 0 0 >>>> 0 0 0 1 3 6 0 >>>> 0 0 5 0 2 0 0 >>>> 0 1 0 5 0 0 0 >>>> 0 3 0 0 4 0 7 >>>> 0 0 0 0 0 0 2 >>>> 0 0 0 0 0 5 0 >>>> _______________________________________________ >>>> Tutor maillist ?- ?Tutor at python.org >>>> To unsubscribe or change subscription options: >>>> http://mail.python.org/mailman/listinfo/tutor >>>> >>>> >>>> >>> >>> -- >>> Bob Gailer >>> 919-636-4239 >>> Chapel Hill NC >>> >>> >>> >> >> > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > From bgailer at gmail.com Tue Aug 10 16:59:10 2010 From: bgailer at gmail.com (bob gailer) Date: Tue, 10 Aug 2010 10:59:10 -0400 Subject: [Tutor] problem loading and array from an external file In-Reply-To: References: <4C60C2B4.5000007@gmail.com> <4C615267.9080306@gmail.com> Message-ID: <4C61693E.1010103@gmail.com> On 8/10/2010 10:42 AM, Bill Allen wrote: > Bob, > > I was really off on that algorithm and had way over complicated it. > I have it working correctly now, but for the sake of those who saw my > earlier really botched code, here is the resultant code that works. > The entire inner loop and intermediate variables are removed, but > shown commented out. I had somehow thought I needed to read each > member of each subarray in individually. That was not the case and > that inner loop was overwriting the array. > > # reads one line at a time from file and puts data into array > for line in textf: > #tempwords = line.split(None) > #for n in range(0, len(room)-1): > # roomx[n] = tempwords[n] > #room[m] = roomx > room[m] = line.split(None) > m += 1 > > Great. Good work. Teach a man to fish? Now for the refinements. First you can use enumerate to obtain the room index: for m, line in enumerate(textf): room[m] = line.split(None) Second you can start with an empty list and append: rooms = [] for line in textf: rooms.append(line.split(None)) Third you can use list comprehension: rooms = [line.split(None) for line in textf] -- Bob Gailer 919-636-4239 Chapel Hill NC From davea at ieee.org Tue Aug 10 17:52:12 2010 From: davea at ieee.org (Dave Angel) Date: Tue, 10 Aug 2010 11:52:12 -0400 Subject: [Tutor] os.urandom() In-Reply-To: <201008110033.14220.steve@pearwood.info> References: <201008101024.04651.steve@pearwood.info> <4C60D460.9070701@ieee.org> <201008110033.14220.steve@pearwood.info> Message-ID: <4C6175AC.4050406@ieee.org> Steven D'Aprano wrote: > On Tue, 10 Aug 2010 02:24:00 pm Dave Angel wrote: > > >> Any suggestions how to fix the Windows console to interpret utf8? >> > > I don't know about Windows, but under Linux there is a menu command for > most xterms that let you set it. > > Googling led me to this page: > > which, if I've read it right, suggests that you should be able to type: > > chcp 65001 > > at the DOS prompt before launching Python, and it theoretically will use > UTF-8. > > Good luck. > > I'm going to need it. If I just try chcp 65001, then batch files no longer work. There are lots of links about how to fix it, but I'll chase them down later. Some suggestions say to issue chcp on each line while invoking the batch, and others say that the console has to have a "compatible" font. Still others say you have to be full screen. Maybe it only works on alternate Thursdays. DaveA From hugo.yoshi at gmail.com Tue Aug 10 18:11:26 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 10 Aug 2010 11:11:26 -0500 Subject: [Tutor] problem loading and array from an external file In-Reply-To: <4C61693E.1010103@gmail.com> References: <4C60C2B4.5000007@gmail.com> <4C615267.9080306@gmail.com> <4C61693E.1010103@gmail.com> Message-ID: On Tue, Aug 10, 2010 at 9:59 AM, bob gailer wrote: > On 8/10/2010 10:42 AM, Bill Allen wrote: >> >> Bob, >> >> I was really off on that algorithm and had way over complicated it. >> I have it working correctly now, but for the sake of those who saw my >> earlier really botched code, here is the resultant code that works. >> The entire inner loop and intermediate variables are removed, but >> shown commented out. ?I had somehow thought I needed to read each >> member of each subarray in individually. ?That was not the case and >> that inner loop was overwriting the array. >> >> # reads one line at a time from file and puts data into array >> ? ? for line in textf: >> ? ? ? ? #tempwords = line.split(None) >> ? ? ? ? #for n in range(0, len(room)-1): >> ? ? ? ? # ? ?roomx[n] = tempwords[n] >> ? ? ? ? #room[m] = roomx >> ? ? ? ? room[m] = line.split(None) >> ? ? ? ? m += 1 >> >> > > Great. Good work. Teach a man to fish? > > Now for the refinements. First you can use enumerate to obtain the room > index: > > ? ?for m, line in enumerate(textf): > ? ? ? ?room[m] = line.split(None) > > > Second you can start with an empty list and append: > > ? ?rooms = [] > ? ?for line in textf: > ? ? ? ?rooms.append(line.split(None)) > > Third you can use list comprehension: > > ? ?rooms = [line.split(None) for line in textf] > Nice going, this is the best way of getting your answer from the tutors list IMO, high fives all around. I wish more threads went like this. You don't actually have to specify the None in line.split AFAIK, but it might be better to be explicit. thoughts on this, anyone? Hugo From eduardo.susan at gmail.com Tue Aug 10 21:39:50 2010 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Tue, 10 Aug 2010 13:39:50 -0600 Subject: [Tutor] Lost in the control flow Message-ID: Hello, list! I'm trying to parse a text file. I'm getting confuse with my strategy, and flags or how to use a sequence of ifs or elifs, continue, etc. Anyhow, after several experiments this is close to what I'd like to get, except, I can't find a way to include all the pin numbers (12 number sequence): Here is my code: http://pastebin.com/1ps6WdF4 The example file is this: http://pastebin.com/1MZmE4d3 Basically, as a initial step, I'd like to transform this: 17 600775301465 CAREYON SIGNS & GRAPHICS EXP 5 93.00 $0.00 $ 26.77 RED DEER AB T4N1L2 FUEL SURCHARGE: 2.10 GST/HST: 1.44 600775301465 18.60 600775301473 18.60 600775301481 18.60 into this. View the code and file for details, please: {'city': 'AB', 'company': 'CAREYON SIGNS & GRAPHICS', 'tracking': ['600775301465', '600775301473', '600775301481', ], 'id': '17'} The way the code is working now I only get this: {'city': 'AB', 'company': 'CAREYON SIGNS & GRAPHICS', 'tracking': ['600775301465', '600775301465'], 'id': '17'}, and a only the ones that have multiple pin numbers. I'd appreciate your help. Thanks. Eduardo From kb1pkl at aim.com Tue Aug 10 21:49:28 2010 From: kb1pkl at aim.com (Corey Richardson) Date: Tue, 10 Aug 2010 15:49:28 -0400 Subject: [Tutor] Making String Message-ID: <4C61AD48.4020700@aim.com> Hello, tutors. I'm attempting to make a string from the items of a list. For example, if the list is ["3", "2", "5", "1", "0"], I desire the string "32510". I've looked into str.join(), but I can't figure it out. Can someone either point me in a different direction, or explain how join() works? Thank you, ~Corey Richardson From adam.jtm30 at gmail.com Tue Aug 10 21:56:29 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Tue, 10 Aug 2010 20:56:29 +0100 Subject: [Tutor] Lost in the control flow In-Reply-To: References: Message-ID: <4C61AEED.3090808@gmail.com> On 10/08/10 20:39, Eduardo Vieira wrote: > Hello, list! I'm trying to parse a text file. I'm getting confuse with > my strategy, and flags or how to use a sequence of ifs or elifs, > continue, etc. Anyhow, after several experiments this is close to what > I'd like to get, except, I can't find a way to include all the pin > numbers (12 number sequence): > > Here is my code: > http://pastebin.com/1ps6WdF4 > > The example file is this: > http://pastebin.com/1MZmE4d3 > > > Basically, as a initial step, I'd like to transform this: > 17 600775301465 CAREYON SIGNS& GRAPHICS EXP 5 > 93.00 $0.00 $ 26.77 > > RED DEER AB T4N1L2 > FUEL SURCHARGE: 2.10 > > > GST/HST: 1.44 > > > > 600775301465 18.60 > > 600775301473 18.60 > > 600775301481 18.60 > > > into this. View the code and file for details, please: > {'city': 'AB', 'company': 'CAREYON SIGNS& GRAPHICS', 'tracking': > ['600775301465', '600775301473', '600775301481', ], 'id': '17'} > > > The way the code is working now I only get this: > {'city': 'AB', 'company': 'CAREYON SIGNS& GRAPHICS', 'tracking': > ['600775301465', '600775301465'], 'id': '17'}, and a only the ones > that have multiple pin numbers. > > I'd appreciate your help. Thanks. > > Eduardo > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > The problem is you don't call make_dict unless there's a "FUEL SURCHARGE" or multiple pins. Also you don't add the first pin to mydict["tracking"] unless there's a "FUEL SURCHARGE". HTH, Adam. From hugo.yoshi at gmail.com Tue Aug 10 22:02:16 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 10 Aug 2010 15:02:16 -0500 Subject: [Tutor] Making String In-Reply-To: <4C61AD48.4020700@aim.com> References: <4C61AD48.4020700@aim.com> Message-ID: On Tue, Aug 10, 2010 at 2:49 PM, Corey Richardson wrote: > Hello, tutors. > > I'm attempting to make a string from the items of a list. > For example, if the list is ["3", "2", "5", "1", "0"], I desire the string > "32510". > > I've looked into str.join(), but I can't figure it out. Can someone either > point me in a different direction, or explain how join() works? > str.join is the one you want. remember that it's a method of the str class, and it takes an iterable as an argument. Your list is an iterable. Try invoking the method on different kinds of strings with your list as argument, and see if you can figure out how it works. Maybe start like this: >>> l = ["3", "2", "5", "1", "0"] >>> a = "string" >>> a.join(l) HTH, Hugo From joel.goldstick at gmail.com Tue Aug 10 22:09:28 2010 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 10 Aug 2010 16:09:28 -0400 Subject: [Tutor] Making String In-Reply-To: <4C61AD48.4020700@aim.com> References: <4C61AD48.4020700@aim.com> Message-ID: On Tue, Aug 10, 2010 at 3:49 PM, Corey Richardson wrote: > Hello, tutors. > > I'm attempting to make a string from the items of a list. > For example, if the list is ["3", "2", "5", "1", "0"], I desire the string > "32510". > > a = ["3", "2", "5", "1", "0"] my_string = "".join(a) Or, this even works: "".join(["3", "2", "5", "1", "0"]) > I've looked into str.join(), but I can't figure it out. Can someone either > point me in a different direction, or explain how join() works? > The str part of str.join() is the string where the result is stored, so you can start off with an empty string: "" The join argument is listed as an iterable, whis is what your list is. > > Thank you, > ~Corey Richardson > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From kb1pkl at aim.com Tue Aug 10 22:39:53 2010 From: kb1pkl at aim.com (Corey Richardson) Date: Tue, 10 Aug 2010 16:39:53 -0400 Subject: [Tutor] Making String In-Reply-To: References: <4C61AD48.4020700@aim.com> Message-ID: <4C61B919.4050102@aim.com> Joel and Hugo: Thanks a lot! That clears it right up. ~Corey Richardson From steve at pearwood.info Wed Aug 11 00:22:29 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 11 Aug 2010 08:22:29 +1000 Subject: [Tutor] Making String In-Reply-To: References: <4C61AD48.4020700@aim.com> Message-ID: <201008110822.31050.steve@pearwood.info> On Wed, 11 Aug 2010 06:09:28 am Joel Goldstick wrote: > The str part of str.join() is the string where the result is stored, > so you can start off with an empty string: "" I don't understand what you mean by that. I can only imagine you think that the string part is a fixed-width buffer that has the result stored into it, but of course that's ridiculous because that's nothing like what join does. Python strings are immutable so you can't store something inside an existing string, but even if they weren't, since the result of join is usually larger than the initial string you pass, what would be the point? The string part of str.join is the string which is used to join the rest of the arguments. This: "spam".join([ "a", "b", "c" ]) is equivalent to: "a" + "spam" + "b" + "spam" + "c" except more efficient and faster. The result is stored in a new string. -- Steven D'Aprano From sudarshana.b at gmail.com Wed Aug 11 03:34:32 2010 From: sudarshana.b at gmail.com (Sudarshana Banerjee) Date: Tue, 10 Aug 2010 18:34:32 -0700 Subject: [Tutor] elif statement Message-ID: Hi: I am trying to teach myself Python, and am stuck at the indentation with the elif statement. This is what I am trying to type (as copied from the textbook): x=3 if x==0: print "x is 0" elif x&1 ==1: print "x is a odd number" elif x&1==0: -- Line 6 print "x is a even number" If I am combining the if and the print statement, then the elif statement is in the next line, and all is well with the world. If however, I write the print as a separate statement, I am getting a syntax error after I press Enter after keying the first elif statement. >>> x=3 >>> if x==0: print x elif x==2: SyntaxError: invalid syntax Again: >>> x=3 >>> if x==2: print x elif x&1 == 1: print 'x is odd' >>> elif x&1 ==0: print 'x is even' SyntaxError: invalid syntax If I am pressing two Enters, the code executes; so I have a elif without a if, and again, a syntax error. What am I not doing right? Thank you. Sudarshana. -------------- next part -------------- An HTML attachment was scrubbed... URL: From adam.jtm30 at gmail.com Wed Aug 11 04:03:57 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Wed, 11 Aug 2010 03:03:57 +0100 Subject: [Tutor] elif statement In-Reply-To: References: Message-ID: <4C62050D.80307@gmail.com> On 11/08/10 02:34, Sudarshana Banerjee wrote: > Hi: I am trying to teach myself Python, and am stuck at the > indentation with the elif statement. > > This is what I am trying to type (as copied from the textbook): > > x=3 > if x==0: > print "x is 0" > elif x&1 ==1: > print "x is a odd number" > elif x&1==0: -- Line 6 > print "x is a even number" > > If I am combining the if and the print statement, then the elif > statement is in the next line, and all is well with the world. If > however, I write the print as a separate statement, I am getting a > syntax error after I press Enter after keying the first elif statement. > > >>> x=3 > >>> if x==0: > print x > elif x==2: Here you have indented the elif statement but it should be at the same level as the if: >>> x=3 >>> if x==0: ... print x ... elif x==2: ... print "something else" ... >>> > SyntaxError: invalid syntax > > Again: > >>> x=3 > >>> if x==2: print x > elif x&1 == 1: print 'x is odd' > >>> elif x&1 ==0: print 'x is even' > SyntaxError: invalid syntax I'm not sure what's going on here but the second elif is being interpreted separate to the rest of the if statement hence a SyntaxError: >>> elif x&1 == 0: print "x is even" File "", line 1 elif x&1 == 0: print "x is even" ^ SyntaxError: invalid syntax This works: >>> if x==2: print x ... elif x&1 == 1: print 'x is odd' ... elif x&1 ==0: print 'x is even' ... x is odd > > If I am pressing two Enters, the code executes; so I have a elif > without a if, and again, a syntax error. What am I not doing right? > > Thank you. > > Sudarshana. HTH, Adam. -------------- next part -------------- An HTML attachment was scrubbed... URL: From guillaume_chorn at merck.com Wed Aug 11 02:17:23 2010 From: guillaume_chorn at merck.com (Chorn, Guillaume) Date: Tue, 10 Aug 2010 20:17:23 -0400 Subject: [Tutor] Module for browsing Windows? Message-ID: <3149FC764D12D24DA307F9DA7248176401DD9D0A@usctmx1158.merck.com> Hello, I'm pretty new to Python programming and it is my first programming language. I made a script that uses data from two different .csv files to make calculations and then spit the results out in a third .csv file. However, the process of typing in the path to each of the two input files and the output file (or even copying and pasting those paths) is somewhat cumbersome from a UI perspective, and so I was wondering if there is a Python module out there that allows you to browse to and select files using a Windows-style interface. Thanks! Cheers, Guillaume Notice: This e-mail message, together with any attachments, contains information of Merck & Co., Inc. (One Merck Drive, Whitehouse Station, New Jersey, USA 08889), and/or its affiliates Direct contact information for affiliates is available at http://www.merck.com/contact/contacts.html) that may be confidential, proprietary copyrighted and/or legally privileged. It is intended solely for the use of the individual or entity named on this message. If you are not the intended recipient, and have received this message in error, please notify us immediately by reply e-mail and then delete it from your system. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fried.sigmund at gmail.com Wed Aug 11 03:11:51 2010 From: fried.sigmund at gmail.com (rara avis) Date: Tue, 10 Aug 2010 18:11:51 -0700 Subject: [Tutor] Indentation woes in elif statement Message-ID: Hi: I am trying to teach myself Python, and am stuck at the indentation with the elif statement. This is what I am trying to type: x=3 if x==0: -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Wed Aug 11 10:07:29 2010 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 11 Aug 2010 09:07:29 +0100 Subject: [Tutor] Module for browsing Windows? In-Reply-To: <3149FC764D12D24DA307F9DA7248176401DD9D0A@usctmx1158.merck.com> References: <3149FC764D12D24DA307F9DA7248176401DD9D0A@usctmx1158.merck.com> Message-ID: <4C625A41.4020707@timgolden.me.uk> On 11/08/2010 01:17, Chorn, Guillaume wrote: > Hello, > > I'm pretty new to Python programming and it is my first programming > language. I made a script that uses data from two different .csv files > to make calculations and then spit the results out in a third .csv file. > However, the process of typing in the path to each of the two input > files and the output file (or even copying and pasting those paths) is > somewhat cumbersome from a UI perspective, and so I was wondering if > there is a Python module out there that allows you to browse to and > select files using a Windows-style interface. Thanks! Take you pick of any of these: http://wiki.python.org/moin/GuiProgramming Although (to select one) you might find that EasyGui gets you going the quickest: http://easygui.sourceforge.net/ TJG From delegbede at dudupay.com Wed Aug 11 10:22:39 2010 From: delegbede at dudupay.com (Dipo Elegbede) Date: Wed, 11 Aug 2010 09:22:39 +0100 Subject: [Tutor] elif statement In-Reply-To: <4C62050D.80307@gmail.com> References: <4C62050D.80307@gmail.com> Message-ID: You need to check the indentation properly. In this case, elif has to be on the same indentation level with if. I should think so. If you're working straight from the python interactive console, like I think you're doing, you need to manually do the indentation thing by yourself. First, I don't understand why you chose to set x to 3. That is not the main thing though. After x = 3, if you press enter, you'd get the python prompt >>> Then you type the next statement to have >>> if x == 0: What you get after this if statement is either a whitespace or ..., from my phone, I get a ... So you manually press the spacebar twice to get an indentation for the first print statement. As soon as you press enter again, you get the dots, just type in the elif statements without pressing the spacebar. Then press enter to move to a new line where the second print statement would be,and press the spacebar twice again for indentation. For the second elif statement, follow the procedure for the first elif statement. Go ahead and press enter twice to tell the console you are done, you shouldn't get an error that way. You should get something like below: >>> x=3 >>> if x==0: ... print x,'is zero' ... elif x//1==1: ... print x,'is odd' ... elif x//1==0: ... print x,'is even' ... else: ... print'what is this' ... The else statement is optional. Hope it helps. On 8/11/10, Adam Bark wrote: > On 11/08/10 02:34, Sudarshana Banerjee wrote: >> Hi: I am trying to teach myself Python, and am stuck at the >> indentation with the elif statement. >> >> This is what I am trying to type (as copied from the textbook): >> >> x=3 >> if x==0: >> print "x is 0" >> elif x&1 ==1: >> print "x is a odd number" >> elif x&1==0: -- Line 6 >> print "x is a even number" >> >> If I am combining the if and the print statement, then the elif >> statement is in the next line, and all is well with the world. If >> however, I write the print as a separate statement, I am getting a >> syntax error after I press Enter after keying the first elif statement. >> >> >>> x=3 >> >>> if x==0: >> print x >> elif x==2: > > Here you have indented the elif statement but it should be at the same > level as the if: > >>> x=3 > >>> if x==0: > ... print x > ... elif x==2: > ... print "something else" > ... > >>> > > >> SyntaxError: invalid syntax >> >> Again: >> >>> x=3 >> >>> if x==2: print x >> elif x&1 == 1: print 'x is odd' >> >>> elif x&1 ==0: print 'x is even' >> SyntaxError: invalid syntax > > I'm not sure what's going on here but the second elif is being > interpreted separate to the rest of the if statement hence a SyntaxError: > >>> elif x&1 == 0: print "x is even" > File "", line 1 > elif x&1 == 0: print "x is even" > ^ > SyntaxError: invalid syntax > > This works: > >>> if x==2: print x > ... elif x&1 == 1: print 'x is odd' > ... elif x&1 ==0: print 'x is even' > ... > x is odd > > >> >> If I am pressing two Enters, the code executes; so I have a elif >> without a if, and again, a syntax error. What am I not doing right? >> >> Thank you. >> >> Sudarshana. > HTH, > Adam. > > > -- Elegbede Muhammed Oladipupo OCA +2348077682428 +2347042171716 www.dudupay.com Mobile Banking Solutions | Transaction Processing | Enterprise Application Development From rdmoores at gmail.com Wed Aug 11 10:45:01 2010 From: rdmoores at gmail.com (Richard D. Moores) Date: Wed, 11 Aug 2010 01:45:01 -0700 Subject: [Tutor] O'Reilly is offering Learning Python (4th ed.), eBook form for USD 9.99 Message-ID: I already own the PDF, as well as the paperback (1160 pages), but I thought I'd let the list know. See the deal, good for just today, on . The 4th edition covers both Python 2.6 and 3.x. So what does "today" mean? Beats me. O'Reilly's corporate headquarters are in California, but there are also O'Reilly offices in Massachusetts, Japan, China, Taiwan, Germany, and the UK. Dick Moores From andreengels at gmail.com Wed Aug 11 13:43:32 2010 From: andreengels at gmail.com (Andre Engels) Date: Wed, 11 Aug 2010 13:43:32 +0200 Subject: [Tutor] Indentation woes in elif statement In-Reply-To: References: Message-ID: On Wed, Aug 11, 2010 at 3:11 AM, rara avis wrote: > Hi: I am trying to teach myself Python, and am stuck at the indentation with > the elif statement. > This is what I am trying to type: > > x=3 > if x==0: What are you trying to accomplish? What result did you expect to get? What result did you actually get? -- Andr? Engels, andreengels at gmail.com From joel.goldstick at gmail.com Wed Aug 11 13:56:37 2010 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 11 Aug 2010 07:56:37 -0400 Subject: [Tutor] Making String In-Reply-To: <201008110822.31050.steve@pearwood.info> References: <4C61AD48.4020700@aim.com> <201008110822.31050.steve@pearwood.info> Message-ID: On Tue, Aug 10, 2010 at 6:22 PM, Steven D'Aprano wrote: > On Wed, 11 Aug 2010 06:09:28 am Joel Goldstick wrote: > > The str part of str.join() is the string where the result is stored, > > so you can start off with an empty string: "" > > I don't understand what you mean by that. I can only imagine you think > that the string part is a fixed-width buffer that has the result stored > into it, but of course that's ridiculous because that's nothing like > what join does. Python strings are immutable so you can't store > something inside an existing string, but even if they weren't, since > the result of join is usually larger than the initial string you pass, > what would be the point? > > The string part of str.join is the string which is used to join the rest > of the arguments. This: > > "spam".join([ "a", "b", "c" ]) > > is equivalent to: > > "a" + "spam" + "b" + "spam" + "c" > > except more efficient and faster. The result is stored in a new string. > > > > -- > Steven D'Aprano > > Steve, thanks for correcting me. The str being the 'glue' that joins between each of the list members. -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Wed Aug 11 14:13:55 2010 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 11 Aug 2010 08:13:55 -0400 Subject: [Tutor] Indentation woes in elif statement In-Reply-To: References: Message-ID: On Tue, Aug 10, 2010 at 9:11 PM, rara avis wrote: > Hi: I am trying to teach myself Python, and am stuck at the indentation > with the elif statement. > This is what I am trying to type: > > x=3 > if x==0: > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > x = 3 if x == 0: print 'x == 0' elif x != 0: print 'x != 0' x != 0 -- The block of code under 'if x...' is indented. Most people use 4 spaces. You can use any number of spaces, but you need to be consistant The elif indentation must match its matching if statement. In this case neither are indented The block which executes under the elif is indented to the same level as that under the original if Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From bsc26 at yahoo.com Wed Aug 11 15:30:13 2010 From: bsc26 at yahoo.com (Benjamin Castillo) Date: Wed, 11 Aug 2010 06:30:13 -0700 (PDT) Subject: [Tutor] O'Reilly is offering Learning Python (4th ed.), eBook form for USD 9.99 In-Reply-To: Message-ID: <708662.7320.qm@web51406.mail.re2.yahoo.com> The site shows 39.99 for ebook. Ben --- On Wed, 8/11/10, Richard D. Moores wrote: > From: Richard D. Moores > Subject: [Tutor] O'Reilly is offering Learning Python (4th ed.), eBook form for USD 9.99 > To: tutor at python.org > Date: Wednesday, August 11, 2010, 1:45 AM > I already own the PDF, as well as the > paperback (1160 pages), but I > thought I'd let the list know. See the deal, good for just > today, on > . > > The 4th edition covers both Python 2.6 and 3.x. > > So what does "today" mean? Beats me. O'Reilly's corporate > headquarters > are in California, but there are also O'Reilly offices in > Massachusetts, Japan, China, Taiwan, Germany, and the UK. > > > Dick Moores > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From felixsan at gmail.com Wed Aug 11 15:36:51 2010 From: felixsan at gmail.com (Felix Santiago) Date: Wed, 11 Aug 2010 09:36:51 -0400 Subject: [Tutor] O'Reilly is offering Learning Python (4th ed.), eBook form for USD 9.99 In-Reply-To: <708662.7320.qm@web51406.mail.re2.yahoo.com> References: <708662.7320.qm@web51406.mail.re2.yahoo.com> Message-ID: <8CA1AE6A-E9E0-4B48-B025-DE179FCB9D70@gmail.com> On Aug 11, 2010, at 9:30 AM, Benjamin Castillo wrote: > The site shows 39.99 for ebook. > > Ben > > > --- On Wed, 8/11/10, Richard D. Moores wrote: > >> From: Richard D. Moores >> Subject: [Tutor] O'Reilly is offering Learning Python (4th ed.), >> eBook form for USD 9.99 >> To: tutor at python.org >> Date: Wednesday, August 11, 2010, 1:45 AM >> I already own the PDF, as well as the >> paperback (1160 pages), but I >> thought I'd let the list know. See the deal, good for just >> today, on >> . >> >> The 4th edition covers both Python 2.6 and 3.x. >> >> So what does "today" mean? Beats me. O'Reilly's corporate >> headquarters >> are in California, but there are also O'Reilly offices in >> Massachusetts, Japan, China, Taiwan, Germany, and the UK. >> >> >> Dick Moores >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> If you go to http://oreilly.com/store/ddbst.html you can see the discounted price. --Felix From augdawg09 at gmail.com Wed Aug 11 15:45:30 2010 From: augdawg09 at gmail.com (aug dawg) Date: Wed, 11 Aug 2010 09:45:30 -0400 Subject: [Tutor] Scripting Blender Message-ID: Are there any Python modules to script Blender? For example, placing predefined objects into a new Blender project to create a 3D model. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From webtourist at gmail.com Wed Aug 11 16:17:03 2010 From: webtourist at gmail.com (Robert) Date: Wed, 11 Aug 2010 10:17:03 -0400 Subject: [Tutor] O'Reilly is offering Learning Python (4th ed.), eBook form for USD 9.99 In-Reply-To: References: Message-ID: Rather depressing to see what's generally considered "Bible on Python" among those other boring, nondescript books. From tnannie at strdetail.com Wed Aug 11 15:58:33 2010 From: tnannie at strdetail.com (Todd Nannie) Date: Wed, 11 Aug 2010 08:58:33 -0500 Subject: [Tutor] [SPAM]Re: O'Reilly is offering Learning Python (4th ed.), eBook form for USD 9.99 In-Reply-To: <708662.7320.qm@web51406.mail.re2.yahoo.com> References: <708662.7320.qm@web51406.mail.re2.yahoo.com> Message-ID: <00b001cb395d$49be2150$dd3a63f0$@com> If you click on the ONE DAY DEAL on the front page it still list the Python book and several others. I just bought the python book for 9.99 Todd -----Original Message----- From: tutor-bounces+tnannie=strdetail.com at python.org [mailto:tutor-bounces+tnannie=strdetail.com at python.org] On Behalf Of Benjamin Castillo Sent: Wednesday, August 11, 2010 8:30 AM To: tutor at python.org; Richard D. Moores Subject: [SPAM]Re: [Tutor] O'Reilly is offering Learning Python (4th ed.),eBook form for USD 9.99 The site shows 39.99 for ebook. Ben --- On Wed, 8/11/10, Richard D. Moores wrote: > From: Richard D. Moores > Subject: [Tutor] O'Reilly is offering Learning Python (4th ed.), eBook form for USD 9.99 > To: tutor at python.org > Date: Wednesday, August 11, 2010, 1:45 AM > I already own the PDF, as well as the > paperback (1160 pages), but I > thought I'd let the list know. See the deal, good for just > today, on > . > > The 4th edition covers both Python 2.6 and 3.x. > > So what does "today" mean? Beats me. O'Reilly's corporate > headquarters > are in California, but there are also O'Reilly offices in > Massachusetts, Japan, China, Taiwan, Germany, and the UK. > > > Dick Moores > _______________________________________________ > Tutor maillist? -? Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor No virus found in this incoming message. Checked by AVG - www.avg.com Version: 9.0.851 / Virus Database: 271.1.1/3060 - Release Date: 08/11/10 01:34:00 From kb1pkl at aim.com Wed Aug 11 16:44:51 2010 From: kb1pkl at aim.com (Corey Richardson) Date: Wed, 11 Aug 2010 10:44:51 -0400 Subject: [Tutor] Scripting Blender In-Reply-To: References: Message-ID: <4C62B763.6030902@aim.com> Yes. It's called the Python API, it comes with Blender ;) bpy and Blender are the top modules. There are submodules for everything. The reference is here: http://www.blender.org/documentation/249PythonDoc/index.html HTH, ~Corey Richardson aug dawg wrote: > Are there any Python modules to script Blender? For example, placing > predefined objects into a new Blender project to create a 3D model. > > Thanks! > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From waynejwerner at gmail.com Wed Aug 11 16:57:58 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 11 Aug 2010 09:57:58 -0500 Subject: [Tutor] Module for browsing Windows? In-Reply-To: <3149FC764D12D24DA307F9DA7248176401DD9D0A@usctmx1158.merck.com> References: <3149FC764D12D24DA307F9DA7248176401DD9D0A@usctmx1158.merck.com> Message-ID: On Tue, Aug 10, 2010 at 7:17 PM, Chorn, Guillaume wrote: > Hello, > > I'm pretty new to Python programming and it is my first programming > language. I made a script that uses data from two different .csv files to > make calculations and then spit the results out in a third .csv file. > However, the process of typing in the path to each of the two input files > and the output file (or even copying and pasting those paths) is somewhat > cumbersome from a UI perspective, and so I was wondering if there is a > Python module out there that allows you to browse to and select files using > a Windows-style interface. Thanks! > Tkinter is pretty easy: import Tkinter as tk import tkFileDialog as fd root = tk.Tk() root.widthdraw() csv1 = fd.askopenfilename() csv2 = fd.askopenfilename() # Do the rest of your stuff here. HTH! -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From pkoek11 at xs4all.nl Wed Aug 11 17:48:52 2010 From: pkoek11 at xs4all.nl (Pete) Date: Wed, 11 Aug 2010 11:48:52 -0400 Subject: [Tutor] import errors Message-ID: <5CAFA1C0-4356-4C8F-BA60-7A26E03D61D2@xs4all.nl> Hi, A common line I've seen in Python code I come across is: #!/usr/bin/python import os import sys import errors I was wondering about the line that says, "import errors". I understand what it's for, but what I don't get is how Python knows which 'errors.py' to import. On my laptop: macbook:bin han$ locate errors.py | grep -E 'py$' /Library/Frameworks/Mono.framework/Versions/2.4.2.1/lib/IPCE/Lib/_codecs_errors.py /Library/Frameworks/Mono.framework/Versions/2.4.2.1/lib/IPCE/Lib/fepy/codecs_errors.py /Library/Python/2.6/site-packages/Skype4Py/errors.py /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/distutils/errors.py /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-mac/macerrors.py /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/distutils/errors.py /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/email/errors.py /System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac/macerrors.py /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/distutils/errors.py /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/email/errors.py /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/macerrors.py ... so there seem to be more than one 'errors.py' - one for the email module, one for Skype4Py, etc. How does the interpreter know which one to import? Thanks for all your time, btw - I'm learning a lot lurking on this list and greatly appreciate all the people offering help and advice. cheers, Pete From smokefloat at gmail.com Wed Aug 11 18:06:24 2010 From: smokefloat at gmail.com (David Hutto) Date: Wed, 11 Aug 2010 12:06:24 -0400 Subject: [Tutor] [SPAM]Re: O'Reilly is offering Learning Python (4th ed.), eBook form for USD 9.99 In-Reply-To: <00b001cb395d$49be2150$dd3a63f0$@com> References: <708662.7320.qm@web51406.mail.re2.yahoo.com> <00b001cb395d$49be2150$dd3a63f0$@com> Message-ID: I thought the open source mentality of python was it own 'perpetual bible'. A building of disciples so to speak. From emile at fenx.com Wed Aug 11 18:06:19 2010 From: emile at fenx.com (Emile van Sebille) Date: Wed, 11 Aug 2010 09:06:19 -0700 Subject: [Tutor] import errors In-Reply-To: <5CAFA1C0-4356-4C8F-BA60-7A26E03D61D2@xs4all.nl> References: <5CAFA1C0-4356-4C8F-BA60-7A26E03D61D2@xs4all.nl> Message-ID: On 8/11/2010 8:48 AM Pete said... > Hi, > > A common line I've seen in Python code I come across is: > > #!/usr/bin/python > import os > import sys > import errors > ... so there seem to be more than one 'errors.py' - one for the email module, one for Skype4Py, etc. > > How does the interpreter know which one to import? Importing looks in directories in sequence as held in sys.path Python 2.4.3 (#1, Sep 3 2009, 15:37:12) [GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> for ii in sys.path: ii ... '' '/usr/lib/python24.zip' '/usr/lib/python2.4' '/usr/lib/python2.4/plat-linux2' '/usr/lib/python2.4/lib-tk' '/usr/lib/python2.4/lib-dynload' '/usr/lib/python2.4/site-packages' '/usr/lib/python2.4/site-packages/Numeric' '/usr/lib/python2.4/site-packages/gtk-2.0' HTH, Emile From joel.goldstick at gmail.com Wed Aug 11 18:35:37 2010 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 11 Aug 2010 12:35:37 -0400 Subject: [Tutor] import errors In-Reply-To: References: <5CAFA1C0-4356-4C8F-BA60-7A26E03D61D2@xs4all.nl> Message-ID: On Wed, Aug 11, 2010 at 12:06 PM, Emile van Sebille wrote: > On 8/11/2010 8:48 AM Pete said... > > Hi, >> >> A common line I've seen in Python code I come across is: >> >> #!/usr/bin/python >> import os >> import sys >> import errors >> > > > ... so there seem to be more than one 'errors.py' - one for the email >> module, one for Skype4Py, etc. >> >> How does the interpreter know which one to import? >> > > Importing looks in directories in sequence as held in sys.path > > Python 2.4.3 (#1, Sep 3 2009, 15:37:12) > [GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import sys > >>> for ii in sys.path: ii > ... > '' > '/usr/lib/python24.zip' > '/usr/lib/python2.4' > '/usr/lib/python2.4/plat-linux2' > '/usr/lib/python2.4/lib-tk' > '/usr/lib/python2.4/lib-dynload' > '/usr/lib/python2.4/site-packages' > '/usr/lib/python2.4/site-packages/Numeric' > '/usr/lib/python2.4/site-packages/gtk-2.0' > > > HTH, > > Emile > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > To import the errors module which handles email do this: import email.errors There is no top level errors module, but several 'packages' contain error modules. A package is a directory which can contain several modules in its subdirectories -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From karim.liateni at free.fr Wed Aug 11 18:59:05 2010 From: karim.liateni at free.fr (Karim) Date: Wed, 11 Aug 2010 18:59:05 +0200 Subject: [Tutor] elif statement In-Reply-To: References: Message-ID: <4C62D6D9.8030503@free.fr> Hello, This code works for me: >>> x=3 >>> if x==0: ... print "x is 0" ... elif x&1 ==1: ... print "x is a odd number" ... elif x&1==0: ... print "x is a even number" ... x is a odd number So I think you copied by error the string '-- Line 6' in you example given that has nothing to do with the rest of the code. Regards Karim On 08/11/2010 03:34 AM, Sudarshana Banerjee wrote: > print "x is a even number" From marky1991 at gmail.com Wed Aug 11 19:11:38 2010 From: marky1991 at gmail.com (Mark Young) Date: Wed, 11 Aug 2010 13:11:38 -0400 Subject: [Tutor] Scripting Blender In-Reply-To: <4C62B763.6030902@aim.com> References: <4C62B763.6030902@aim.com> Message-ID: 2010/8/11 Corey Richardson > Yes. It's called the Python API, it comes with Blender ;) bpy and Blender > are the top modules. There are submodules for everything. The reference is > here: http://www.blender.org/documentation/249PythonDoc/index.html > > HTH, > ~Corey Richardson > > aug dawg wrote: > >> Are there any Python modules to script Blender? For example, placing >> predefined objects into a new Blender project to create a 3D model. >> >> Thanks! >> >> ------------------------------------------------------------------------ >> >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Questions about coding in blender will likely be answered better at http://blenderartists.org/forum/ . Also, the previously mentioned docs are outdated, documenting blender 2.4x, which is supposed to become obsolete sometime soon. Blender 2.5x is pretty different from 2.4x, so those docs won't help too much. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eduardo.susan at gmail.com Wed Aug 11 19:14:15 2010 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Wed, 11 Aug 2010 11:14:15 -0600 Subject: [Tutor] Lost in the control flow In-Reply-To: <4C61AEED.3090808@gmail.com> References: <4C61AEED.3090808@gmail.com> Message-ID: On Tue, Aug 10, 2010 at 1:56 PM, Adam Bark wrote: > > The problem is you don't call make_dict unless there's a "FUEL SURCHARGE" or > multiple pins. Also you don't add the first pin to mydict["tracking"] unless > there's a "FUEL SURCHARGE". > > HTH, > Adam. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Hi, I made these changes, got rid of the functions, and changed some logic: here is the link: http://pastebin.com/F19vKUjr Now mydict will be changing, of course with every loop, as the output below: {'company': 'CITY SIGNS', 'tracking': ['600775301143'], 'id': '1'} {'city': 'MEDICINE HAT', 'company': 'CITY SIGNS', 'tracking': ['600775301143'], 'id': '1', 'prov': 'AB'} {'city': 'MEDICINE HAT', 'company': 'TRIMLINE', 'tracking': ['600775301150'], 'id': '2', 'prov': 'AB'} {'city': 'ROCKY MOUNTAIN HOUSE', 'company': 'TRIMLINE', 'tracking': ['600775301150'], 'id': '2', 'prov': 'AB'} {'city': 'ROCKY MOUNTAIN HOUSE', 'company': 'TS SIGNS PRINTING & PROMO', 'tracking': ['600775301168'], 'id': '3', 'prov': 'AB'} {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', 'tracking': ['600775301168'], 'id': '3', 'prov': 'AB'} {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', 'tracking': ['600775301168', '600775301168'], 'id': '3', 'prov': 'AB'} {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', 'tracking': ['600775301168', '600775301168', '600775301176'], 'id': '3', 'prov': 'AB'} {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', 'tracking': ['600775301168', '600775301168', '600775301176', '600775301184'], 'id': '3', 'prov': 'AB'} {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', 'tracking': ['600775301168', '600775301168', '600775301176', '600775301184', '600775301192'], 'id': '3', 'prov': 'AB'} {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', 'tracking': ['600775301168', '600775301168', '600775301176', '600775301184', '600775301192', '600775301200'], 'id': '3', 'prov': 'AB'} so I appended everything to a bigdata list and used it to update the dictionary data_dict I can't understand why I get only one value: {'18': {'city': 'ESTEVAN', 'company': 'BRAKE & DRIVE SYSTEMS', 'id': '18', 'prov': 'SK', 'tracking': ['600775301515', '600775301515', '600775301523']}} Regards, Eduardo From karim.liateni at free.fr Wed Aug 11 19:51:54 2010 From: karim.liateni at free.fr (Karim) Date: Wed, 11 Aug 2010 19:51:54 +0200 Subject: [Tutor] Executing Python from TCL Message-ID: <4C62E33A.7090109@free.fr> Hello Tutors, I want to know if there are modules or whatever to execute python functions inside TCL. These functions should returns python lists as TCL lists and Python dictionary as TCL Hash tables. Existing (opensource) tools, packages are welcome! I want to avoid to do it myself (anyway I don't have any idea how to do it :o) ) In fact, I develop parser for xml using xml.etree.ElementTree and another team which develop in TCL need to access it via an API I should do. Great Challenge. Regards Karim From laurens at daemon.be Wed Aug 11 23:04:15 2010 From: laurens at daemon.be (Laurens Vets) Date: Wed, 11 Aug 2010 23:04:15 +0200 Subject: [Tutor] Need help understanding output... Message-ID: <4C63104F.70104@daemon.be> Hello list, I'm learning Python and I'm currently facing an issue with a small script I'm writing. I need to generate a list of 30 numbers randomly chosen from 1, 2, 3, 4, 5 & 6. However, I cannot have more than 2 numbers which are the same next to each other. I came up with the following (Please ignore the fact that I'm trying to avoid an IndexError in a stupid way :)): import random reeks = [] while len(reeks) <= 1: number = random.randrange(1, 7, 1) reeks.append(number) while len(reeks) <= 29: nummer = random.randrange(1, 7, 1) if nummer != reeks[-1] and nummer != reeks[-2]: reeks.append(nummer) print reeks So far so good (I think). From what I can see from the output, I get 30 numbers, without more than 2 being the same next to each other. However, I wanted to look deeper in the above script and I created the following: import random iteraties = 5 cijferreeks = 6 aantal_cijfers = iteraties * cijferreeks reeks = [] while len(reeks) <= 1: nummer = random.randrange(1, cijferreeks + 1, 1) print 'Nummer: ', nummer print 'Reeks: ', reeks reeks.append(nummer) print '\n' while len(reeks) <= aantal_cijfers: nummer = random.randrange(1, cijferreeks + 1, 1) print 'Nummer: ', nummer print 'Voorlaatste vd reeks (-2): ', reeks[-2] print 'Laatste vd reeks (-1): ', reeks[-1] print 'Reeks: ', reeks if nummer != reeks[-1] and nummer != reeks[-2]: reeks.append(nummer) else: print 'Nummer: ', nummer, 'is gelijk aan vorige 2 nummers: ', reeks[-1], '&', reeks[-2], '!' print '\n' print reeks When I run that, I can see there's something wrong with my if statement, it triggers the else condition even when the 2 previous numbers in my list are not the same... I'm not sure what is happening here... From evert.rol at gmail.com Wed Aug 11 23:53:16 2010 From: evert.rol at gmail.com (Evert Rol) Date: Wed, 11 Aug 2010 23:53:16 +0200 Subject: [Tutor] Need help understanding output... In-Reply-To: <4C63104F.70104@daemon.be> References: <4C63104F.70104@daemon.be> Message-ID: > I'm learning Python and I'm currently facing an issue with a small script I'm writing. > > I need to generate a list of 30 numbers randomly chosen from 1, 2, 3, 4, 5 & 6. However, I cannot have more than 2 numbers which are the same next to each other. I came up with the following (Please ignore the fact that I'm trying to avoid an IndexError in a stupid way :)): Ok, we'll ignore that (for now ;-D). > However, I wanted to look deeper in the above script and I created the following: > > import random > iteraties = 5 > cijferreeks = 6 > aantal_cijfers = iteraties * cijferreeks > reeks = [] > while len(reeks) <= 1: > nummer = random.randrange(1, cijferreeks + 1, 1) > print 'Nummer: ', nummer > print 'Reeks: ', reeks > reeks.append(nummer) > print '\n' > > while len(reeks) <= aantal_cijfers: > nummer = random.randrange(1, cijferreeks + 1, 1) > print 'Nummer: ', nummer > print 'Voorlaatste vd reeks (-2): ', reeks[-2] > print 'Laatste vd reeks (-1): ', reeks[-1] > print 'Reeks: ', reeks > if nummer != reeks[-1] and nummer != reeks[-2]: > reeks.append(nummer) > else: > print 'Nummer: ', nummer, 'is gelijk aan vorige 2 nummers: ', reeks[-1], '&', reeks[-2], '!' > print '\n' > print reeks > > When I run that, I can see there's something wrong with my if statement, it triggers the else condition even when the 2 previous numbers in my list are not the same... I'm not sure what is happening here... For an 'and' in a condition, only one part of the condition needs to be False for the condition to fail and skip to the else clause. Eg, with nummer=1, reeks[-1]=1 and reeks[-2]=2, it finds that 1 != 1 is False, and immediately skips to the else part. Ditto if nummer=2 and same reeks: first part is then True, but second part False, hence skip to else. I leave it up to you to find the correct if statement. (Hint: it's phrased in your third sentence at the top.) Btw, tip: always code in English. It just makes things easier for yourself when using other code examples, for example. But I just find generally good practice. Cheers, Evert From emile at fenx.com Thu Aug 12 00:02:15 2010 From: emile at fenx.com (Emile van Sebille) Date: Wed, 11 Aug 2010 15:02:15 -0700 Subject: [Tutor] Need help understanding output... In-Reply-To: <4C63104F.70104@daemon.be> References: <4C63104F.70104@daemon.be> Message-ID: On 8/11/2010 2:04 PM Laurens Vets said... > Hello list, > > I'm learning Python and I'm currently facing an issue with a small > script I'm writing. > > I need to generate a list of 30 numbers randomly chosen from 1, 2, 3, 4, > 5 & 6. However, I cannot have more than 2 numbers which are the same > next to each other. I came up with the following (Please ignore the fact > that I'm trying to avoid an IndexError in a stupid way :)): > > import random > reeks = [] > while len(reeks) <= 1: > number = random.randrange(1, 7, 1) > reeks.append(number) > > while len(reeks) <= 29: > nummer = random.randrange(1, 7, 1) > if nummer != reeks[-1] and nummer != reeks[-2]: > reeks.append(nummer) > print reeks > > So far so good (I think). From what I can see from the output, I get 30 > numbers, without more than 2 being the same next to each other. > > However, I wanted to look deeper in the above script and I created the > following: > > import random > iteraties = 5 > cijferreeks = 6 > aantal_cijfers = iteraties * cijferreeks > reeks = [] > while len(reeks) <= 1: > nummer = random.randrange(1, cijferreeks + 1, 1) > print 'Nummer: ', nummer > print 'Reeks: ', reeks > reeks.append(nummer) > print '\n' > > while len(reeks) <= aantal_cijfers: > nummer = random.randrange(1, cijferreeks + 1, 1) > print 'Nummer: ', nummer > print 'Voorlaatste vd reeks (-2): ', reeks[-2] > print 'Laatste vd reeks (-1): ', reeks[-1] > print 'Reeks: ', reeks > if nummer != reeks[-1] and nummer != reeks[-2]: You're testing here if nummer is niet gelijk van _both_ vorige twee nummers, maar je wil testen als het niet gelijk is van _either_ nummer: if nummer != reeks[-1] _or_ nummer != reeks[-2]: For then it is true that nummer == reeks[-1] and nummer == reeks[-2] You should review/create or/and truth tables to determine the validity of your logical tests. Also, particularly when starting, it is known that negatives often lead to confusion, with use of multiple negatives leading to even more confusion. Next time, try eliminating the negatives and look for a positive test when you have this kind of issue. Then you might have written: if nummer == reeks[-1] and nummer == reeks[-2]: print "it's the same as the prior two" else: reeks.append(nummer) HTH, Emile > reeks.append(nummer) > else: > print 'Nummer: ', nummer, 'is gelijk aan vorige 2 nummers: ', reeks[-1], > '&', reeks[-2], '!' > print '\n' > print reeks > > When I run that, I can see there's something wrong with my if statement, > it triggers the else condition even when the 2 previous numbers in my > list are not the same... I'm not sure what is happening here... > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From steve at pearwood.info Thu Aug 12 01:26:48 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 12 Aug 2010 09:26:48 +1000 Subject: [Tutor] Need help understanding output... In-Reply-To: <4C63104F.70104@daemon.be> References: <4C63104F.70104@daemon.be> Message-ID: <201008120926.49330.steve@pearwood.info> On Thu, 12 Aug 2010 07:04:15 am Laurens Vets wrote: > I need to generate a list of 30 numbers randomly chosen from 1, 2, 3, > 4, 5 & 6. However, I cannot have more than 2 numbers which are the > same next to each other. I came up with the following (Please ignore > the fact that I'm trying to avoid an IndexError in a stupid way :)): I can't possible do that! :) > import random > reeks = [] > while len(reeks) <= 1: > number = random.randrange(1, 7, 1) > reeks.append(number) > > while len(reeks) <= 29: > nummer = random.randrange(1, 7, 1) > if nummer != reeks[-1] and nummer != reeks[-2]: > reeks.append(nummer) > print reeks This is probably a simpler way: import random reeks = [] for i in range(30): temp = [random.randint(1, 6)] while reeks[-2:-1] == reeks[-1:] == temp: # print "Triplet found:", reeks, temp temp = [random.randint(1, 6)] reeks.extend(temp) print reeks Note that you can avoid dealing with IndexError by extracting slices and comparing lists. > However, I wanted to look deeper in the above script and I created > the following: [...] > if nummer != reeks[-1] and nummer != reeks[-2]: > reeks.append(nummer) > else: > print 'Nummer: ', nummer, 'is gelijk aan vorige 2 nummers: ', > reeks[-1], '&', reeks[-2], '!' > print '\n' > print reeks > > When I run that, I can see there's something wrong with my if > statement, it triggers the else condition even when the 2 previous > numbers in my list are not the same... I'm not sure what is > happening here... nummer != reeks[-1] and nummer != reeks[-2] gives a true result if all three numbers are different, otherwise it gives a false result. Negative conditions are often hard to reason with. It might be better to write that as: nummer == reeks[-1] and nummer == reeks[-2] and swap the if/else clauses. But even better is to use Python's chained comparisons, and write: nummer == reeks[-1] == reeks[-2] -- Steven D'Aprano From wallenpb at gmail.com Thu Aug 12 01:41:58 2010 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 11 Aug 2010 18:41:58 -0500 Subject: [Tutor] problem loading and array from an external file In-Reply-To: <4C61693E.1010103@gmail.com> References: <4C60C2B4.5000007@gmail.com> <4C615267.9080306@gmail.com> <4C61693E.1010103@gmail.com> Message-ID: On Tue, Aug 10, 2010 at 9:59 AM, bob gailer wrote: > On 8/10/2010 10:42 AM, Bill Allen wrote: >> >> Bob, >> >> I was really off on that algorithm and had way over complicated it. >> I have it working correctly now, but for the sake of those who saw my >> earlier really botched code, here is the resultant code that works. >> The entire inner loop and intermediate variables are removed, but >> shown commented out. ?I had somehow thought I needed to read each >> member of each subarray in individually. ?That was not the case and >> that inner loop was overwriting the array. >> >> # reads one line at a time from file and puts data into array >> ? ? for line in textf: >> ? ? ? ? #tempwords = line.split(None) >> ? ? ? ? #for n in range(0, len(room)-1): >> ? ? ? ? # ? ?roomx[n] = tempwords[n] >> ? ? ? ? #room[m] = roomx >> ? ? ? ? room[m] = line.split(None) >> ? ? ? ? m += 1 >> >> > > Great. Good work. Teach a man to fish? > > Now for the refinements. First you can use enumerate to obtain the room > index: > > ? ?for m, line in enumerate(textf): > ? ? ? ?room[m] = line.split(None) > > > Second you can start with an empty list and append: > > ? ?rooms = [] > ? ?for line in textf: > ? ? ? ?rooms.append(line.split(None)) > > Third you can use list comprehension: > > ? ?rooms = [line.split(None) for line in textf] > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > Bob, Great pointer! I had not gotten back on the email until just now. I figured out the second method today on my own. That third method is fascinating. I have not heard of "list comprehension" before. That must be unique Python lingo. What is the principle behind that? Thanks for the help. Bill From wallenpb at gmail.com Thu Aug 12 01:46:41 2010 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 11 Aug 2010 18:46:41 -0500 Subject: [Tutor] problem loading and array from an external file In-Reply-To: References: <4C60C2B4.5000007@gmail.com> <4C615267.9080306@gmail.com> <4C61693E.1010103@gmail.com> Message-ID: On Tue, Aug 10, 2010 at 11:11 AM, Hugo Arts wrote: > On Tue, Aug 10, 2010 at 9:59 AM, bob gailer wrote: >> On 8/10/2010 10:42 AM, Bill Allen wrote: >>> >>> Bob, >>> >>> I was really off on that algorithm and had way over complicated it. >>> I have it working correctly now, but for the sake of those who saw my >>> earlier really botched code, here is the resultant code that works. >>> The entire inner loop and intermediate variables are removed, but >>> shown commented out. ?I had somehow thought I needed to read each >>> member of each subarray in individually. ?That was not the case and >>> that inner loop was overwriting the array. >>> >>> # reads one line at a time from file and puts data into array >>> ? ? for line in textf: >>> ? ? ? ? #tempwords = line.split(None) >>> ? ? ? ? #for n in range(0, len(room)-1): >>> ? ? ? ? # ? ?roomx[n] = tempwords[n] >>> ? ? ? ? #room[m] = roomx >>> ? ? ? ? room[m] = line.split(None) >>> ? ? ? ? m += 1 >>> >>> >> >> Great. Good work. Teach a man to fish? >> >> Now for the refinements. First you can use enumerate to obtain the room >> index: >> >> ? ?for m, line in enumerate(textf): >> ? ? ? ?room[m] = line.split(None) >> >> >> Second you can start with an empty list and append: >> >> ? ?rooms = [] >> ? ?for line in textf: >> ? ? ? ?rooms.append(line.split(None)) >> >> Third you can use list comprehension: >> >> ? ?rooms = [line.split(None) for line in textf] >> > > Nice going, this is the best way of getting your answer from the > tutors list IMO, high fives all around. I wish more threads went like > this. > > You don't actually have to specify the None in line.split AFAIK, but > it might be better to be explicit. thoughts on this, anyone? > > Hugo > Hugo, I had wondered about the use of None in that context. I had seen it used that way in some examples and just followed suit. Just do line.split() ? Bill From missive at hotmail.com Thu Aug 12 01:55:57 2010 From: missive at hotmail.com (Lee Harr) Date: Thu, 12 Aug 2010 04:25:57 +0430 Subject: [Tutor] Scripting Blender Message-ID: > Are there any Python modules to script Blender? For example, placing > predefined objects into a new Blender project to create a 3D model. If you are using 2.5, I saw this posted on blendernation.com just today: http://blenderartists.org/forum/showthread.php?t=193908 From alan.gauld at btinternet.com Thu Aug 12 01:59:39 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Aug 2010 00:59:39 +0100 Subject: [Tutor] problem loading and array from an external file References: <4C60C2B4.5000007@gmail.com><4C615267.9080306@gmail.com><4C61693E.1010103@gmail.com> Message-ID: "Bill Allen" wrote > second method today on my own. That third method is fascinating. I > have not heard of "list comprehension" before. That must be unique > Python lingo. What is the principle behind that? Its not unique to Python, Haskell had it first. It is based on mathematical set notation, you can define a set of numbers using a (somewhat) similar construct. You will find a basic description in the Functional Programming topic of my tutorial. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Aug 12 02:02:16 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Aug 2010 01:02:16 +0100 Subject: [Tutor] Module for browsing Windows? References: <3149FC764D12D24DA307F9DA7248176401DD9D0A@usctmx1158.merck.com> Message-ID: "Chorn, Guillaume" wrote > there is a Python module out there that allows you to browse to and > select files using a Windows-style interface. Thanks! EasyGUI is designed for exactly that kind of mixed mode programming. You can find a basic intro in the Talking to the User topic of my tutorial. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Aug 12 02:13:20 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Aug 2010 01:13:20 +0100 Subject: [Tutor] Executing Python from TCL References: <4C62E33A.7090109@free.fr> Message-ID: "Karim" wrote > I want to know if there are modules or whatever to execute > python functions inside TCL. Not that I know of, unless Google tells you something different. You can of course call Python programs from Tcl and vice-versa. If you use the Java versions of both you might succeed. Or you could wrap your parser as a separate server process and expose it as a Web service or XML RPC... But given the wealth of xml parsers available for Tcl I'm surprised that they need yours... > These functions should returns python lists as TCL lists and > Python dictionary as TCL Hash tables. You could probably do some C level integration using Boost or SWIG or somesuch but I doubt the benefit would be worth it. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Aug 12 02:23:24 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Aug 2010 01:23:24 +0100 Subject: [Tutor] Need help understanding output... References: <4C63104F.70104@daemon.be> Message-ID: "Laurens Vets" wrote > next to each other. I came up with the following (Please ignore the > fact that I'm trying to avoid an IndexError in a stupid way :)): Others have answered your question. I'll suggest that instead of using indexes its easier to just cache the last two values in variables - back1 and back2 say. initialise them to values outside the range for the first two values then the loop body becomes (in pseudo code) x = random number if x == back1 == back2: # a triple print 'error' else back2,back1 = back1,x append(x) HTH, Alan G. From wallenpb at gmail.com Thu Aug 12 02:36:57 2010 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 11 Aug 2010 19:36:57 -0500 Subject: [Tutor] problem loading and array from an external file In-Reply-To: References: <4C60C2B4.5000007@gmail.com> <4C615267.9080306@gmail.com> <4C61693E.1010103@gmail.com> Message-ID: On Wed, Aug 11, 2010 at 6:59 PM, Alan Gauld wrote: > > > You will find a basic description in the Functional Programming > topic of my tutorial. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > Alan, Awesome website! Thanks! I have a buddy that is also working on learning Python with me, I will definitely point him there. Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From rabidpoobear at gmail.com Thu Aug 12 05:09:49 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Wed, 11 Aug 2010 22:09:49 -0500 Subject: [Tutor] problem loading and array from an external file In-Reply-To: References: <4C60C2B4.5000007@gmail.com> <4C615267.9080306@gmail.com> <4C61693E.1010103@gmail.com> Message-ID: <8C0B4854-E2FF-4BBF-9FA8-AA5C823598E4@gmail.com> Don't pass none. It's an optional parameter. It's accepted practice to not pass optional parameters. Sent from my iPhone On Aug 11, 2010, at 6:46 PM, Bill Allen wrote: > On Tue, Aug 10, 2010 at 11:11 AM, Hugo Arts wrote: >> On Tue, Aug 10, 2010 at 9:59 AM, bob gailer wrote: >>> On 8/10/2010 10:42 AM, Bill Allen wrote: >>>> >>>> Bob, >>>> >>>> I was really off on that algorithm and had way over complicated it. >>>> I have it working correctly now, but for the sake of those who saw my >>>> earlier really botched code, here is the resultant code that works. >>>> The entire inner loop and intermediate variables are removed, but >>>> shown commented out. I had somehow thought I needed to read each >>>> member of each subarray in individually. That was not the case and >>>> that inner loop was overwriting the array. >>>> >>>> # reads one line at a time from file and puts data into array >>>> for line in textf: >>>> #tempwords = line.split(None) >>>> #for n in range(0, len(room)-1): >>>> # roomx[n] = tempwords[n] >>>> #room[m] = roomx >>>> room[m] = line.split(None) >>>> m += 1 >>>> >>>> >>> >>> Great. Good work. Teach a man to fish? >>> >>> Now for the refinements. First you can use enumerate to obtain the room >>> index: >>> >>> for m, line in enumerate(textf): >>> room[m] = line.split(None) >>> >>> >>> Second you can start with an empty list and append: >>> >>> rooms = [] >>> for line in textf: >>> rooms.append(line.split(None)) >>> >>> Third you can use list comprehension: >>> >>> rooms = [line.split(None) for line in textf] >>> >> >> Nice going, this is the best way of getting your answer from the >> tutors list IMO, high fives all around. I wish more threads went like >> this. >> >> You don't actually have to specify the None in line.split AFAIK, but >> it might be better to be explicit. thoughts on this, anyone? >> >> Hugo >> > > Hugo, > > I had wondered about the use of None in that context. I had seen it > used that way in some examples and just followed suit. Just do > line.split() ? > > Bill > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From wallenpb at gmail.com Thu Aug 12 05:23:25 2010 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 11 Aug 2010 22:23:25 -0500 Subject: [Tutor] problem loading and array from an external file In-Reply-To: <8C0B4854-E2FF-4BBF-9FA8-AA5C823598E4@gmail.com> References: <4C60C2B4.5000007@gmail.com> <4C615267.9080306@gmail.com> <4C61693E.1010103@gmail.com> <8C0B4854-E2FF-4BBF-9FA8-AA5C823598E4@gmail.com> Message-ID: On Wed, Aug 11, 2010 at 10:09 PM, Luke Paireepinart wrote: > Don't pass none. It's an optional parameter. It's accepted practice to not > pass optional parameters. > > Sent from my iPhone > > On Aug 11, 2010, at 6:46 PM, Bill Allen wrote: > > >> > >> You don't actually have to specify the None in line.split AFAIK, but > >> it might be better to be explicit. thoughts on this, anyone? > >> > >> Hugo > >> > > > > Hugo, > > > > I had wondered about the use of None in that context. I had seen it > > used that way in some examples and just followed suit. Just do > > line.split() ? > > > > Bill > > Luke, Thanks for the confirmation on not passing None. Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Thu Aug 12 05:42:17 2010 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 11 Aug 2010 22:42:17 -0500 Subject: [Tutor] a graceful program exit Message-ID: I have only learned a couple of ways to cause a Python program to exit: sys.exit(0) & raise.SystemExit . I am using this in a try/except block. Which is preferred? Are there other, better ways? Thanks, Bill Allen -------------- next part -------------- An HTML attachment was scrubbed... URL: From prologic at shortcircuit.net.au Thu Aug 12 06:06:57 2010 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 12 Aug 2010 14:06:57 +1000 Subject: [Tutor] a graceful program exit In-Reply-To: References: Message-ID: On Thu, Aug 12, 2010 at 1:42 PM, Bill Allen wrote: > I have only learned a couple of ways to cause a Python program to exit: > sys.exit(0)? &? raise.SystemExit .? I am using this in a try/except block. > Which is preferred?? Are there other, better ways? The normal pattern is to have an entry point and an exit point. main() and SystemExit exception. cheers James -- -- James Mills -- -- "Problems are solved by method" From karim.liateni at free.fr Thu Aug 12 06:38:52 2010 From: karim.liateni at free.fr (Karim) Date: Thu, 12 Aug 2010 06:38:52 +0200 Subject: [Tutor] Executing Python from TCL In-Reply-To: References: <4C62E33A.7090109@free.fr> Message-ID: <4C637ADC.9020008@free.fr> Hello Alan, I want to take benefit of xml.etree.ElementTree and xml.etree.CElementTree, which are very good and do most of the job for me (create automatically database with lists and dictionary for me). My point is to do a same API used by team developing with Python and another team developing in TCL. I want to facilitate the reuse and make everybody happy (no war between the 2 languages supporters) though for me Python is largely superior. Anyway, you're right I found what I needed at: http://sourceforge.net/projects/elmer/files/elmer/elmer1.1.5/elmer1.1.5.tar.gz/download This is the open source Elmer distribution. Thanks Karim On 08/12/2010 02:13 AM, Alan Gauld wrote: > > "Karim" wrote >> I want to know if there are modules or whatever to execute >> python functions inside TCL. > > Not that I know of, unless Google tells you something different. > You can of course call Python programs from Tcl and vice-versa. If you > use the Java versions of both you might succeed. > > Or you could wrap your parser as a separate server process and expose > it as a Web service or XML RPC... > > But given the wealth of xml parsers available for Tcl I'm surprised > that they need yours... > >> These functions should returns python lists as TCL lists and >> Python dictionary as TCL Hash tables. > > You could probably do some C level integration using Boost or SWIG or > somesuch but I doubt the benefit would be worth it. > > HTH, > > From knacktus at googlemail.com Thu Aug 12 07:37:11 2010 From: knacktus at googlemail.com (Knacktus) Date: Thu, 12 Aug 2010 07:37:11 +0200 Subject: [Tutor] Performance list vs. deque for [-1] Message-ID: <4C638887.7010401@googlemail.com> Hi everyone, I'm wondering what's the fastet datatype in python to lookup the last element in an ordered collection. I know about lists, of course, and read about deques. As I understand deques have better performance for popping and adding elements, but I didn't understand what's the behavior for look-up's without any changes to the collection. I will not pop() out of my ordered collection, and only recently append. Also, the collections will be small (about 10-20 elements), but I will have huge amount (50000-100000) of those collections which need to be processed for certain tasks in my application. Thanks in advance and cheers, Jan From hugo.yoshi at gmail.com Thu Aug 12 08:46:46 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Thu, 12 Aug 2010 01:46:46 -0500 Subject: [Tutor] a graceful program exit In-Reply-To: References: Message-ID: On Wed, Aug 11, 2010 at 11:06 PM, James Mills wrote: > On Thu, Aug 12, 2010 at 1:42 PM, Bill Allen wrote: >> I have only learned a couple of ways to cause a Python program to exit: >> sys.exit(0)? &? raise.SystemExit .? I am using this in a try/except block. >> Which is preferred?? Are there other, better ways? > > The normal pattern is to have an entry point and an exit point. > > main() and SystemExit exception. > > cheers > James > I usually just have the top of the program as entry point, and the bottom as exit. I like the simplicity. From info at evidenca.si Wed Aug 11 15:18:27 2010 From: info at evidenca.si (Evidenca B d.o.o.) Date: Wed, 11 Aug 2010 15:18:27 +0200 (Central Europe Daylight Time) Subject: [Tutor] UTF-8 character Message-ID: <4C62A323.00000F.03016@PRENOSNI-POLONA> Hi. I have a problem. I am making pa program which, makes a .txt document, the problem is in my language have special character like this: ?,?,?. They don t appear in aschi code, but you can find them in UTF-8 code. So wen I wont to save with writelines a string with one of those characters in tells me that I have to have string or that some of the characters don't appear in ashi. I don't know how to solve this problem, pleas help me. THX Karmen -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: bg.jpg Type: image/jpeg Size: 3066 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: flowers.jpg Type: image/jpeg Size: 2249 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: stampa_girl_line_en.gif Type: image/gif Size: 46417 bytes Desc: not available URL: From alan.gauld at btinternet.com Thu Aug 12 09:39:45 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Aug 2010 08:39:45 +0100 Subject: [Tutor] Executing Python from TCL References: <4C62E33A.7090109@free.fr> <4C637ADC.9020008@free.fr> Message-ID: "Karim" wrote > Anyway, you're right I found what I needed at: > > http://sourceforge.net/projects/elmer/files/elmer/elmer1.1.5/elmer1.1.5.tar.gz/download > > This is the open source Elmer distribution. OK, glad you found something and I'm sure it will be worth a try. But I'm pretty sure it will have to embed the Python interpreter so that the Tcl interpreter will call the python interpreter to execute the parser. That could lead to a significant slow down of your code. If speed is not a high priority you may get away with it. At least it should prove the concept and design of the app. But you may still find you need to use a native Tcl parser if speed is an issue. (Then again, if speed was a big issue you probably wouldn't be working in Tcl or even Python!) HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Aug 12 09:44:54 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Aug 2010 08:44:54 +0100 Subject: [Tutor] Performance list vs. deque for [-1] References: <4C638887.7010401@googlemail.com> Message-ID: "Knacktus" wrote > I'm wondering what's the fastet datatype in python to lookup the > last element in an ordered collection. When in doubt timeit() But I would expect a standard list to be prettyy fast isf you are only concerned about accessing the last element [-1] > Also, the collections will be small (about 10-20 elements), but I > will have huge amount (50000-100000) of those collections which need > to be processed for certain tasks in my application. Sounds like you should be more concerned about how you locate the specific collection than about finding the last element in each... What kind of container will the collections sit in? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From cfuller084 at thinkingplanet.net Thu Aug 12 08:59:26 2010 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Thu, 12 Aug 2010 01:59:26 -0500 Subject: [Tutor] a graceful program exit In-Reply-To: References: Message-ID: <201008120159.26758.cfuller084@thinkingplanet.net> The preferred and most graceful way is to use neither, as others have pointed out. However, you can't return an exit code that way, and it sometimes isn't feasible to structure your code to allow it. I prefer SystemExit, because it doesn't require adding something to the namespace (the sys module), and it seems a bit more pythonic. You can trap it, however, which bugs me. I think these two should exhibit the same behavior. I'd use sys.exit for "real" code, even though it appeals less aesthetically, because it is less prone to doing something unexpected (one of Python's guiding principles, btw). Cheers On Wednesday 11 August 2010, Bill Allen wrote: > I have only learned a couple of ways to cause a Python program to exit: > sys.exit(0) & raise.SystemExit . I am using this in a try/except block. > Which is preferred? Are there other, better ways? > > > Thanks, > Bill Allen From coolankur2006 at gmail.com Thu Aug 12 10:11:59 2010 From: coolankur2006 at gmail.com (ANKUR AGGARWAL) Date: Thu, 12 Aug 2010 13:41:59 +0530 Subject: [Tutor] string conversion according to the terminal Message-ID: Hey- suppose we have a file name-"my file number" if we want to execute it into the terminal it would be like - my\ file\ number so wondering is there any one in the python that change the enter string into the terminal string one- like if user enter the file name with path- "my file number". i want to automatically convert it into "my\ file\ number" Plz help me out in this. Thanks in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Thu Aug 12 10:40:39 2010 From: evert.rol at gmail.com (Evert Rol) Date: Thu, 12 Aug 2010 10:40:39 +0200 Subject: [Tutor] string conversion according to the terminal In-Reply-To: References: Message-ID: <4154E574-D1A7-4F63-A407-CD9D220239E8@gmail.com> > Hey- suppose we have a file name-"my file number" > if we want to execute it into the terminal it would be like - my\ file\ number > > so wondering is there any one in the python that change the enter string into the terminal string one- > like if user enter the file name with path- "my file number". i want to automatically convert it into "my\ file\ number" > Plz help me out in this. >>> a = "my file number" >>> a.replace(' ', '\\ ') 'my\\ file\\ number' >>> print a.replace(' ', '\\ ') my\ file\ number From sander.sweers at gmail.com Thu Aug 12 12:07:10 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Thu, 12 Aug 2010 12:07:10 +0200 Subject: [Tutor] Performance list vs. deque for [-1] In-Reply-To: References: <4C638887.7010401@googlemail.com> Message-ID: On 12 August 2010 09:44, Alan Gauld wrote: >> I'm wondering what's the fastet datatype in python to lookup the last >> element in an ordered collection. > > When in doubt timeit() Out of curiosity I used timeit and lists are faster if we iterate over them one by one. Now this is my first go with the timeit module so please do correct me :-). Code used is at http://python.pastebin.org/475014. def getLastItem(c): return [x[-1] for x in c] The list/deque consists of 5000 items (lists or deques) with a length 21 random ints. Also for deque I used maxlen=26 which makes it a bit faster. List took 0.000693 seconds 693.01178383827209 / 100000 (default times run by timeit) Deque took 0.009195 seconds 693.01178383827209 / 100000 (default times run by timeit) How this applies to the OP situation I don't know.. Greets Saner From davea at ieee.org Thu Aug 12 12:10:36 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 12 Aug 2010 06:10:36 -0400 Subject: [Tutor] Performance list vs. deque for [-1] In-Reply-To: <4C638887.7010401@googlemail.com> References: <4C638887.7010401@googlemail.com> Message-ID: <4C63C89C.3060301@ieee.org> Knacktus wrote: > Hi everyone, > > I'm wondering what's the fastet datatype in python to lookup the last > element in an ordered collection. I know about lists, of course, and > read about deques. As I understand deques have better performance for > popping and adding elements, but I didn't understand what's the > behavior for look-up's without any changes to the collection. > > I will not pop() out of my ordered collection, and only recently > append. Also, the collections will be small (about 10-20 elements), > but I will have huge amount (50000-100000) of those collections which > need to be processed for certain tasks in my application. > > Thanks in advance and cheers, > > Jan > Referencing the last element of a list by items[-1] is very fast, and switching to a deque will not be any quicker, and probably a lot slower. Indeed looking up any element if you know the index# is fast. It's only when you need to look up an item by its value that a deque gets to be quicker, and even there, I doubt if it'd help much for a list of only 10 items. In case you ever do need to do pop(), realize that a pop(-1) (which is the default you get if you just say pop() ), is very quick. It's dangerous to make assertions like this without actually timing it, but I'd be surprised if a deque could beat a list on any of the above operations. DaveA From sander.sweers at gmail.com Thu Aug 12 12:12:05 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Thu, 12 Aug 2010 12:12:05 +0200 Subject: [Tutor] string conversion according to the terminal In-Reply-To: <4154E574-D1A7-4F63-A407-CD9D220239E8@gmail.com> References: <4154E574-D1A7-4F63-A407-CD9D220239E8@gmail.com> Message-ID: On 12 August 2010 10:40, Evert Rol wrote: >>>> a = "my file number" >>>> a.replace(' ', '\\ ') > 'my\\ file\\ number' What if a has more than 1 space between words? Then I think this would be a safer way. >>> print "\\ ".join("my file number".split()) my\ file\ number Greets Sander From sander.sweers at gmail.com Thu Aug 12 12:17:47 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Thu, 12 Aug 2010 12:17:47 +0200 Subject: [Tutor] Performance list vs. deque for [-1] In-Reply-To: References: <4C638887.7010401@googlemail.com> Message-ID: On 12 August 2010 12:07, Sander Sweers wrote: > Deque took 0.009195 seconds > 693.01178383827209 / 100000 (default times run by timeit) Messed up the deque results :( Deque took 0.009195 seconds 919.49732708930969 / 100000 (default times run by timeit) Greets Sander From evert.rol at gmail.com Thu Aug 12 12:19:12 2010 From: evert.rol at gmail.com (Evert Rol) Date: Thu, 12 Aug 2010 12:19:12 +0200 Subject: [Tutor] string conversion according to the terminal In-Reply-To: References: <4154E574-D1A7-4F63-A407-CD9D220239E8@gmail.com> Message-ID: >>>>> a = "my file number" >>>>> a.replace(' ', '\\ ') >> 'my\\ file\\ number' > > What if a has more than 1 space between words? Then I think this would > be a safer way. > >>>> print "\\ ".join("my file number".split()) > my\ file\ number If those spaces are in the actual filename, you'll want to keep them, hence you'll need to escape those extra spaces as well. From davea at ieee.org Thu Aug 12 12:30:59 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 12 Aug 2010 06:30:59 -0400 Subject: [Tutor] UTF-8 character In-Reply-To: <4C62A323.00000F.03016@PRENOSNI-POLONA> References: <4C62A323.00000F.03016@PRENOSNI-POLONA> Message-ID: <4C63CD63.1070307@ieee.org> Evidenca B d.o.o. wrote: > Hi. > > > > I have a problem. I am making pa program which, makes a .txt document, the > problem is in my language have special character like this: ?,?,?. They don > t appear in aschi code, but you can find them in UTF-8 code. So wen I wont > to save with writelines a string with one of those characters in tells me > that I have to have string or that some of the characters don't appear in > ashi. > > I don't know how to solve this problem, pleas help me. > > > > THX > > Karmen > You don't say what version of Python you use, and you don't show either the code or the error traceback. So we can only guess what your problem is. I'll assume you're using Python 2.6 or 2.7, running on Windows, and that you have code like the following: I'll also assume you've solved the source file encoding issues that pertain to string literals. .... #mystrings is a list of Unicode strings with some non-ascii characters in one or more of them outfile = open(filename, "w") outfile.writelines(mystrings) If you replace the open with outfile = codecs.open(filename,'wb','utf-8-sig') you should correctly write the unicode as utf8 strings to the file. DaveA From evert.rol at gmail.com Thu Aug 12 12:44:24 2010 From: evert.rol at gmail.com (Evert Rol) Date: Thu, 12 Aug 2010 12:44:24 +0200 Subject: [Tutor] string conversion according to the terminal In-Reply-To: References: <4154E574-D1A7-4F63-A407-CD9D220239E8@gmail.com> Message-ID: > Ok. I appreciate ur response and its gud somewhat... But we dont have only space=" " . this '\' rules also applies to '(' ')' and all that stuff also... so i was looking for the builtin function that fully converts it... Is there any one?? This may depend on your system, but generally, putting the complete filename between quotes ("some filename with ()") also works well; no need for escapes (unless your filename contains quotes itself). Otherwise, you put the a.replace in a simple for loop that iterates through all special characters that need to be replaced. Or you could look into regular expressions: re.sub can help. Lastly, depending on your exact needs, Python may already take care of this anyway. Eg: >>> import glob >>> files = glob.glob("special*") >>> files ['special name'] >>> f = open(files[0]) >>> f.read() 'data\n' So even though there's no escape for the space character in 'special name', Python's open is smart enough to take care of the spaces and open the file correctly anyway. > >>>>> a = "my file number" > >>>>> a.replace(' ', '\\ ') > >> 'my\\ file\\ number' > > > > What if a has more than 1 space between words? Then I think this would > > be a safer way. > > > >>>> print "\\ ".join("my file number".split()) > > my\ file\ number > > If those spaces are in the actual filename, you'll want to keep them, hence you'll need to escape those extra spaces as well. From steve at pearwood.info Thu Aug 12 13:35:01 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 12 Aug 2010 21:35:01 +1000 Subject: [Tutor] a graceful program exit In-Reply-To: <201008120159.26758.cfuller084@thinkingplanet.net> References: <201008120159.26758.cfuller084@thinkingplanet.net> Message-ID: <201008122135.01977.steve@pearwood.info> On Thu, 12 Aug 2010 04:59:26 pm Chris Fuller wrote: > The preferred and most graceful way is to use neither, as others have > pointed out. However, you can't return an exit code that way Of course you can. Exiting out the end of the program returns an exit code of zero, and raising an uncaught exception returns a non-zero exit code: [steve at sylar ~]$ python -c "pass" [steve at sylar ~]$ echo $? 0 [steve at sylar ~]$ python -c "raise ValueError('spam')" Traceback (most recent call last): File "", line 1, in ValueError: spam [steve at sylar ~]$ echo $? 1 If you need to specify the exit code yourself, and avoid the traceback, that's exactly what SystemExit is for: [steve at sylar babble]$ python -c "raise SystemExit(42)" [steve at sylar babble]$ echo $? 42 > , and it > sometimes isn't feasible to structure your code to allow it. I > prefer SystemExit, because it doesn't require adding something to the > namespace (the sys module), and it seems a bit more pythonic. You > can trap it, however, which bugs me. I think these two should > exhibit the same behavior. I'd use sys.exit for "real" code, even > though it appeals less aesthetically, because it is less prone to > doing something unexpected (one of Python's guiding principles, btw). They do have the same behaviour. help(sys.exit) says: Exit the interpreter by raising SystemExit(status). and sure enough, it can be caught: [steve at sylar ~]$ python -c " import sys try: sys.exit(42) except SystemExit: print 'Caught' " Caught [steve at sylar ~]$ echo $? 0 -- Steven D'Aprano From __peter__ at web.de Thu Aug 12 15:28:03 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 12 Aug 2010 15:28:03 +0200 Subject: [Tutor] string conversion according to the terminal References: Message-ID: ANKUR AGGARWAL wrote: > Hey- suppose we have a file name-"my file number" > if we want to execute it into the terminal it would be like - my\ file\ > number > > so wondering is there any one in the python that change the enter string > into the terminal string one- > like if user enter the file name with path- "my file number". i want to > automatically convert it into "my\ file\ number" If you want this to prepare an os.system() call you should instead use subprocess.call() with a list containing the command and a filename that is not escaped. >>> import subprocess, os Bad: >>> os.system(r"ls -l my\ file\ number") -rw-r--r-- 1 petto petto 0 2010-08-12 15:20 my file number 0 Good: >>> subprocess.call(["ls", "-l", "my file number"]) -rw-r--r-- 1 petto petto 0 2010-08-12 15:20 my file number 0 Peter From zstumgoren at gmail.com Thu Aug 12 18:20:48 2010 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 12 Aug 2010 12:20:48 -0400 Subject: [Tutor] is it possible to call a setter property during class instantiation? Message-ID: Hey all, Does anyone know if it's possible to call a property setter inside of a class's init method? Below is a code sample of what I'm trying to do. class Question(object); def __init__(self, value): self.text(value) @property def text(self): return self._text @text.setter def text(self, value): if not isinstance(value, str): raise TypeError self._text = value Here's an explanation of what I'm trying to accomplish: I have a class with an init method that is getting bloated with error-checking guard clauses. I was hoping to "hide" some of these guard clauses by using the @property decorator and its associated setter method. I'd like to use the Question.text property to set the value (or raise an error) upon instantiation of a Question object. I figured this would clean up my init method and move the error-checking code closer to the relevant class attribute. I've tried numerous variations on the above init method, but all without success. In the current version, when I try: >>> q = Question("Hello world?") I get the following error: AttributeError: 'Question' object has no attribute '_text' I was hoping text property would create self._text for me on instantiation, but apparently no dice. I'm also getting errors when I do the below variations: ### variation 1 #### def __init__(self, value): self._text = '' self.text(value) ### variation 2 #### def __init__(self, value): self._text = None self.text(value) Can anyone point out what I'm doing wrong? I suspect I'm misunderstanding properties and/or the finer points of object instantiation. Any help would be greatly appreciated! Thanks! Serdar -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Thu Aug 12 18:37:15 2010 From: evert.rol at gmail.com (Evert Rol) Date: Thu, 12 Aug 2010 18:37:15 +0200 Subject: [Tutor] is it possible to call a setter property during class instantiation? In-Reply-To: References: Message-ID: <4395F5DB-E70F-486C-898A-2E04187696EE@gmail.com> > Does anyone know if it's possible to call a property setter inside of a class's init method? Below is a code sample of what I'm trying to do. Just a quick guess: > class Question(object); replace the semi-colon with a colon (I assume it's just a typo, since you don't get an error for this). > > def __init__(self, value): > self.text(value) self.text = value # is the way to do this, if you're using it as a property. > > @property > def text(self): > return self._text > > @text.setter > def text(self, value): > if not isinstance(value, str): > raise TypeError > self._text = value > > > Here's an explanation of what I'm trying to accomplish: > > I have a class with an init method that is getting bloated with error-checking guard clauses. I was hoping to "hide" some of these guard clauses by using the @property decorator and its associated setter method. I'd like to use the Question.text property to set the value (or raise an error) upon instantiation of a Question object. I figured this would clean up my init method and move the error-checking code closer to the relevant class attribute. I've tried numerous variations on the above init method, but all without success. > > > In the current version, when I try: > > >>> q = Question("Hello world?") > > I get the following error: > > AttributeError: 'Question' object has no attribute '_text' > > I was hoping text property would create self._text for me on instantiation, but apparently no dice. I'm also getting errors when I do the below variations: > > ### variation 1 #### > def __init__(self, value): > self._text = '' > self.text(value) > > ### variation 2 #### > def __init__(self, value): > self._text = None > self.text(value) > > Can anyone point out what I'm doing wrong? I suspect I'm misunderstanding properties and/or the finer points of object instantiation. Any help would be greatly appreciated! Again, see the correction above: use 'self.text = value'. Don't use self._text, nor call self.text() > > Thanks! > Serdar From zstumgoren at gmail.com Thu Aug 12 19:07:05 2010 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Thu, 12 Aug 2010 13:07:05 -0400 Subject: [Tutor] is it possible to call a setter property during class instantiation? In-Reply-To: <4395F5DB-E70F-486C-898A-2E04187696EE@gmail.com> References: <4395F5DB-E70F-486C-898A-2E04187696EE@gmail.com> Message-ID: > > def __init__(self, value): > > self.text(value) > > self.text = value # is the way to do this, if you're using it as a > property. > > That worked perfectly! So it seems I was botching the syntax. Many thanks for the quick response!! Serdar -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Thu Aug 12 19:31:09 2010 From: wallenpb at gmail.com (Bill Allen) Date: Thu, 12 Aug 2010 12:31:09 -0500 Subject: [Tutor] a graceful program exit In-Reply-To: <201008122135.01977.steve@pearwood.info> References: <201008120159.26758.cfuller084@thinkingplanet.net> <201008122135.01977.steve@pearwood.info> Message-ID: On Thu, Aug 12, 2010 at 6:35 AM, Steven D'Aprano wrote: > On Thu, 12 Aug 2010 04:59:26 pm Chris Fuller wrote: > > The preferred and most graceful way is to use neither, as others have > > pointed out. However, you can't return an exit code that way > > Of course you can. Exiting out the end of the program returns an exit > code of zero, and raising an uncaught exception returns a non-zero exit > code: > > [steve at sylar ~]$ python -c "pass" > [steve at sylar ~]$ echo $? > 0 > > [steve at sylar ~]$ python -c "raise ValueError('spam')" > Traceback (most recent call last): > File "", line 1, in > ValueError: spam > [steve at sylar ~]$ echo $? > 1 > > > If you need to specify the exit code yourself, and avoid the traceback, > that's exactly what SystemExit is for: > > [steve at sylar babble]$ python -c "raise SystemExit(42)" > [steve at sylar babble]$ echo $? > 42 > > > > , and it > > sometimes isn't feasible to structure your code to allow it. I > > prefer SystemExit, because it doesn't require adding something to the > > namespace (the sys module), and it seems a bit more pythonic. You > > can trap it, however, which bugs me. I think these two should > > exhibit the same behavior. I'd use sys.exit for "real" code, even > > though it appeals less aesthetically, because it is less prone to > > doing something unexpected (one of Python's guiding principles, btw). > > They do have the same behaviour. help(sys.exit) says: > > Exit the interpreter by raising SystemExit(status). > > and sure enough, it can be caught: > > > [steve at sylar ~]$ python -c " > import sys > try: > sys.exit(42) > except SystemExit: > print 'Caught' > " > Caught > [steve at sylar ~]$ echo $? > 0 > > > Steven, Excellent! I think that may be everything I needed to know about that. I appreciate you and the others responding. Thanks, Bill Allen -------------- next part -------------- An HTML attachment was scrubbed... URL: From sudarshana.b at gmail.com Fri Aug 13 03:39:03 2010 From: sudarshana.b at gmail.com (Sudarshana Banerjee) Date: Thu, 12 Aug 2010 18:39:03 -0700 Subject: [Tutor] elif statement In-Reply-To: <4C62050D.80307@gmail.com> References: <4C62050D.80307@gmail.com> Message-ID: Thank you Adam. On Tue, Aug 10, 2010 at 7:03 PM, Adam Bark wrote: > On 11/08/10 02:34, Sudarshana Banerjee wrote: > > Hi: I am trying to teach myself Python, and am stuck at the indentation > with the elif statement. > > This is what I am trying to type (as copied from the textbook): > > x=3 > if x==0: > print "x is 0" > elif x&1 ==1: > print "x is a odd number" > elif x&1==0: -- Line 6 > print "x is a even number" > > If I am combining the if and the print statement, then the elif statement > is in the next line, and all is well with the world. If however, I write the > print as a separate statement, I am getting a syntax error after I press > Enter after keying the first elif statement. > > >>> x=3 > >>> if x==0: > print x > elif x==2: > > > Here you have indented the elif statement but it should be at the same > level as the if: > > >>> x=3 > >>> if x==0: > ... print x > ... elif x==2: > ... print "something else" > ... > >>> > > > SyntaxError: invalid syntax > > Again: > >>> x=3 > >>> if x==2: print x > elif x&1 == 1: print 'x is odd' > >>> elif x&1 ==0: print 'x is even' > SyntaxError: invalid syntax > > > I'm not sure what's going on here but the second elif is being interpreted > separate to the rest of the if statement hence a SyntaxError: > > >>> elif x&1 == 0: print "x is even" > File "", line 1 > > elif x&1 == 0: print "x is even" > ^ > SyntaxError: invalid syntax > > This works: > > >>> if x==2: print x > ... elif x&1 == 1: print 'x is odd' > ... elif x&1 ==0: print 'x is even' > ... > x is odd > > > > > If I am pressing two Enters, the code executes; so I have a elif without > a if, and again, a syntax error. What am I not doing right? > > Thank you. > > Sudarshana. > > HTH, > Adam. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sudarshana.b at gmail.com Fri Aug 13 03:40:44 2010 From: sudarshana.b at gmail.com (Sudarshana Banerjee) Date: Thu, 12 Aug 2010 18:40:44 -0700 Subject: [Tutor] elif statement In-Reply-To: <4C62D6D9.8030503@free.fr> References: <4C62D6D9.8030503@free.fr> Message-ID: Thank you Karim.. the code is not actually part of anything... but is a textbook example, literally (Python Power by Matt Telles). On Wed, Aug 11, 2010 at 9:59 AM, Karim wrote: > > Hello, > > This code works for me: > > > >>> x=3 > >>> if x==0: > ... print "x is 0" > ... elif x&1 ==1: > ... print "x is a odd number" > ... elif x&1==0: > ... print "x is a even number" > ... > > x is a odd number > > So I think you copied by error the string '-- Line 6' in you example given > that has nothing to > do with the rest of the code. > > Regards > Karim > > > > On 08/11/2010 03:34 AM, Sudarshana Banerjee wrote: > >> print "x is a even number" >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sudarshana.b at gmail.com Fri Aug 13 03:45:19 2010 From: sudarshana.b at gmail.com (Sudarshana Banerjee) Date: Thu, 12 Aug 2010 18:45:19 -0700 Subject: [Tutor] elif statement In-Reply-To: References: <4C62050D.80307@gmail.com> Message-ID: Hi: Thank you very much for the detailed reply. My problem is I know I am doing the indentation wrong; but I cannot get it right in IDLE. Could you take a look at this please: >>> x=3 >>> if x==0: print "x is 0" >>> elif x&1==1: SyntaxError: invalid syntax See, the moment I am pressing Enter the >>> is coming.. not ... I am using IDLE on Mac; and this is driving me crazy! :) I can get the result if I combine the if and print statements in one line.. but I really want to know what is going on. On Wed, Aug 11, 2010 at 1:22 AM, Dipo Elegbede wrote: > You need to check the indentation properly. > In this case, elif has to be on the same indentation level with if. I > should think so. > If you're working straight from the python interactive console, like I > think you're doing, you need to manually do the indentation thing by > yourself. > First, I don't understand why you chose to set x to 3. That is not the > main thing though. > After x = 3, if you press enter, you'd get the python prompt > >>> > Then you type the next statement to have > >>> if x == 0: > What you get after this if statement is either a whitespace or ..., > from my phone, I get a ... > So you manually press the spacebar twice to get an indentation for the > first print statement. > As soon as you press enter again, you get the dots, just type in the > elif statements without pressing the spacebar. Then press enter to > move to a new line where the second print statement would be,and press > the spacebar twice again for indentation. > For the second elif statement, follow the procedure for the first elif > statement. > Go ahead and press enter twice to tell the console you are done, you > shouldn't get an error that way. > You should get something like below: > > >>> x=3 > >>> if x==0: > ... print x,'is zero' > ... elif x//1==1: > ... print x,'is odd' > ... elif x//1==0: > ... print x,'is even' > ... else: > ... print'what is this' > ... > > The else statement is optional. > Hope it helps. > > On 8/11/10, Adam Bark wrote: > > On 11/08/10 02:34, Sudarshana Banerjee wrote: > >> Hi: I am trying to teach myself Python, and am stuck at the > >> indentation with the elif statement. > >> > >> This is what I am trying to type (as copied from the textbook): > >> > >> x=3 > >> if x==0: > >> print "x is 0" > >> elif x&1 ==1: > >> print "x is a odd number" > >> elif x&1==0: -- Line 6 > >> print "x is a even number" > >> > >> If I am combining the if and the print statement, then the elif > >> statement is in the next line, and all is well with the world. If > >> however, I write the print as a separate statement, I am getting a > >> syntax error after I press Enter after keying the first elif statement. > >> > >> >>> x=3 > >> >>> if x==0: > >> print x > >> elif x==2: > > > > Here you have indented the elif statement but it should be at the same > > level as the if: > > >>> x=3 > > >>> if x==0: > > ... print x > > ... elif x==2: > > ... print "something else" > > ... > > >>> > > > > > >> SyntaxError: invalid syntax > >> > >> Again: > >> >>> x=3 > >> >>> if x==2: print x > >> elif x&1 == 1: print 'x is odd' > >> >>> elif x&1 ==0: print 'x is even' > >> SyntaxError: invalid syntax > > > > I'm not sure what's going on here but the second elif is being > > interpreted separate to the rest of the if statement hence a SyntaxError: > > >>> elif x&1 == 0: print "x is even" > > File "", line 1 > > elif x&1 == 0: print "x is even" > > ^ > > SyntaxError: invalid syntax > > > > This works: > > >>> if x==2: print x > > ... elif x&1 == 1: print 'x is odd' > > ... elif x&1 ==0: print 'x is even' > > ... > > x is odd > > > > > >> > >> If I am pressing two Enters, the code executes; so I have a elif > >> without a if, and again, a syntax error. What am I not doing right? > >> > >> Thank you. > >> > >> Sudarshana. > > HTH, > > Adam. > > > > > > > > > -- > Elegbede Muhammed Oladipupo > OCA > +2348077682428 > +2347042171716 > www.dudupay.com > Mobile Banking Solutions | Transaction Processing | Enterprise > Application Development > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pkoek11 at xs4all.nl Fri Aug 13 03:56:31 2010 From: pkoek11 at xs4all.nl (Pete) Date: Thu, 12 Aug 2010 21:56:31 -0400 Subject: [Tutor] Callbacks and exception handling Message-ID: <51AF4A93-F626-4E03-8546-42CFA263A76B@xs4all.nl> Hi, I've been writing some code which uses callbacks. I have not used callbacks much before, but it does not seem too difficult so far. One thing though - I noticed that when an exception is raised in the callback function, that exception doesn't actually "show up" in the calling program. Two questions: 1) Theoretically - why is this? I guess I've seen callback functions a little like subroutines, therefore it seems intuitive that an exception would be propagated up to the calling routine. 2) How can you catch an exception in the callback function? The code is not easily isolated, but can post if necessary. thanks again, Pete From steve at pearwood.info Fri Aug 13 04:09:54 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 13 Aug 2010 12:09:54 +1000 Subject: [Tutor] Callbacks and exception handling In-Reply-To: <51AF4A93-F626-4E03-8546-42CFA263A76B@xs4all.nl> References: <51AF4A93-F626-4E03-8546-42CFA263A76B@xs4all.nl> Message-ID: <201008131209.55206.steve@pearwood.info> On Fri, 13 Aug 2010 11:56:31 am Pete wrote: > Hi, > > I've been writing some code which uses callbacks. I have not used > callbacks much before, but it does not seem too difficult so far. > > One thing though - I noticed that when an exception is raised in the > callback function, that exception doesn't actually "show up" in the > calling program. > > Two questions: > > 1) Theoretically - why is this? I guess I've seen callback functions > a little like subroutines, therefore it seems intuitive that an > exception would be propagated up to the calling routine. They are, unless the calling function explicitly catches and subpresses the exception. > 2) How can you catch an exception in the callback function? The same way you catch an exception anywhere: with a try...except block. If you are writing a callback function, and want to catch your own exception: def callback(): try: do_stuff_here except (KeyError, ValueError, TypeError): # or whatever pass If you are writing the calling function: def caller(arg, callback): do_something_with(arg) try: callback() except (AttributeError, RecursionError): # or whatever pass By the way, don't be tempted to write a bare except clause: try: ... except: ... There are very few reasons for such a thing, as they are too broad and catch too many things, masking errors, preventing user keyboard interrupts, etc. Avoid them. -- Steven D'Aprano From karim.liateni at free.fr Fri Aug 13 04:20:46 2010 From: karim.liateni at free.fr (Karim) Date: Fri, 13 Aug 2010 04:20:46 +0200 Subject: [Tutor] Executing Python from TCL In-Reply-To: References: <4C62E33A.7090109@free.fr> <4C637ADC.9020008@free.fr> Message-ID: <4C64ABFE.2040008@free.fr> Thanks Alan, For clarify that. The speed is not an issue people just need config files generated from xml to feed EDA simulations and validations tools. Karim On 08/12/2010 09:39 AM, Alan Gauld wrote: > > "Karim" wrote > >> Anyway, you're right I found what I needed at: >> >> http://sourceforge.net/projects/elmer/files/elmer/elmer1.1.5/elmer1.1.5.tar.gz/download >> >> >> This is the open source Elmer distribution. > > OK, glad you found something and I'm sure it will be worth a try. > But I'm pretty sure it will have to embed the Python interpreter > so that the Tcl interpreter will call the python interpreter to execute > the parser. That could lead to a significant slow down of your code. > If speed is not a high priority you may get away with it. At least > it should prove the concept and design of the app. > > But you may still find you need to use a native Tcl parser if speed > is an issue. (Then again, if speed was a big issue you probably > wouldn't be working in Tcl or even Python!) > > HTH > > From pkoek11 at xs4all.nl Fri Aug 13 05:24:59 2010 From: pkoek11 at xs4all.nl (Pete) Date: Thu, 12 Aug 2010 23:24:59 -0400 Subject: [Tutor] Callbacks and exception handling In-Reply-To: <201008131209.55206.steve@pearwood.info> References: <51AF4A93-F626-4E03-8546-42CFA263A76B@xs4all.nl> <201008131209.55206.steve@pearwood.info> Message-ID: <53550E4D-956C-4D26-A188-E5DFDA152B85@xs4all.nl> > By the way, don't be tempted to write a bare except clause: > > try: > ... > except: > ... > > There are very few reasons for such a thing, as they are too broad and > catch too many things, masking errors, preventing user keyboard > interrupts, etc. Avoid them. Doh! That is what I did :) Thanks Steve! -Pete From alan.gauld at btinternet.com Fri Aug 13 10:06:27 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Aug 2010 09:06:27 +0100 Subject: [Tutor] string conversion according to the terminal References: Message-ID: "ANKUR AGGARWAL" wrote > Hey- suppose we have a file name-"my file number" > if we want to execute it into the terminal it would be like - my\ > file\ > number It depends what you are trying to do. > so wondering is there any one in the python that change the enter > string > into the terminal string one- like if user enter the file name with > path- "my file number". i want to automatically convert it into "my\ > file\ number" If you use raw_input to capture the filename then the escaping will be done for you when you come to use it. >>> s = raw_input('?') ?name with spaces >>> s 'name with spaces' >>> f = open(s,'w') >>> f.write('hello world\n') >>> f.close() >>> f = open(s) >>> f.read() 'hello world\n' >>> f.close() >>> ^Z C:\Documents and Settings\Alan Gauld>dir n* Volume in drive C is SYSTEM Volume Serial Number is 7438-BB1D Directory of C:\Documents and Settings\Alan Gauld 13/08/2010 09:03 13 name with spaces So are you sure you need to do this? -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Aug 13 10:13:11 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Aug 2010 09:13:11 +0100 Subject: [Tutor] is it possible to call a setter property during classinstantiation? References: Message-ID: "Serdar Tumgoren" wrote > Does anyone know if it's possible to call a property setter inside > of a > class's init method? Below is a code sample of what I'm trying to > do. Yes and that bit has been answered. But... > I have a class with an init method that is getting bloated with > error-checking guard clauses. Thats very strange. We don't usually have to check types in Python, it is a dynamic language and we can use duck-typing and exceptions so we don't usually care too much about types. Are you sure you really need all that type checking code? Or are you simply carrying bad habits over from statically typed programming experience? I can't tell the context so it may be that you really do need to check a lot of types, but it is quite unusual and does usually lead to a lot of extra work. Python is not Java or C++ etc... Just a thought, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Aug 13 10:23:19 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Aug 2010 09:23:19 +0100 Subject: [Tutor] Callbacks and exception handling References: <51AF4A93-F626-4E03-8546-42CFA263A76B@xs4all.nl> Message-ID: "Pete" wrote > One thing though - I noticed that when an exception is raised in the > callback function, that exception doesn't actually "show up" in the > calling program. Yes it does and Steven has answered that so maybe you are clear now. But just to clarify, when you set a callback there is no guarantee that the callback gets used immediately so the exception will not necessarily appear in the setting function, it will appear in the calling function. cb = [] def setcb(f): cb.append(f) def fireworks(): try: for f in cb: print f() # call them all now except: print 'a callback failed' def myFunc() setcb('lambda : len(cb)) setcb('lambda : 42) setcb('lambda : 66) setcb('lambda : 12/0) #oops! myFunc() fireworks() Here any exceptions in the callback functions won't appear until the fireworks function, they will not show up in myFunc. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Aug 13 10:27:29 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Aug 2010 09:27:29 +0100 Subject: [Tutor] elif statement References: <4C62050D.80307@gmail.com> Message-ID: "Sudarshana Banerjee" wrote > Could you take a look at this please: >>>> x=3 >>>> if x==0: > print "x is 0" > >>>> elif x&1==1: > SyntaxError: invalid syntax > > See, the moment I am pressing Enter the >>> is coming.. not ... IDLE doesn't give you a ... prompt it gives you spaces. So you mistake is that ypu are hitting Enter after your print line. It needs to look like: >>> x=3 >>> if x==0: print "x is 0" elif x&1==1: print.... Which looks horrible and I wish Idle were fixed so it didn't do this. I keep meaning to try and find a way to patch it myself! Essentially you need to ignore the >>> offset in the if line. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From squirrox at gmail.com Fri Aug 13 12:22:52 2010 From: squirrox at gmail.com (Stephen Farthing) Date: Fri, 13 Aug 2010 11:22:52 +0100 Subject: [Tutor] Learning Python ...Books Message-ID: Hi everyone, I am going to learn both Python and Ruby so I can see what suits me best. My ultimate aim is to do some open source cross platform development for my ham radio and robotics hobbies. One of the key requirements is to be able to control hardware, via USB, using a GUI. I am an old school programmer - PL/1, Cobol, RTL/2, Algol 60 and I currently use C to program microcontrollers. I like Jackson Structured Programming (the other Michael Jackson) and am not up to speed with Object Orientation. I also learn stuff best from books. What I was wondering is if there is a Python equivalent to "The C Programming language" by Kernighan and Richie which is the best text on programming i have ever read. Thanks in advance, Steve -- It is vain to do with more that which can be done with less. -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Fri Aug 13 14:04:30 2010 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 13 Aug 2010 08:04:30 -0400 Subject: [Tutor] Learning Python ...Books In-Reply-To: References: Message-ID: I like "Learning Python" (O'reilly) Its thicker, but excellent. There isn't really an equivalent to K & R. But, you should go to python.org and read the docs. They are very good On Fri, Aug 13, 2010 at 6:22 AM, Stephen Farthing wrote: > Hi everyone, > > I am going to learn both Python and Ruby so I can see what suits me best. > My ultimate aim is to do some open source cross platform development for my > ham radio and robotics hobbies. One of the key requirements is to be able to > control hardware, via USB, using a GUI. > > I am an old school programmer - PL/1, Cobol, RTL/2, Algol 60 and I > currently use C to program microcontrollers. I like Jackson Structured > Programming (the other Michael Jackson) and am not up to speed with Object > Orientation. I also learn stuff best from books. > > What I was wondering is if there is a Python equivalent to "The C > Programming language" by Kernighan and Richie which is the best text on > programming i have ever read. > > Thanks in advance, > > Steve > > -- > It is vain to do with more that which can be done with less. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Fri Aug 13 14:29:42 2010 From: wallenpb at gmail.com (Bill Allen) Date: Fri, 13 Aug 2010 07:29:42 -0500 Subject: [Tutor] Learning Python ...Books In-Reply-To: References: Message-ID: On Fri, Aug 13, 2010 at 5:22 AM, Stephen Farthing wrote: > > What I was wondering is if there is a Python equivalent to "The C > Programming language" by Kernighan and Richie which is the best text on > programming i have ever read. > > Thanks in advance, > > Steve > Steve, There are several books out there, some for Python 2.x, some for Python 3.x. None that are quite like K&R in my opinion. However, here are some resources that may be useful for you, web based but some providing PDF download so you can build a book if you like. A Byte of Python Dive into Python v.2 Dive into Python v.3 The Learning to Program Website (teaches using Python) How to Think Like a Computer Scientist (also teaches using Python) Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Fri Aug 13 14:33:48 2010 From: wallenpb at gmail.com (Bill Allen) Date: Fri, 13 Aug 2010 07:33:48 -0500 Subject: [Tutor] Learning Python ...Books In-Reply-To: References: Message-ID: On Fri, Aug 13, 2010 at 7:29 AM, Bill Allen wrote: > > > There are several books out there, some for Python 2.x, some for Python > 3.x. None that are quite like K&R in my opinion. > However, here are some resources that may be useful for you, web based but > some providing PDF download so you can build a book if you like. > > A Byte of Python > > Dive into Python v.2 Dive into Python > v.3 > > The Learning to Program Website (teaches using Python) > > How to Think Like a Computer Scientist (also teaches using Python) > > Bill > > > I also forgot to mention that the Python book that I am reading right now is Programming in Python 3 by Mark Summerfield Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From zstumgoren at gmail.com Fri Aug 13 15:55:23 2010 From: zstumgoren at gmail.com (Serdar Tumgoren) Date: Fri, 13 Aug 2010 09:55:23 -0400 Subject: [Tutor] is it possible to call a setter property during classinstantiation? In-Reply-To: References: Message-ID: > > > > I have a class with an init method that is getting bloated with >> error-checking guard clauses. >> > > Thats very strange. We don't usually have to check types in Python, > it is a dynamic language and we can use duck-typing and exceptions > so we don't usually care too much about types. Are you sure you > really need all that type checking code? Hmm...for my scenario I thought I needed to bend that rule, but if I explain the use case perhaps you can offer alternatives. Much of my error-checking aims to ensure that a class is "fed" the correct type of data. For instance, I included a type check for a string to make sure that a future programmer (or myself) wouldn't try to pass in a list of lines after a text has been split. Other code internal to the Question class depends on the fact that the incoming data arrives in the form of a single string. If the wrong data type is fed, then I have a custom exception that gets raised to specify the problem. I guess the program would just crash with a TypeError if a list of lines was fed rather than a string, so even without the guard clause the processing would not take place. Is it better in such cases to just let the program die a natural death, without cluttering things up with such anticipatory guard clauses? I have to admit, it certainly does clutter up the code and seems to be leading to a lot of additional unit testing overhead. Is there a better way to approach these issues? -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Fri Aug 13 17:18:39 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 13 Aug 2010 10:18:39 -0500 Subject: [Tutor] Learning Python ...Books In-Reply-To: References: Message-ID: On Fri, Aug 13, 2010 at 5:22 AM, Stephen Farthing wrote: > Hi everyone, > > I am going to learn both Python and Ruby so I can see what suits me best. > My ultimate aim is to do some open source cross platform development for my > ham radio and robotics hobbies. One of the key requirements is to be able to > control hardware, via USB, using a GUI. > Using the pyserial module: http://pyserial.sourceforge.net/, and depending on how advanced you want to get, Tkinter, pyGTK, wxPython, or PyQT (as the main choices) are great ways to do such a thing. I've used pyserial with my Arduino under Ubuntu and it worked great. > What I was wondering is if there is a Python equivalent to "The C > Programming language" by Kernighan and Richie which is the best text on > programming i have ever read. > This post: http://stackoverflow.com/questions/947942/advanced-python-programming-book-like-effective-c has several books. I've heard that Wesley Chun's book (who also happens to contribute here every so often ;) Core Python Programming is a great one. I'm a big tutorial reader - reading tutorials with plenty of examples is how I learn best - I've done a lot of eBooks. One great resource that surprisingly few people mention (mainly because it's "for kids" - that just means it's a lot more entertaining :) is Snake Wrangling for Kids: http://www.briggs.net.nz/log/writing/snake-wrangling-for-kids/ It covers all the basic stuff that's easy to blitz through if you're familiar with programming, and then towards the end it gets a little into programming with Tkinter. Anyhow, HTH, good luck, and welcome! If you get stuck, there are plenty of people here willing to help (which you may find par for the course when dealing with Pythonistas). -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From adam.jtm30 at gmail.com Fri Aug 13 22:38:20 2010 From: adam.jtm30 at gmail.com (Adam Bark) Date: Fri, 13 Aug 2010 21:38:20 +0100 Subject: [Tutor] Lost in the control flow In-Reply-To: References: <4C61AEED.3090808@gmail.com> Message-ID: <4C65AD3C.5080108@gmail.com> On 11/08/10 18:14, Eduardo Vieira wrote: > On Tue, Aug 10, 2010 at 1:56 PM, Adam Bark wrote: > > >> The problem is you don't call make_dict unless there's a "FUEL SURCHARGE" or >> multiple pins. Also you don't add the first pin to mydict["tracking"] unless >> there's a "FUEL SURCHARGE". >> >> HTH, >> Adam. >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> >> > Hi, I made these changes, got rid of the functions, and changed some logic: > here is the link: http://pastebin.com/F19vKUjr > > Now mydict will be changing, of course with every loop, as the output below: > {'company': 'CITY SIGNS', 'tracking': ['600775301143'], 'id': '1'} > {'city': 'MEDICINE HAT', 'company': 'CITY SIGNS', 'tracking': > ['600775301143'], 'id': '1', 'prov': 'AB'} > {'city': 'MEDICINE HAT', 'company': 'TRIMLINE', 'tracking': > ['600775301150'], 'id': '2', 'prov': 'AB'} > {'city': 'ROCKY MOUNTAIN HOUSE', 'company': 'TRIMLINE', 'tracking': > ['600775301150'], 'id': '2', 'prov': 'AB'} > {'city': 'ROCKY MOUNTAIN HOUSE', 'company': 'TS SIGNS PRINTING& > PROMO', 'tracking': ['600775301168'], 'id': '3', 'prov': 'AB'} > {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING& PROMO', > 'tracking': ['600775301168'], 'id': '3', 'prov': 'AB'} > {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING& PROMO', > 'tracking': ['600775301168', '600775301168'], 'id': '3', 'prov': 'AB'} > {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING& PROMO', > 'tracking': ['600775301168', '600775301168', '600775301176'], 'id': > '3', 'prov': 'AB'} > {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING& PROMO', > 'tracking': ['600775301168', '600775301168', '600775301176', > '600775301184'], 'id': '3', 'prov': 'AB'} > {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING& PROMO', > 'tracking': ['600775301168', '600775301168', '600775301176', > '600775301184', '600775301192'], 'id': '3', 'prov': 'AB'} > {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING& PROMO', > 'tracking': ['600775301168', '600775301168', '600775301176', > '600775301184', '600775301192', '600775301200'], 'id': '3', 'prov': > 'AB'} > so I appended everything to a bigdata list and used it to update the > dictionary data_dict > > I can't understand why I get only one value: > {'18': {'city': 'ESTEVAN', > 'company': 'BRAKE& DRIVE SYSTEMS', > 'id': '18', > 'prov': 'SK', > 'tracking': ['600775301515', '600775301515', '600775301523']}} > > Regards, > > Eduardo > It looks to me like you keep overwriting the previous data, you keep using mydict. Doing an append does not copy the dictionary it just copies a reference to the underlying data structure. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sudarshana.b at gmail.com Sat Aug 14 04:01:02 2010 From: sudarshana.b at gmail.com (Sudarshana Banerjee) Date: Fri, 13 Aug 2010 19:01:02 -0700 Subject: [Tutor] elif statement In-Reply-To: References: <4C62050D.80307@gmail.com> Message-ID: Hi Alan: Yay! I pressed Enter after the print, and then delete. Which brought the cursor back to the starting position at the beginning of the line, and no more elif syntax errors. This is good to know. Thank you very much. I also took the liberty of checking out your computing website. It is really helpful; and I have added it to my bookmarks. Thanks a ton! Sudarshana. On Fri, Aug 13, 2010 at 1:27 AM, Alan Gauld wrote: > > "Sudarshana Banerjee" wrote > > > Could you take a look at this please: >> >>> x=3 >>>>> if x==0: >>>>> >>>> print "x is 0" >> >> elif x&1==1: >>>>> >>>> SyntaxError: invalid syntax >> >> See, the moment I am pressing Enter the >>> is coming.. not ... >> > > IDLE doesn't give you a ... prompt it gives you spaces. > So you mistake is that ypu are hitting Enter after your print line. It > needs to look like: > > > x=3 >>>> if x==0: >>>> >>> print "x is 0" > elif x&1==1: > print.... > > Which looks horrible and I wish Idle were fixed so it didn't do this. > I keep meaning to try and find a way to patch it myself! > > > Essentially you need to ignore the >>> offset in the if line. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Aug 14 11:08:30 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 14 Aug 2010 09:08:30 +0000 (GMT) Subject: [Tutor] is it possible to call a setter property during classinstantiation? In-Reply-To: References: Message-ID: <353222.32605.qm@web86704.mail.ird.yahoo.com> so we don't usually care too much about types. Are you sure you >>really need all that type checking code? ...I included a type check for a string to make sure that a future programmer (or myself) wouldn't try to pass in a list of lines after a text has been split. Other code internal to the Question class depends on the fact that the incoming data arrives in the form of a single string. Does it really? If so that suggfgests it will call a method that is unique to strings? If so an exception will be thrown that you can catch. but if your methods don't use methods that are unique to strings could you generalise them to be applicable to any sequence type - including a user defined class that looks like a string but is not derived from string? If the wrong data type is fed, then I have a custom exception that gets raised >to specify the problem. I guess the program would just crash with a >TypeError if a list of lines was fed rather than a string, >Or you catch the error where the method really needs a string rather than trying > to predict the possibility in the init method. Of course this might mean many duplicated try/except clauses which might mess yopur code up just aws much. So its a trade off. LBYL v EAFP (try Google :-) Is it better in such cases to just let the program die a natural death, >Or catch the error where it occurs and take remedial action. Would converting to a string work? (Usually not because almost anything in Python returns a value from str() even if only a description of type!) Is there a better way to approach these issues? >If you know which methods might be missing it can be more effective to check for their existence rather than checking for an explicit type. Thus code can check for a "file like object" by testing that the subset of file operations they need are present. This can often be combined with binding the methods to local variables for a slight performance improvement: def f(aFile): try: # we need to use read and close methods of the input object _read = aFile.read _close = aFile.close except AttributeError: raise TypeError data = _read() process(data) _close() I'm not saying its never necessary to check types but its a lot less necessary than in static languages, especially if you try to write functions that can operate on the widest set of data types possible and guard against missing operations rather than "incorrect" types. HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From squirrox at gmail.com Sat Aug 14 11:29:49 2010 From: squirrox at gmail.com (Stephen Farthing) Date: Sat, 14 Aug 2010 10:29:49 +0100 Subject: [Tutor] Tutor Digest, Vol 78, Issue 68 In-Reply-To: References: Message-ID: Guys, Thanks for all the help....I am working my way through "Snake wrangling for kids" as a start. I downloaded Netbeans and installed the plug in as Idle will not load on my 64 bit Windows 7. And I have WXPython 2.8 plus the examples to play with. Life is good in rainy England, Steve -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Sat Aug 14 15:54:07 2010 From: wallenpb at gmail.com (Bill Allen) Date: Sat, 14 Aug 2010 08:54:07 -0500 Subject: [Tutor] Tutor Digest, Vol 78, Issue 68 In-Reply-To: References: Message-ID: On Sat, Aug 14, 2010 at 4:29 AM, Stephen Farthing wrote: > > Thanks for all the help....I am working my way through "Snake wrangling for > kids" as a start. I downloaded Netbeans and installed the plug in as Idle > will not load on my 64 bit Windows 7. And I have WXPython 2.8 plus the > examples to play with. > > Life is good in rainy England, > > Steve > > I also want to express my thanks for the help that I have received here on Tutor. My "practice program" is rapidly advancing now and I am having lots of fun learning Python. I have not enjoyed programming this much since I had to figure out how to write my own graphics primitives in x86 Assembler for an old IBM XT with a Hercules hires graphics card (very ancient home PC tech) in order to write a program for generating Madelbrot fractals. (Yes that was fun!) Thanks again! Burning up in 100+ temps in Texas, Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Sun Aug 15 01:17:34 2010 From: wallenpb at gmail.com (Bill Allen) Date: Sat, 14 Aug 2010 18:17:34 -0500 Subject: [Tutor] my Python learning exercise Message-ID: In the process of learning Python, I have given myself a programming exercise to do. This is a standard thing I do whenever learning a new programming language and I have used this same exercise several times before with other programming languages. It is a simple text based game that simply lets a user explore a maze of rooms. If fully fleshed out, it would be a Zork or D&D type game. It demonstrates some basic programming tasks such as reading data into an array from a file, getting and responding to user input, looping, control structures, system calls and function definitions. I share it here as example code for others also learning Python and I welcome comments. The code is for Python 3.x, but the comments explain how to easily convert it for use in Python 2.x. It is far from perfect and is for learning purposes only ? something to tinker with. It is based on concepts from Creating Adventure Games on Your Computer by Tim Hartnell , which used the BASIC programming language. You are welcome to take this code and use and modify for any purpose you like. The current version of this code will always be at this location: mazegame-current. You can create an appropriate data file by making a text file with contents similar to the following, the current code requires a fixed number of columns (7 at the time of this writing and subject to change) and an unlimited number of rows. 0 0 0 0 0 0 0 0 0 4 2 0 0 0 0 0 0 1 3 6 0 0 0 5 0 2 0 0 0 1 0 5 0 0 0 0 3 0 0 4 0 7 0 0 0 0 0 0 2 0 0 0 0 0 5 0 -------------- next part -------------- An HTML attachment was scrubbed... URL: From augdawg09 at gmail.com Mon Aug 16 00:20:15 2010 From: augdawg09 at gmail.com (aug dawg) Date: Sun, 15 Aug 2010 18:20:15 -0400 Subject: [Tutor] Parsing RSS Feeds Message-ID: Hey all, Does anyone know of any modules to help my program parse RSS feeds? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Aug 16 01:02:07 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 16 Aug 2010 09:02:07 +1000 Subject: [Tutor] Parsing RSS Feeds In-Reply-To: References: Message-ID: <201008160902.08616.steve@pearwood.info> On Mon, 16 Aug 2010 08:20:15 am aug dawg wrote: > Hey all, > > Does anyone know of any modules to help my program parse RSS feeds? Yes, many people know of modules to parse RSS feeds. If you google for "Python RSS feed" you will find them. -- Steven D'Aprano From nitin.162 at gmail.com Mon Aug 16 05:04:59 2010 From: nitin.162 at gmail.com (Nitin Das) Date: Mon, 16 Aug 2010 08:34:59 +0530 Subject: [Tutor] Parsing RSS Feeds In-Reply-To: References: Message-ID: http://www.feedparser.org/ --nitin On Mon, Aug 16, 2010 at 3:50 AM, aug dawg wrote: > Hey all, > > Does anyone know of any modules to help my program parse RSS feeds? > > Thanks! > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.serrato at gmail.com Mon Aug 16 05:51:39 2010 From: benjamin.serrato at gmail.com (Benjamin Serrato) Date: Sun, 15 Aug 2010 22:51:39 -0500 Subject: [Tutor] Schema change in ElementTree Message-ID: Hi guys, thanks for you help in the past. I had my first occasion to write a useful script recently editing the contents of an xml file. It was pretty simple, but I have two problems which I know have to take care of by opening in Notepad++ and changing manually. 1. The file output has LF not CRLF as the newline character. I'm not sure if this matters, but this is on windows and I'm having trouble reimporting this file back into the program it belongs to. I'd like to change how it outputs newlines, or use python to automatically fix the .xml file. 2. Before parsing the file 'xs' is the schema prefix, but after writing 'ns0' is the schema prefix (e.g. to ), but this doesn't carry over to the attributes so I'm left with (... types="xs:int"). That doesn't make any sense. I've the documentation at effbot, but didn't see anything outright I needed to redefine the schema before writing to disk. Also, is it possible to define the order of the schema attributes? dpaste of the code for the curious: http://dpaste.de/Eebo/ Benjamin Serrato 682.472.8650 -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Mon Aug 16 08:11:54 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 16 Aug 2010 08:11:54 +0200 Subject: [Tutor] Schema change in ElementTree In-Reply-To: References: Message-ID: Benjamin Serrato, 16.08.2010 05:51: > Hi guys, thanks for you help in the past. I had my first occasion to write > a useful script recently editing the contents of an xml file. It was pretty > simple, but I have two problems which I know have to take care of by opening > in Notepad++ and changing manually. > > 1. The file output has LF not CRLF as the newline character. I'm not sure > if this matters, but this is on windows and I'm having trouble reimporting > this file back into the program it belongs to. Sounds like the program is not really expecting XML. XML is newline character agnostic and parsers will normalise it to plain CR. > I'd like to change how it > outputs newlines, or use python to automatically fix the .xml file. You didn't say where the newline characters occur. Do you pretty print the file on output? ElementTree doesn't have a way of formatting (pretty printing) XML files, so there can't be that many newline characters in the structure (they may be in the occur, though!). There's a pretty printing recipe on the effbot site that you can easily adapt to inject the newline characters you need. > 2. Before parsing the file 'xs' is the schema prefix, but after writing > 'ns0' is the schema prefix (e.g. to), but > this doesn't carry over to the attributes so I'm left with (... > types="xs:int"). That doesn't make any sense. I've the documentation at > effbot, but didn't see anything outright I needed to redefine the schema > before writing to disk. Yes, that's a known problem with ET - it doesn't keep namespace prefixes end-to-end. In case you are using Python 2.7 (or ET 1.3), you can globally assign a specific prefix to a namespace URI, though. That way, ET can output your 'xs' prefix for the namespace at hand. > Also, is it possible to define the order of the > schema attributes? Not sure what you mean here. If you are talking about the namespace declarations, then no, these are XML attributes which are not ordered. The only way to get a deterministic output order is canonical (C14N) serialisation. That's also supported by ET since 1.3. Stefan From knacktus at googlemail.com Mon Aug 16 09:01:58 2010 From: knacktus at googlemail.com (Knacktus) Date: Mon, 16 Aug 2010 09:01:58 +0200 Subject: [Tutor] Multiple inheritance for mixin attributes Message-ID: <4C68E266.20104@googlemail.com> Hello everyone, I've got a question about class design. I want to model classes like these (examples): ##################################################################### class BaseItem(object): def __init__(self, ident, name, description): self.ident = ident self.name = name self.description = description class DataSourceItem(object): def __init__(self, ident, name, description, data_source): self.ident = ident self.name = name self.description = description self.data_source = data_source class BaseItemCollection(list): def __init__(self, ident, name, description): self.ident = ident self.name = name self.description = description def default_version(self): return self[-1] class BaseDataSourceItemCollection(list): def __init__(self, ident, name, description, data_source): self.ident = ident self.name = name self.description = description self.data_source = data_source def default_version(self): return self[-1] ####################################################################### Now, to remove all the duplicated code I could use inheritance. But that would lead to multiple inheritance and the question how to initialise both superclasses? I would appreciate some advice about how to model classes like this. Personaly, I don't have to use inheritance, but I have no better idea. Would you accept at least some duplication to avoid multiple inheritance? Thanks in advance, Jan From alan.gauld at btinternet.com Mon Aug 16 10:05:27 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 Aug 2010 09:05:27 +0100 Subject: [Tutor] Multiple inheritance for mixin attributes References: <4C68E266.20104@googlemail.com> Message-ID: "Knacktus" wrote > I've got a question about class design. I want to model classes like > these (examples): Since these only really have data and inheritance should be based on behaviour its almost impossible to make a meaningful decision on what the inheritance tree should look like. However... > ##################################################################### > class BaseItem(object): > > def __init__(self, ident, name, description): > self.ident = ident > self.name = name > self.description = description > > class DataSourceItem(object): > > def __init__(self, ident, name, description, data_source): > self.ident = ident > self.name = name > self.description = description > self.data_source = data_source Surely the DataSourceItem could inherit BaseItem? They are both types of Item... class DataSourceItem(BaseItem): def __init__(self,ident, name, description, data_source): BaseItem.__init__(self,ident, name, description) # or use super()... self.data_source = data_source > class BaseItemCollection(list): > > def __init__(self, ident, name, description): > self.ident = ident > self.name = name > self.description = description > > def default_version(self): > return self[-1] > > class BaseDataSourceItemCollection(list): And the same here - Make the DataSourceItemCollection inherit from ItemCollection since they are both ItemCollections... > Now, to remove all the duplicated code I could use inheritance. But > that would lead to multiple inheritance and the question how to > initialise both superclasses? Why would it lead to multiple inheritance? There seem to be two different types of things - Items and collections. Inheritance is not a code saving tool but an Is-A relationship that enables polymorphism. Do not use inherirtance just to save code - its nearly always a bad idea. Although lots of duplicated code - especially methods - often suggest that an Is-A relationship exists... > I would appreciate some advice about how to model classes like this. > Personaly, I don't have to use inheritance, but I have no better > idea. Would you accept at least some duplication to avoid multiple > inheritance? Duplication is irerelevant. But I would not do anything to "avoid multiple inheritance" if MI was appropriate. MI is a very effective and powerful tool. It is not something to be avoided just in principle. But you very rarely need it in Python in practice. Few things are genuinely of two such different types that dynamic duck-typing can't deal with it without MI. But don't use inheritance just to avoid duplicating code, use delegation for that. FWIW I've worked on projects using MI with a single class inheriting 7 parent classes, if done properly and deliberately MI is nothing to worry about. The problems only occur when MI is abused and not designed IMHO -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From zebra05 at gmail.com Mon Aug 16 10:10:47 2010 From: zebra05 at gmail.com (Sithembewena Lloyd Dube) Date: Mon, 16 Aug 2010 10:10:47 +0200 Subject: [Tutor] Using Django with TortoiseSVN (overwriting files) Message-ID: Hi everyone, We have a project at work where myself and a co-developer are setting up Django. Our version control software of choice is TortoiseSVN. When doing a project update from SVN, it pulls the server version to the local project. When checking code in, it overwrites the server version of the code as expected. I wish to find out whether Django would work happily this way, as it requires one to use the django-admin.py tool to create projects and apps. Would overwriting these files/ directories with server versions compromise their integrity in a Django setup? -- Regards, Sithembewena Lloyd Dube http://www.lloyddube.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From knacktus at googlemail.com Mon Aug 16 10:21:35 2010 From: knacktus at googlemail.com (Jan Jansen) Date: Mon, 16 Aug 2010 10:21:35 +0200 Subject: [Tutor] Multiple inheritance for mixin attributes In-Reply-To: References: <4C68E266.20104@googlemail.com> Message-ID: Thanks a lot, your explanations are very helpful getting a better (right) understanding about the ideas behind inheritance. Cheers, Jan -------------- next part -------------- An HTML attachment was scrubbed... URL: From justin.mailinglists at gmail.com Mon Aug 16 10:38:11 2010 From: justin.mailinglists at gmail.com (justin.mailinglists at gmail.com) Date: Mon, 16 Aug 2010 08:38:11 +0000 Subject: [Tutor] Schema change in ElementTree Message-ID: <0016364c654fb8aac2048decc07a@google.com> # so that ET preserves your namespaces ET._namespace_map["http://www.w3.org/2001/XMLSchema"] = 'xs' # open your file explicitly specifying the correct mode f = open('testing.xml', 'w') xml_tree.write(f, encoding='UTF-8') f.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Mon Aug 16 10:54:38 2010 From: evert.rol at gmail.com (Evert Rol) Date: Mon, 16 Aug 2010 10:54:38 +0200 Subject: [Tutor] Using Django with TortoiseSVN (overwriting files) In-Reply-To: References: Message-ID: <6D8D9F4C-DEF3-4507-A1C5-F009C3D47ECB@gmail.com> > We have a project at work where myself and a co-developer are setting up Django. Our version control software of choice is TortoiseSVN. > > When doing a project update from SVN, it pulls the server version to the local project. When checking code in, it overwrites the server version of the code as expected. > > I wish to find out whether Django would work happily this way, as it requires one to use the django-admin.py tool to create projects and apps. Would overwriting these files/ directories with server versions compromise their integrity in a Django setup? That's not a Python question, more a Django question or a system-admin question. You'd be better off using the correct mailing list for that. That said, you should be fine, providing you re-sync the databases every time you 'svn up', to keep your model schema's in the database in sync (you can use fixtures to sync data in the database). Also the settings files may differ on the server or the local machines; it's best to keep those out of SVN, or have a little if-else clause in settings.py that takes care server-dependent settings. Otherwise, all your code can (and should) be machine/server agnostic, and thus easily transportable. Evert From stefan_ml at behnel.de Mon Aug 16 11:20:06 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 16 Aug 2010 11:20:06 +0200 Subject: [Tutor] Schema change in ElementTree In-Reply-To: <0016364c654fb8aac2048decc07a@google.com> References: <0016364c654fb8aac2048decc07a@google.com> Message-ID: justin.mailinglists at gmail.com, 16.08.2010 10:38: > # so that ET preserves your namespaces > ET._namespace_map["http://www.w3.org/2001/XMLSchema"] = 'xs' > > # open your file explicitly specifying the correct mode > f = open('testing.xml', 'w') > xml_tree.write(f, encoding='UTF-8') > f.close() Note that it's best to hit "reply" when responding to other people's postings. That way, mail readers can see the relation between the original posting and the reply and sort the reply into the right thread. Stefan From zebra05 at gmail.com Mon Aug 16 12:39:34 2010 From: zebra05 at gmail.com (Sithembewena Lloyd Dube) Date: Mon, 16 Aug 2010 12:39:34 +0200 Subject: [Tutor] Using Django with TortoiseSVN (overwriting files) In-Reply-To: <6D8D9F4C-DEF3-4507-A1C5-F009C3D47ECB@gmail.com> References: <6D8D9F4C-DEF3-4507-A1C5-F009C3D47ECB@gmail.com> Message-ID: Hi Evert, You are right, I actually intended the question for the Django list - it was a posting error. Thanks for the answer, we did soon figure out to exclude the settings file from any SVN checkins/ checkouts. We will simply apply this rule as it should be simple enough to observe and to make any corrections if a team member overwrites it. Many thanks, Lloyd On Mon, Aug 16, 2010 at 10:54 AM, Evert Rol wrote: > > We have a project at work where myself and a co-developer are setting up > Django. Our version control software of choice is TortoiseSVN. > > > > When doing a project update from SVN, it pulls the server version to the > local project. When checking code in, it overwrites the server version of > the code as expected. > > > > I wish to find out whether Django would work happily this way, as it > requires one to use the django-admin.py tool to create projects and apps. > Would overwriting these files/ directories with server versions compromise > their integrity in a Django setup? > > That's not a Python question, more a Django question or a system-admin > question. You'd be better off using the correct mailing list for that. > > That said, you should be fine, providing you re-sync the databases every > time you 'svn up', to keep your model schema's in the database in sync (you > can use fixtures to sync data in the database). Also the settings files may > differ on the server or the local machines; it's best to keep those out of > SVN, or have a little if-else clause in settings.py that takes care > server-dependent settings. > Otherwise, all your code can (and should) be machine/server agnostic, and > thus easily transportable. > > Evert > > > -- Regards, Sithembewena Lloyd Dube http://www.lloyddube.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Aug 16 13:01:53 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 16 Aug 2010 21:01:53 +1000 Subject: [Tutor] Multiple inheritance for mixin attributes In-Reply-To: <4C68E266.20104@googlemail.com> References: <4C68E266.20104@googlemail.com> Message-ID: <201008162101.54431.steve@pearwood.info> On Mon, 16 Aug 2010 05:01:58 pm Knacktus wrote: > Hello everyone, > > I've got a question about class design. I want to model classes like > these (examples): > > ##################################################################### > class BaseItem(object): > def __init__(self, ident, name, description): > self.ident = ident > self.name = name > self.description = description > > class DataSourceItem(object): > def __init__(self, ident, name, description, data_source): > self.ident = ident > self.name = name > self.description = description > self.data_source = data_source That's a clear job for single inheritance: class DataSourceItem(BaseItem): def __init__(self, ident, name, description, data_source): BaseItem.__init__(self, ident, name, description) self.data_source = data_source Note: there's a BIG question mark as to whether you should use super() or not when inheriting methods. I've previously defended the use of super() even in single-inheritance classes, where it is not strictly necessary but does no harm. However in this case, the function signature of DataSourceItem and BaseItem are different, which is a clear signal *not* to use super(). But if you're brave, here's a version that uses super(): class DataSourceItem(BaseItem): def __init__(self, ident, name, description, data_source): super(DataSourceItem, self).__init__(ident, name, description) self.data_source = data_source Is this safe? Well, probably, for the simple class hierarchy you enter. But if you extend the class hierarchy with more sibling and child classes, perhaps not. > class BaseItemCollection(list): > def __init__(self, ident, name, description): > self.ident = ident > self.name = name > self.description = description > def default_version(self): > return self[-1] That's a clear job for composition: class BaseItemCollection(list): def __init__(self, ident, name, description): self.data = BaseItem(ident, name, description) def default_version(self): return self[-1] > class BaseDataSourceItemCollection(list): > def __init__(self, ident, name, description, data_source): > self.ident = ident > self.name = name > self.description = description > self.data_source = data_source > def default_version(self): > return self[-1] This one isn't clear. You could inherit either directly from list: class BaseDataSourceItemCollection(list): def __init__(self, ident, name, description, data_source): self.data = DataSourceItem( ident, name, description, data_source) def default_version(self): return self[-1] or from BaseItemCollection: class BaseDataSourceItemCollection(BaseItemCollection): def __init__(self, ident, name, description, data_source): BaseItemCollection.__init__(self, ident, name, description) self.data_source = data_source Which such trivially small classes, there's no real advantage or disadvantage to either. Of course, you could use multiple inheritance, but that opens a whole rat's nest of difficulties. Even though Python makes it easy to implement multiple-inheritance, it is full of pitfalls for the unwary, and even the wary, so you should always consider whether you *really* need it. Other alternatives are traits and generic functions: http://www.artima.com/weblogs/viewpost.jsp?thread=246488 http://www.artima.com/weblogs/viewpost.jsp?thread=237764 Lastly, I should mention automatic delegation as an alternative to inheritance. It's not clear to me that this would be either useful or necessary for your classes, but I'll mention it so you can google for more information if you are interested. -- Steven D'Aprano From rabidpoobear at gmail.com Mon Aug 16 16:25:03 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 16 Aug 2010 09:25:03 -0500 Subject: [Tutor] my Python learning exercise In-Reply-To: References: Message-ID: On Sat, Aug 14, 2010 at 6:17 PM, Bill Allen wrote: > In the process of learning Python, I have given myself a programming > exercise to do.? This is a standard thing I do whenever learning a new > programming language and I have used this same exercise several times before > with other programming languages.? It is a simple text based game that > simply lets a user explore a maze of rooms. Anyone who finds this interesting may also want to look into http://inventwithpython.com/ , I hear it's a good book but I haven't personally worked through it. -Luke From sierra_mtnview at sbcglobal.net Mon Aug 16 17:39:45 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 16 Aug 2010 08:39:45 -0700 Subject: [Tutor] Moving from Python 2.5.4 to 2.5.2? Message-ID: <4C695BC1.8010402@sbcglobal.net> My partner got ahead of the game last year, and installed 2.5.4, which confounds matters when the other four participants when sharing some python programs under Win XP. My guess is that if he uses control panel add/remove for py 2.5.4, he can then successfully install 2.5.2 w/o messing up any programs I've sent him. I'm presuming he did not put them under c:\Python. -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "An experiment is a question which science poses to Nature, and a measurement is the recording of Nature?s answer." -- Max Planck Web Page: From rabidpoobear at gmail.com Mon Aug 16 17:58:43 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 16 Aug 2010 10:58:43 -0500 Subject: [Tutor] Moving from Python 2.5.4 to 2.5.2? In-Reply-To: <4C695BC1.8010402@sbcglobal.net> References: <4C695BC1.8010402@sbcglobal.net> Message-ID: On Mon, Aug 16, 2010 at 10:39 AM, Wayne Watson wrote: > My partner got ahead of the game last year, and installed 2.5.4, which > confounds matters when the other four participants when sharing some python > programs under Win XP. My guess is that if he uses control panel add/remove > for py 2.5.4, he can then successfully install 2.5.2 w/o messing up any > programs I've sent him. I'm presuming he did not put them under c:\Python. Is this a question or a statement? Not really sure what you're looking to get out of this. Why would 2.5.4 cause issues with 2.5.2? Why don't you all just upgrade to 2.5.4? -Luke From guillaume_chorn at merck.com Mon Aug 16 19:44:33 2010 From: guillaume_chorn at merck.com (Chorn, Guillaume) Date: Mon, 16 Aug 2010 13:44:33 -0400 Subject: [Tutor] Question about Dictionaries Message-ID: <3149FC764D12D24DA307F9DA7248176401E17FDD@usctmx1158.merck.com> Hi All, I know that I can look up the value for a particular key in a dictionary, but can I look up the key associated with a particular value? I understand that this could be problematic from the standpoint of multiple keys having the same value, but even then I feel like Python could just return a list of keys with that value. Thanks! Guillaume Notice: This e-mail message, together with any attachments, contains information of Merck & Co., Inc. (One Merck Drive, Whitehouse Station, New Jersey, USA 08889), and/or its affiliates Direct contact information for affiliates is available at http://www.merck.com/contact/contacts.html) that may be confidential, proprietary copyrighted and/or legally privileged. It is intended solely for the use of the individual or entity named on this message. If you are not the intended recipient, and have received this message in error, please notify us immediately by reply e-mail and then delete it from your system. -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Mon Aug 16 21:24:20 2010 From: emile at fenx.com (Emile van Sebille) Date: Mon, 16 Aug 2010 12:24:20 -0700 Subject: [Tutor] Question about Dictionaries In-Reply-To: <3149FC764D12D24DA307F9DA7248176401E17FDD@usctmx1158.merck.com> References: <3149FC764D12D24DA307F9DA7248176401E17FDD@usctmx1158.merck.com> Message-ID: On 8/16/2010 10:44 AM Chorn, Guillaume said... > Hi All, > > I know that I can look up the value for a particular key in a > dictionary, but can I look up the key associated with a particular > value? Yes. But you'll need to implement it. There are likely modules out there that'll do this, but it'd take more time to look up and evaluate than to simply write and implement exactly what you need. > I understand that this could be problematic from the standpoint > of multiple keys having the same value, but even then I feel like Python > could just return a list of keys with that value. > So, in untested code you'd have a function something like: result = [] for ky, val in dict.items(): if val == targetval: result.append(ky) return result If you need repeated access such that iterating over a large dict frequently impacts performance, you could subclass dict and maintain a second index allowing instant access to the keys associated with a specific value. HTH, Emile From sierra_mtnview at sbcglobal.net Mon Aug 16 22:57:37 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 16 Aug 2010 13:57:37 -0700 Subject: [Tutor] Moving from Python 2.5.4 to 2.5.2? In-Reply-To: References: <4C695BC1.8010402@sbcglobal.net> Message-ID: <4C69A641.20105@sbcglobal.net> The question is would going back likely cause problems? I'm dealing with neophytes. He's messed up before. On 8/16/2010 8:58 AM, Luke Paireepinart wrote: > On Mon, Aug 16, 2010 at 10:39 AM, Wayne Watson > wrote: > >> My partner got ahead of the game last year, and installed 2.5.4, which >> confounds matters when the other four participants when sharing some python >> programs under Win XP. My guess is that if he uses control panel add/remove >> for py 2.5.4, he can then successfully install 2.5.2 w/o messing up any >> programs I've sent him. I'm presuming he did not put them under c:\Python. >> > Is this a question or a statement? Not really sure what you're > looking to get out of this. > > Why would 2.5.4 cause issues with 2.5.2? Why don't you all just > upgrade to 2.5.4? > > -Luke > > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "An experiment is a question which science poses to Nature, and a measurement is the recording of Nature?s answer." -- Max Planck Web Page: From missive at hotmail.com Mon Aug 16 23:22:16 2010 From: missive at hotmail.com (Lee Harr) Date: Tue, 17 Aug 2010 01:52:16 +0430 Subject: [Tutor] Question about Dictionaries Message-ID: > I know that I can look up the value for a particular key in a > dictionary, but can I look up the key associated with a particular > value? I am using bidict in one of my projects: http://pypi.python.org/pypi/bidict/0.1.1 It's probably a bit more complex than what I need, but the parts I am using are working fine, and the design of the extra features is kind of interesting. I think something like this should be in the stdlib, but there is some controversy about how exactly it should work. From rabidpoobear at gmail.com Mon Aug 16 23:41:37 2010 From: rabidpoobear at gmail.com (Luke Paireepinart) Date: Mon, 16 Aug 2010 16:41:37 -0500 Subject: [Tutor] Moving from Python 2.5.4 to 2.5.2? In-Reply-To: <4C69A641.20105@sbcglobal.net> References: <4C695BC1.8010402@sbcglobal.net> <4C69A641.20105@sbcglobal.net> Message-ID: The core issue here is: are there actually issues exacerbated by the difference in Python versions? If so, which issues? There shouldn't be hardly any reason to force you all to maintain the exact same python version, especially if you're in the same sub-version (2.5) On Mon, Aug 16, 2010 at 3:57 PM, Wayne Watson wrote: > The question is would going back likely cause problems? I'm dealing with > neophytes. He's messed up before. > > On 8/16/2010 8:58 AM, Luke Paireepinart wrote: >> >> On Mon, Aug 16, 2010 at 10:39 AM, Wayne Watson >> ?wrote: >> >>> >>> My partner got ahead of the game last year, and installed 2.5.4, which >>> confounds matters when the other four participants when sharing some >>> python >>> programs under Win XP. My guess is that if he uses control panel >>> add/remove >>> for py 2.5.4, he can then successfully install 2.5.2 w/o messing up any >>> programs I've sent him. I'm presuming he did not put them under >>> c:\Python. >>> >> >> Is this a question or a statement? ?Not really sure what you're >> looking to get out of this. >> >> Why would 2.5.4 cause issues with 2.5.2? ?Why don't you all just >> upgrade to 2.5.4? >> >> -Luke >> >> > > -- > ? ? ? ? ? Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > ? ? ? ? ? ? (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) > ? ? ? ? ? ? ?Obz Site: ?39? 15' 7" N, 121? 2' 32" W, 2700 feet > > ? ? ? ? ? ?"An experiment is a question which science poses to > ? ? ? ? ? ? Nature, and a measurement is the recording of > ? ? ? ? ? ? Nature?s answer." -- Max Planck > > > ? ? ? ? ? ? ? ? ? ?Web Page: > > From eduardo.susan at gmail.com Mon Aug 16 23:49:06 2010 From: eduardo.susan at gmail.com (Eduardo Vieira) Date: Mon, 16 Aug 2010 15:49:06 -0600 Subject: [Tutor] Lost in the control flow In-Reply-To: <4C65AD3C.5080108@gmail.com> References: <4C61AEED.3090808@gmail.com> <4C65AD3C.5080108@gmail.com> Message-ID: On Fri, Aug 13, 2010 at 2:38 PM, Adam Bark wrote: > On 11/08/10 18:14, Eduardo Vieira wrote: > > On Tue, Aug 10, 2010 at 1:56 PM, Adam Bark wrote: > > > > The problem is you don't call make_dict unless there's a "FUEL SURCHARGE" or > multiple pins. Also you don't add the first pin to mydict["tracking"] unless > there's a "FUEL SURCHARGE". > > HTH, > Adam. > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > > > Hi, I made these changes, got rid of the functions, and changed some logic: > here is the link: http://pastebin.com/F19vKUjr > > Now mydict will be changing, of course with every loop, as the output below: > {'company': 'CITY SIGNS', 'tracking': ['600775301143'], 'id': '1'} > {'city': 'MEDICINE HAT', 'company': 'CITY SIGNS', 'tracking': > ['600775301143'], 'id': '1', 'prov': 'AB'} > {'city': 'MEDICINE HAT', 'company': 'TRIMLINE', 'tracking': > ['600775301150'], 'id': '2', 'prov': 'AB'} > {'city': 'ROCKY MOUNTAIN HOUSE', 'company': 'TRIMLINE', 'tracking': > ['600775301150'], 'id': '2', 'prov': 'AB'} > {'city': 'ROCKY MOUNTAIN HOUSE', 'company': 'TS SIGNS PRINTING & > PROMO', 'tracking': ['600775301168'], 'id': '3', 'prov': 'AB'} > {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', > 'tracking': ['600775301168'], 'id': '3', 'prov': 'AB'} > {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', > 'tracking': ['600775301168', '600775301168'], 'id': '3', 'prov': 'AB'} > {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', > 'tracking': ['600775301168', '600775301168', '600775301176'], 'id': > '3', 'prov': 'AB'} > {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', > 'tracking': ['600775301168', '600775301168', '600775301176', > '600775301184'], 'id': '3', 'prov': 'AB'} > {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', > 'tracking': ['600775301168', '600775301168', '600775301176', > '600775301184', '600775301192'], 'id': '3', 'prov': 'AB'} > {'city': 'FORT MCMURRAY', 'company': 'TS SIGNS PRINTING & PROMO', > 'tracking': ['600775301168', '600775301168', '600775301176', > '600775301184', '600775301192', '600775301200'], 'id': '3', 'prov': > 'AB'} > so I appended everything to a bigdata list and used it to update the > dictionary data_dict > > I can't understand why I get only one value: > {'18': {'city': 'ESTEVAN', > 'company': 'BRAKE & DRIVE SYSTEMS', > 'id': '18', > 'prov': 'SK', > 'tracking': ['600775301515', '600775301515', '600775301523']}} > > Regards, > > Eduardo > > > It looks to me like you keep overwriting the previous data, you keep using > mydict. Doing an append does not copy the dictionary it just copies a > reference to the underlying data structure. > Thank you, Adam. That was the problem. By using deepcopy I managed to fix it: final = deepcopy(mydict) Cheers, Eduardo From sierra_mtnview at sbcglobal.net Mon Aug 16 23:56:23 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 16 Aug 2010 14:56:23 -0700 Subject: [Tutor] Moving from Python 2.5.4 to 2.5.2? In-Reply-To: References: <4C695BC1.8010402@sbcglobal.net> <4C69A641.20105@sbcglobal.net> Message-ID: <4C69B407.7010304@sbcglobal.net> I guess it's a matter of bookkeeping. I don't need the extra hassle dealing with one of them. I'll just let it go at 2.5.x On 8/16/2010 2:41 PM, Luke Paireepinart wrote: > The core issue here is: are there actually issues exacerbated by the > difference in Python versions? If so, which issues? There shouldn't > be hardly any reason to force you all to maintain the exact same > python version, especially if you're in the same sub-version (2.5) > > On Mon, Aug 16, 2010 at 3:57 PM, Wayne Watson > wrote: > >> The question is would going back likely cause problems? I'm dealing with >> neophytes. He's messed up before. >> >> On 8/16/2010 8:58 AM, Luke Paireepinart wrote: >> >>> On Mon, Aug 16, 2010 at 10:39 AM, Wayne Watson >>> wrote: >>> >>> >>>> My partner got ahead of the game last year, and installed 2.5.4, which >>>> confounds matters when the other four participants when sharing some >>>> python >>>> programs under Win XP. My guess is that if he uses control panel >>>> add/remove >>>> for py 2.5.4, he can then successfully install 2.5.2 w/o messing up any >>>> programs I've sent him. I'm presuming he did not put them under >>>> c:\Python. >>>> >>>> >>> Is this a question or a statement? Not really sure what you're >>> looking to get out of this. >>> >>> Why would 2.5.4 cause issues with 2.5.2? Why don't you all just >>> upgrade to 2.5.4? >>> >>> -Luke >>> >>> >>> >> -- >> Wayne Watson (Watson Adventures, Prop., Nevada City, CA) >> >> (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) >> Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet >> >> "An experiment is a question which science poses to >> Nature, and a measurement is the recording of >> Nature?s answer." -- Max Planck >> >> >> Web Page: >> >> >> > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "An experiment is a question which science poses to Nature, and a measurement is the recording of Nature?s answer." -- Max Planck Web Page: From emile at fenx.com Tue Aug 17 00:14:19 2010 From: emile at fenx.com (Emile van Sebille) Date: Mon, 16 Aug 2010 15:14:19 -0700 Subject: [Tutor] Moving from Python 2.5.4 to 2.5.2? In-Reply-To: References: <4C695BC1.8010402@sbcglobal.net> <4C69A641.20105@sbcglobal.net> Message-ID: On 8/16/2010 2:41 PM Luke Paireepinart said... > The core issue here is: are there actually issues exacerbated by the > difference in Python versions? If so, which issues? There shouldn't > be hardly any reason to force you all to maintain the exact same > python version, especially if you're in the same sub-version (2.5) > I agree. 2.5.4 is a bug release for the 2.5 series and by decree may not introduce backward incompatibilities of any kind. If there's a compatibility issue, please provide details so it can be verified as it ought to be reported. Emile From davea at ieee.org Tue Aug 17 01:02:47 2010 From: davea at ieee.org (Dave Angel) Date: Mon, 16 Aug 2010 19:02:47 -0400 Subject: [Tutor] Question about Dictionaries In-Reply-To: <3149FC764D12D24DA307F9DA7248176401E17FDD@usctmx1158.merck.com> References: <3149FC764D12D24DA307F9DA7248176401E17FDD@usctmx1158.merck.com> Message-ID: <4C69C397.4020603@ieee.org> Chorn, Guillaume wrote: > Hi All, > > I know that I can look up the value for a particular key in a > dictionary, but can I look up the key associated with a particular > value? I understand that this could be problematic from the standpoint > of multiple keys having the same value, but even then I feel like Python > could just return a list of keys with that value. > > Thanks! > > Guillaume > > Notice: This e-mail message, together with any attachments, contains > information of Merck & Co., Inc. (One Merck Drive, Whitehouse Station, > New Jersey, USA 08889), and/or its affiliates Direct contact information > for affiliates is available at > http://www.merck.com/contact/contacts.html) that may be confidential, > proprietary copyrighted and/or legally privileged. It is intended solely > for the use of the individual or entity named on this message. If you are > not the intended recipient, and have received this message in error, > please notify us immediately by reply e-mail and then delete it from > your system. > > As long as you don't mind it being (relatively) slow, you could do something like (untested): [key for key, item in mydict if item == value] DaveA From huyslogic at gmail.com Tue Aug 17 01:12:39 2010 From: huyslogic at gmail.com (Huy Ton That) Date: Mon, 16 Aug 2010 19:12:39 -0400 Subject: [Tutor] Question about Dictionaries In-Reply-To: References: <3149FC764D12D24DA307F9DA7248176401E17FDD@usctmx1158.merck.com> Message-ID: What do you mean by subclass? On Aug 16, 2010 3:26 PM, "Emile van Sebille" wrote: On 8/16/2010 10:44 AM Chorn, Guillaume said... > > Hi All, > > I know that I can look up the value for a particular key in a > dictionary, but can... Yes. But you'll need to implement it. There are likely modules out there that'll do this, but it'd take more time to look up and evaluate than to simply write and implement exactly what you need. > I understand that this could be problematic from the standpoint > of multiple keys having the sa... So, in untested code you'd have a function something like: result = [] for ky, val in dict.items(): if val == targetval: result.append(ky) return result If you need repeated access such that iterating over a large dict frequently impacts performance, you could subclass dict and maintain a second index allowing instant access to the keys associated with a specific value. HTH, Emile _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Aug 17 01:20:43 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Aug 2010 00:20:43 +0100 Subject: [Tutor] Question about Dictionaries References: <3149FC764D12D24DA307F9DA7248176401E17FDD@usctmx1158.merck.com> Message-ID: "Chorn, Guillaume" wrote > dictionary, but can I look up the key associated with a particular > value? Not directly but its not hard to do bearing in mind you will get a collection back.: >>> d = {1:10,2:20,3:10,4:20} >>> val = 10 >>> ks = [k for k in d if d[k] == val] >>> ks [1, 3] >>> You need to trawl the dictionary whatever you do (unless you get very sophisticated and build a double dictionary class, but then insertions get slow because you have to update both versions...) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Aug 17 01:27:11 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Aug 2010 00:27:11 +0100 Subject: [Tutor] Schema change in ElementTree References: <0016364c654fb8aac2048decc07a@google.com> Message-ID: "Stefan Behnel" wrote > Note that it's best to hit "reply" when responding to other people's > postings. Or on the tutor list make that ReplyAll! :-) Alan G. From guillaume_chorn at merck.com Tue Aug 17 01:11:57 2010 From: guillaume_chorn at merck.com (Chorn, Guillaume) Date: Mon, 16 Aug 2010 19:11:57 -0400 Subject: [Tutor] Question about Dictionaries In-Reply-To: <4C69C397.4020603@ieee.org> References: <3149FC764D12D24DA307F9DA7248176401E17FDD@usctmx1158.merck.com> <4C69C397.4020603@ieee.org> Message-ID: <3149FC764D12D24DA307F9DA7248176401E181F8@usctmx1158.merck.com> Thanks Dave. Actually I figured out a relatively simple solution to my specific problem--since the dictionary I made was the result of zipping together two lists, I simply made a second dictionary with the lists switched around after the zip command and used that. It worked in my case because all key-value pairings were unique... -----Original Message----- From: Dave Angel [mailto:davea at ieee.org] Sent: Monday, August 16, 2010 4:03 PM To: Chorn, Guillaume Cc: tutor at python.org Subject: Re: [Tutor] Question about Dictionaries Chorn, Guillaume wrote: > Hi All, > > I know that I can look up the value for a particular key in a > dictionary, but can I look up the key associated with a particular > value? I understand that this could be problematic from the standpoint > of multiple keys having the same value, but even then I feel like Python > could just return a list of keys with that value. > > Thanks! > > Guillaume > > Notice: This e-mail message, together with any attachments, contains > information of Merck & Co., Inc. (One Merck Drive, Whitehouse Station, > New Jersey, USA 08889), and/or its affiliates Direct contact information > for affiliates is available at > http://www.merck.com/contact/contacts.html) that may be confidential, > proprietary copyrighted and/or legally privileged. It is intended solely > for the use of the individual or entity named on this message. If you are > not the intended recipient, and have received this message in error, > please notify us immediately by reply e-mail and then delete it from > your system. > > As long as you don't mind it being (relatively) slow, you could do something like (untested): [key for key, item in mydict if item == value] DaveA Notice: This e-mail message, together with any attachments, contains information of Merck & Co., Inc. (One Merck Drive, Whitehouse Station, New Jersey, USA 08889), and/or its affiliates Direct contact information for affiliates is available at http://www.merck.com/contact/contacts.html) that may be confidential, proprietary copyrighted and/or legally privileged. It is intended solely for the use of the individual or entity named on this message. If you are not the intended recipient, and have received this message in error, please notify us immediately by reply e-mail and then delete it from your system. From wallenpb at gmail.com Tue Aug 17 01:50:47 2010 From: wallenpb at gmail.com (Bill Allen) Date: Mon, 16 Aug 2010 18:50:47 -0500 Subject: [Tutor] my Python learning exercise In-Reply-To: References: Message-ID: On Mon, Aug 16, 2010 at 9:25 AM, Luke Paireepinart wrote: > > Anyone who finds this interesting may also want to look into > http://inventwithpython.com/ , I hear it's a good book but I haven't > personally worked through it. > > > Very interesting, looks good! Thanks, Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Aug 17 02:14:35 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 17 Aug 2010 10:14:35 +1000 Subject: [Tutor] Moving from Python 2.5.4 to 2.5.2? In-Reply-To: <4C69A641.20105@sbcglobal.net> References: <4C695BC1.8010402@sbcglobal.net> <4C69A641.20105@sbcglobal.net> Message-ID: <201008171014.35746.steve@pearwood.info> On Tue, 17 Aug 2010 06:57:37 am Wayne Watson wrote: > The question is would going back likely cause problems? I'm dealing > with neophytes. He's messed up before. There shouldn't be any differences you're likely to care about between 2.5.2 and 2.5.4, but if there is, your best approach is for you to upgrade to 2.5.4 rather than trying to get the neophyte to downgrade to 2.5.2. -- Steven D'Aprano From steve at pearwood.info Tue Aug 17 02:17:22 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 17 Aug 2010 10:17:22 +1000 Subject: [Tutor] Question about Dictionaries In-Reply-To: <3149FC764D12D24DA307F9DA7248176401E17FDD@usctmx1158.merck.com> References: <3149FC764D12D24DA307F9DA7248176401E17FDD@usctmx1158.merck.com> Message-ID: <201008171017.22729.steve@pearwood.info> On Tue, 17 Aug 2010 03:44:33 am Chorn, Guillaume wrote: > Hi All, > > I know that I can look up the value for a particular key in a > dictionary, but can I look up the key associated with a particular > value? I understand that this could be problematic from the > standpoint of multiple keys having the same value, but even then I > feel like Python could just return a list of keys with that value. There is no built-in way of doing so, but it's easy to write your own. def reverse_lookup(d, target, first_only=False): found = [] for key, value in d.items(): if value == target: if first_only: return key found.append(key) return found Or if you want a one-liner, use a list-comp: [k for (k,v) in d.items() if v == target] -- Steven D'Aprano From emile at fenx.com Tue Aug 17 02:20:01 2010 From: emile at fenx.com (Emile van Sebille) Date: Mon, 16 Aug 2010 17:20:01 -0700 Subject: [Tutor] Question about Dictionaries In-Reply-To: References: <3149FC764D12D24DA307F9DA7248176401E17FDD@usctmx1158.merck.com> Message-ID: On 8/16/2010 4:12 PM Huy Ton That said... > What do you mean by subclass? > > > If you need repeated access such that iterating over a large dict frequently > impacts performance, you could subclass dict and maintain a second index > allowing instant access to the keys associated with a specific value. > > HTH, > > Emile > Something along these lines: class myDict(dict): def __init__(self): self.altKeys = {} def __setitem__(self,ky,val): self.altKeys[val]=ky return dict.__setitem__(self, ky,val) def lookup(self,ky): return self.altKeys[ky] a = myDict() a[1] = 111 a[2] = 222 a[3] = 333 a[3] a.lookup(333) Emile From steve at pearwood.info Tue Aug 17 02:24:30 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 17 Aug 2010 10:24:30 +1000 Subject: [Tutor] Question about Dictionaries In-Reply-To: References: <3149FC764D12D24DA307F9DA7248176401E17FDD@usctmx1158.merck.com> Message-ID: <201008171024.30926.steve@pearwood.info> On Tue, 17 Aug 2010 09:12:39 am Huy Ton That wrote: > What do you mean by subclass? It's a fundamental term from object-oriented programming. If you have a class that defines certain data and behaviour, you can create a *subclass* that inherits the same data and behaviour, except for specific examples which are over-ridden or over-loaded. A simple example: class MyInt(int): # creates a subclass of int def __str__(self): return "My Integer %d" % self MyInts are exactly the same as built-in ints except their string form is different. >>> n = MyInt(42) >>> print n My Integer 42 -- Steven D'Aprano From sierra_mtnview at sbcglobal.net Tue Aug 17 02:52:10 2010 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 16 Aug 2010 17:52:10 -0700 Subject: [Tutor] Moving from Python 2.5.4 to 2.5.2? In-Reply-To: <201008171014.35746.steve@pearwood.info> References: <4C695BC1.8010402@sbcglobal.net> <4C69A641.20105@sbcglobal.net> <201008171014.35746.steve@pearwood.info> Message-ID: <4C69DD3A.2000608@sbcglobal.net> No question about that. For the record, I'm not going to ask him to change based on the answers here. On 8/16/2010 5:14 PM, Steven D'Aprano wrote: > On Tue, 17 Aug 2010 06:57:37 am Wayne Watson wrote: > >> The question is would going back likely cause problems? I'm dealing >> with neophytes. He's messed up before. >> > There shouldn't be any differences you're likely to care about between > 2.5.2 and 2.5.4, but if there is, your best approach is for you to > upgrade to 2.5.4 rather than trying to get the neophyte to downgrade to > 2.5.2. > > > > -- Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet "An experiment is a question which science poses to Nature, and a measurement is the recording of Nature?s answer." -- Max Planck Web Page: From justin.mailinglists at gmail.com Tue Aug 17 03:35:27 2010 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Tue, 17 Aug 2010 09:35:27 +0800 Subject: [Tutor] Schema change in ElementTree Message-ID: > Note that it's best to hit "reply" when responding to other people's > postings. That way, mail readers can see the relation between the original > posting and the reply and sort the reply into the right thread. > > Stefan how's this? btw, I am getting daily(?) digests of the posts via E-mail and not each post individually. From wallenpb at gmail.com Tue Aug 17 06:30:23 2010 From: wallenpb at gmail.com (Bill Allen) Date: Mon, 16 Aug 2010 23:30:23 -0500 Subject: [Tutor] box drawing characters Message-ID: I am looking for some guidance about how to best utilize box drawing characters(using unicode?) in as portable a way as possible in Python. Any good guides out there for this? Thanks, Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Tue Aug 17 08:14:57 2010 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 17 Aug 2010 08:14:57 +0200 Subject: [Tutor] Schema change in ElementTree In-Reply-To: References: Message-ID: > Stefan Behnel wrote: >> Note that it's best to hit "reply" when responding to other people's >> postings. That way, mail readers can see the relation between the original >> posting and the reply and sort the reply into the right thread. Comment to my own posting: as Alan noted already, "reply all" or "reply to list" is more suitable in this context. Justin Ezequiel, 17.08.2010 03:35: > how's this? > btw, I am getting daily(?) digests of the posts via E-mail and not > each post individually. Ah, ok, sorry, that explains it. I'm actually reading the list through the Gmane newsgroup mirror (gmane.comp.python.tutor). That allows me to be selective on what I read and prevents my account from getting flooded with e-mails while at the same time providing a perfect interface in both directions. Stefan From nitinchandra1 at gmail.com Tue Aug 17 10:39:11 2010 From: nitinchandra1 at gmail.com (nitin chandra) Date: Tue, 17 Aug 2010 14:09:11 +0530 Subject: [Tutor] reading from 2 file output to 1 Message-ID: Hello All, I am trying to read from 2 CSV files, where first 4 ([0,1,2,3]) columns are read from 'file1' and 3 columns ([1,2,3]) from 'file2' and write them into a 3rd file 'file3', 7 columns string. The data is Numeric values both, +ve and -ve. this is how i was trying. ****************************************** import sys,os, fileinput file11 = raw_input('Enter PR1 File name :') fp1 = open(file11,'r') file12 = raw_input('Enter PR3 File Name :') fp2 = open(file12,'r') while 1: fp1 = fp1.readline() for line in fp1: line2 = line.split(",") col1 = line2[0] col2 = line2[1] col3 = line2[2] col4 = line2[3] print col1 print col2 FL1 = '%s,%s,%s,%s' % (col1,col2,col3,col4) print FL1 while 1: fp2 = fp2.readline() for line1 in fp2: line3 = line1.split(",") col5 = line3[1] col6 = line3[2] col7 = line3[3] FL2 = '%s,%s,%s,' % (col5,col6,col7) print FL2 file3=raw_input('Enter PR2 OUTPUT File Name :') fp3 = open(file3,'w') print col1,col2,col3,col4 + ',' + col5,col6,col7 str3 = '%s,%s,%s,%s,%s,%s,%s\n' % (col1,col2,col3,col4,col5,col6,col7) fp3.write(str3) ********************************************** I am getting the following error : Traceback (most recent call last): File "mer5Pr2.py", line 16, in col2 = line2[1] IndexError: list index out of range ********************************************************* There is data in the file at 'col2'. So what am i missing / doing wrong ? And is there better / optimized way of doing it? Thanks Nitin From evert.rol at gmail.com Tue Aug 17 10:57:12 2010 From: evert.rol at gmail.com (Evert Rol) Date: Tue, 17 Aug 2010 10:57:12 +0200 Subject: [Tutor] reading from 2 file output to 1 In-Reply-To: References: Message-ID: > I am trying to read from 2 CSV files, where first 4 ([0,1,2,3]) > columns are read from 'file1' and 3 columns ([1,2,3]) from 'file2' and > write them into a 3rd file 'file3', 7 columns string. The data is > Numeric values both, +ve and -ve. > > this is how i was trying. > > ****************************************** > import sys,os, fileinput > > > file11 = raw_input('Enter PR1 File name :') > fp1 = open(file11,'r') > > file12 = raw_input('Enter PR3 File Name :') > fp2 = open(file12,'r') > > > while 1: > fp1 = fp1.readline() > for line in fp1: This is too much: Looks like you've gathered input from example scripts, and combined them all in the above three lines. Instead of explaining what's going wrong (sorry; ask again if you really want to know), here's what you could do instead: while 1: line = fp1.readline() # read a line and move file pointer to the next line line2 = ... and probably wrap that in a try-except block to catch the EOF error when there's nothing more to read. Better is, however, for line in fp1: # iterating through a file is iterating through its separate lines. line2 = ... Even better, assuming you're Python >=2.6 (for Python 2.5, use the following at the top of your file: from __future__ import with_statement): file11 = raw_input('Enter PR1 File name :') with open(file11) as fp1: for line in fp1: line2 = ... The with clause, in combination with the open(file1) statement (note: mode 'r' is the default), will neatly close the file afterwards, even if you get an error in the for loop (ie, the with statement takes care of some try-except-finally clauses previously used). As for whether there are better ways of 'doing it': there are CSV Python modules out there that could help you (I've never used those), and personally I would use a combination of *nix tools like awk & paste for just this. But that's not an option on a Python mailing list ;-). Hope that helps, Evert > line2 = line.split(",") > col1 = line2[0] > col2 = line2[1] > col3 = line2[2] > col4 = line2[3] > print col1 > print col2 > FL1 = '%s,%s,%s,%s' % (col1,col2,col3,col4) > print FL1 > > while 1: > fp2 = fp2.readline() > for line1 in fp2: > line3 = line1.split(",") > col5 = line3[1] > col6 = line3[2] > col7 = line3[3] > > FL2 = '%s,%s,%s,' % (col5,col6,col7) > print FL2 > > file3=raw_input('Enter PR2 OUTPUT File Name :') > fp3 = open(file3,'w') > > print col1,col2,col3,col4 + ',' + col5,col6,col7 > > str3 = '%s,%s,%s,%s,%s,%s,%s\n' % (col1,col2,col3,col4,col5,col6,col7) > fp3.write(str3) > > ********************************************** > > I am getting the following error : > > Traceback (most recent call last): > File "mer5Pr2.py", line 16, in > col2 = line2[1] > IndexError: list index out of range > > ********************************************************* > > There is data in the file at 'col2'. So what am i missing / doing wrong ? > > And is there better / optimized way of doing it? > > Thanks > > Nitin > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Tue Aug 17 11:14:54 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Aug 2010 10:14:54 +0100 Subject: [Tutor] reading from 2 file output to 1 References: Message-ID: "nitin chandra" wrote in message news:AANLkTimjRqFH=TdQtRic7=utFgbXjCGaaai9coYNNdJD at mail.gmail.com... > Hello All, > > I am trying to read from 2 CSV files, where first 4 ([0,1,2,3]) > columns are read from 'file1' and 3 columns ([1,2,3]) from 'file2' > and > write them into a 3rd file 'file3', 7 columns string. The data is > Numeric values both, +ve and -ve. The data types should be irrelevant since it is all strings in the file. But reading your requirement you want something like: while nTrue try: line1A = file1.readline() line1B = file2.readline() file3.write(line1A + line1B) except IOError: reached end of one of the files, figure out how to handle it... That looks like it should be simpler than the code you posted... -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From nitin.162 at gmail.com Tue Aug 17 12:29:35 2010 From: nitin.162 at gmail.com (Nitin Das) Date: Tue, 17 Aug 2010 15:59:35 +0530 Subject: [Tutor] reading from 2 file output to 1 In-Reply-To: References: Message-ID: I think in both the while loops , for loops are iterating over the new lines, as a result col1,col2,col3,col4,col5,col6,col7 as a result after both the while loop finishes these colums would only be having the values of the last lines from both the files. as a result the new file3 would only be having last lines of the both the files appended together, because u r combining the columns after both the while loops. --nitin On Tue, Aug 17, 2010 at 2:09 PM, nitin chandra wrote: > Hello All, > > I am trying to read from 2 CSV files, where first 4 ([0,1,2,3]) > columns are read from 'file1' and 3 columns ([1,2,3]) from 'file2' and > write them into a 3rd file 'file3', 7 columns string. The data is > Numeric values both, +ve and -ve. > > this is how i was trying. > > ****************************************** > import sys,os, fileinput > > > file11 = raw_input('Enter PR1 File name :') > fp1 = open(file11,'r') > > file12 = raw_input('Enter PR3 File Name :') > fp2 = open(file12,'r') > > > while 1: > fp1 = fp1.readline() > for line in fp1: > line2 = line.split(",") > col1 = line2[0] > col2 = line2[1] > col3 = line2[2] > col4 = line2[3] > print col1 > print col2 > FL1 = '%s,%s,%s,%s' % (col1,col2,col3,col4) > print FL1 > > while 1: > fp2 = fp2.readline() > for line1 in fp2: > line3 = line1.split(",") > col5 = line3[1] > col6 = line3[2] > col7 = line3[3] > > FL2 = '%s,%s,%s,' % (col5,col6,col7) > print FL2 > > file3=raw_input('Enter PR2 OUTPUT File Name :') > fp3 = open(file3,'w') > > print col1,col2,col3,col4 + ',' + col5,col6,col7 > > str3 = '%s,%s,%s,%s,%s,%s,%s\n' % (col1,col2,col3,col4,col5,col6,col7) > fp3.write(str3) > > ********************************************** > > I am getting the following error : > > Traceback (most recent call last): > File "mer5Pr2.py", line 16, in > col2 = line2[1] > IndexError: list index out of range > > ********************************************************* > > There is data in the file at 'col2'. So what am i missing / doing wrong ? > > And is there better / optimized way of doing it? > > Thanks > > Nitin > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Tue Aug 17 15:31:50 2010 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 17 Aug 2010 09:31:50 -0400 Subject: [Tutor] reading from 2 file output to 1 In-Reply-To: References: Message-ID: I haven't worked through the reading of the files, but once you have the matching lines from each you can process like this: def split_and_combine(l1, l2): first = l1.split(', ') second = l2.split(', ') combined = first[:4] + second[1:4] return combined Then write the value to the output file. -- Joel Goldstick On Tue, Aug 17, 2010 at 6:29 AM, Nitin Das wrote: > I think in both the while loops , for loops are iterating over the new > lines, as a result col1,col2,col3,col4,col5,col6,col7 as a result after both > the while loop finishes these colums would only be having the values of the > last lines from both the files. as a result the new file3 would only be > having last lines of the both the files appended together, because u r > combining the columns after both the while loops. > > --nitin > > > On Tue, Aug 17, 2010 at 2:09 PM, nitin chandra wrote: > >> Hello All, >> >> I am trying to read from 2 CSV files, where first 4 ([0,1,2,3]) >> columns are read from 'file1' and 3 columns ([1,2,3]) from 'file2' and >> write them into a 3rd file 'file3', 7 columns string. The data is >> Numeric values both, +ve and -ve. >> >> this is how i was trying. >> >> ****************************************** >> import sys,os, fileinput >> >> >> file11 = raw_input('Enter PR1 File name :') >> fp1 = open(file11,'r') >> >> file12 = raw_input('Enter PR3 File Name :') >> fp2 = open(file12,'r') >> >> >> while 1: >> fp1 = fp1.readline() >> for line in fp1: >> line2 = line.split(",") >> col1 = line2[0] >> col2 = line2[1] >> col3 = line2[2] >> col4 = line2[3] >> print col1 >> print col2 >> FL1 = '%s,%s,%s,%s' % (col1,col2,col3,col4) >> print FL1 >> >> while 1: >> fp2 = fp2.readline() >> for line1 in fp2: >> line3 = line1.split(",") >> col5 = line3[1] >> col6 = line3[2] >> col7 = line3[3] >> >> FL2 = '%s,%s,%s,' % (col5,col6,col7) >> print FL2 >> >> file3=raw_input('Enter PR2 OUTPUT File Name :') >> fp3 = open(file3,'w') >> >> print col1,col2,col3,col4 + ',' + col5,col6,col7 >> >> str3 = '%s,%s,%s,%s,%s,%s,%s\n' % (col1,col2,col3,col4,col5,col6,col7) >> fp3.write(str3) >> >> ********************************************** >> >> I am getting the following error : >> >> Traceback (most recent call last): >> File "mer5Pr2.py", line 16, in >> col2 = line2[1] >> IndexError: list index out of range >> >> ********************************************************* >> >> There is data in the file at 'col2'. So what am i missing / doing wrong ? >> >> And is there better / optimized way of doing it? >> >> Thanks >> >> Nitin >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Aug 17 17:00:01 2010 From: bgailer at gmail.com (bob gailer) Date: Tue, 17 Aug 2010 11:00:01 -0400 Subject: [Tutor] box drawing characters In-Reply-To: References: Message-ID: <4C6AA3F1.9090501@gmail.com> On 8/17/2010 12:30 AM, Bill Allen wrote: > I am looking for some guidance about how to best utilize box drawing > characters(using unicode?) in as portable a way as possible in > Python. Any good guides out there for this? Please tell us a bit more about your goals. -- Bob Gailer 919-636-4239 Chapel Hill NC From wallenpb at gmail.com Wed Aug 18 03:12:51 2010 From: wallenpb at gmail.com (Bill Allen) Date: Tue, 17 Aug 2010 20:12:51 -0500 Subject: [Tutor] box drawing characters In-Reply-To: <4C6AA3F1.9090501@gmail.com> References: <4C6AA3F1.9090501@gmail.com> Message-ID: On Tue, Aug 17, 2010 at 10:00 AM, bob gailer wrote: > On 8/17/2010 12:30 AM, Bill Allen wrote: > >> I am looking for some guidance about how to best utilize box drawing >> characters(using unicode?) in as portable a way as possible in Python. Any >> good guides out there for this? >> > > Please tell us a bit more about your goals. > > > I want to be able to create some user interfaces, similar to what you see in console based programs like Midnight Commander or other TUI type programs that use box drawing characters to create a user interfaces for input and display of information. However, I do want them to be portable to most platforms that Python will run on. I have actually found much more information on designing fully graphical GUI interfaces using Tk or Qt or GTK, but I know the other type is possible. I suppose I have a preference for the older console type programs. Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From mesrod at juno.com Wed Aug 18 06:54:22 2010 From: mesrod at juno.com (mesrod at juno.com) Date: Wed, 18 Aug 2010 04:54:22 GMT Subject: [Tutor] Error Using exec to Run Module Files Message-ID: <20100817.225422.29421.0@webmail11.vgs.untd.com> I'm a rank beginner in Python. Took advantage of the O'Reilly one-day sale of 'Learning Python' announced on the tutor, and starting to work my way through it. When I tried out an example from pg57, on Using exec to Run Module Files, I get the following result: >>> exec(open('script1.py').read()) Traceback (most recent call last): File "", line 1, in File "", line 1 %!PS-Adobe-3.0 ^ SyntaxError: invalid syntax What is going on/ Gene R. From knacktus at googlemail.com Wed Aug 18 07:45:22 2010 From: knacktus at googlemail.com (Knacktus) Date: Wed, 18 Aug 2010 07:45:22 +0200 Subject: [Tutor] Error Using exec to Run Module Files In-Reply-To: <20100817.225422.29421.0@webmail11.vgs.untd.com> References: <20100817.225422.29421.0@webmail11.vgs.untd.com> Message-ID: <4C6B7372.8030506@googlemail.com> Am 18.08.2010 06:54, schrieb mesrod at juno.com: > I'm a rank beginner in Python. Took advantage of the O'Reilly one-day sale of 'Learning Python' announced on the tutor, and starting to work my way through it. When I tried out an example from pg57, on Using exec to Run Module Files, I get the following result: >>>> exec(open('script1.py').read()) > Traceback (most recent call last): > File "", line 1, in > File "", line 1 > %!PS-Adobe-3.0 > ^ > SyntaxError: invalid syntax > It looks like the first line of your file "script1.py" contains "%!PS-Adobe-3.0". (Which is no valid syntax, of course) Have you doublechecked the content of script1.py and does it work by invoking it form the command line with "python script1.py"? My guess is the file somehow got screwed up. HTH Jan > What is going on/ > Gene R. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From wiserwaylander at gmail.com Wed Aug 18 09:15:40 2010 From: wiserwaylander at gmail.com (shane brennan) Date: Wed, 18 Aug 2010 08:15:40 +0100 Subject: [Tutor] Getting confusing NameError Message-ID: Hi Tutors This is my first mail to this list so firstly thank you for reading and apologies in advance for any noob mistakes i may have inadvertantly made:). Ive only started learning python as my first programming language and its all going well so far, working my way through a couple of books one of which is programming python: for absolute beginners by Michael Dawson In one of the code samples he supplies while doing loops ( namely if and else loops) im getting a NameError i dont understand and cannot find any help anywhere about it. here is the code he supplied and the error im getting # Password # Demonstrates the if statement print("Welcome to System Security Inc.") print("-- where security is our middle name\n") password = input("Enter your password: ") if password == "secret": print("Access Granted") input("\n\nPress the enter key to exit.") and the traceback error im getting Traceback (most recent call last): File "G:\Programming\Python\programming python\chapter3\password.py", line 7, in password = input("Enter your password: ") File "", line 1, in NameError: name 'secret' is not defined I know this is probably very simple but for some reason i cannot get my head around it. thank you for any help in advance shane -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Wed Aug 18 09:28:28 2010 From: evert.rol at gmail.com (Evert Rol) Date: Wed, 18 Aug 2010 09:28:28 +0200 Subject: [Tutor] Getting confusing NameError In-Reply-To: References: Message-ID: > This is my first mail to this list so firstly thank you for reading and apologies in advance for any noob mistakes i may have inadvertantly made:). Ive only started learning python as my first programming language and its all going well so far, working my way through a couple of books one of which is programming python: for absolute beginners by Michael Dawson > > In one of the code samples he supplies while doing loops ( namely if and else loops) im getting a NameError i dont understand and cannot find any help anywhere about it. here is the code he supplied and the error im getting > > # Password > # Demonstrates the if statement > > print("Welcome to System Security Inc.") > print("-- where security is our middle name\n") > > password = input("Enter your password: ") > > if password == "secret": > print("Access Granted") > > input("\n\nPress the enter key to exit.") > > > and the traceback error im getting > > Traceback (most recent call last): > File "G:\Programming\Python\programming python\chapter3\password.py", line 7, > in > password = input("Enter your password: ") > File "", line 1, in > NameError: name 'secret' is not defined Hi Shane, Normally, a NameError would indicate a variable that's not defined. Here it's a it more tricky. You're probably using Python 2.x, while the code is for Python 3.x. There are several changes between Python versions 2 and 3 that make the two languages different (or rather, the interpreters handle some code differently). One difference how the function 'input()' is handled, and that difference is big enough for your code to crash. I would hope that the book somewhere in the beginning mentions the code is for Python 3 and not for Python 2. The best solution for you is to try and install Python 3 and use that to proceed through the code in the book. Evert NB: if-else are not actually loops, but rather form a conditional statement. You can, then, use such a if-else construction to break out of a loop, which probably will be shown in some later code. Just to be pedantic ;-). > I know this is probably very simple but for some reason i cannot get my head around it. > > thank you for any help in advance > > shane > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From nitin.162 at gmail.com Wed Aug 18 09:30:31 2010 From: nitin.162 at gmail.com (Nitin Das) Date: Wed, 18 Aug 2010 13:00:31 +0530 Subject: [Tutor] Getting confusing NameError In-Reply-To: References: Message-ID: use raw_input instead of input . as using input is unsafe as it evaluates your input as python command. for e,g. x = input("enter command") and u entered "1 + 2" as input., then it will evaluate 1+2 = 3 = x. -nitin On Wed, Aug 18, 2010 at 12:45 PM, shane brennan wrote: > Hi Tutors > > This is my first mail to this list so firstly thank you for reading and > apologies in advance for any noob mistakes i may have inadvertantly made:). > Ive only started learning python as my first programming language and its > all going well so far, working my way through a couple of books one of which > is programming python: for absolute beginners by Michael Dawson > > In one of the code samples he supplies while doing loops ( namely if and > else loops) im getting a NameError i dont understand and cannot find any > help anywhere about it. here is the code he supplied and the error im > getting > > # Password > # Demonstrates the if statement > > print("Welcome to System Security Inc.") > print("-- where security is our middle name\n") > > password = input("Enter your password: ") > > if password == "secret": > print("Access Granted") > > input("\n\nPress the enter key to exit.") > > > and the traceback error im getting > > Traceback (most recent call last): > File "G:\Programming\Python\programming python\chapter3\password.py", > line 7, > in > password = input("Enter your password: ") > File "", line 1, in > NameError: name 'secret' is not defined > > > I know this is probably very simple but for some reason i cannot get my > head around it. > > thank you for any help in advance > > shane > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at compuscan.co.za Wed Aug 18 09:37:13 2010 From: cwitts at compuscan.co.za (Christian Witts) Date: Wed, 18 Aug 2010 09:37:13 +0200 Subject: [Tutor] Getting confusing NameError In-Reply-To: References: Message-ID: <4C6B8DA9.9070906@compuscan.co.za> On 18/08/2010 09:15, shane brennan wrote: > Hi Tutors > This is my first mail to this list so firstly thank you for reading > and apologies in advance for any noob mistakes i may have > inadvertantly made:). Ive only started learning python as my first > programming language and its all going well so far, working my way > through a couple of books one of which is programming python: for > absolute beginners by Michael Dawson > In one of the code samples he supplies while doing loops ( namely if > and else loops) im getting a NameError i dont understand and cannot > find any help anywhere about it. here is the code he supplied and the > error im getting > # Password > # Demonstrates the if statement > print("Welcome to System Security Inc.") > print("-- where security is our middle name\n") > password = input("Enter your password: ") > if password == "secret": > print("Access Granted") > input("\n\nPress the enter key to exit.") > and the traceback error im getting > Traceback (most recent call last): > File "G:\Programming\Python\programming > python\chapter3\password.py", line 7, > in > password = input("Enter your password: ") > File "", line 1, in > NameError: name 'secret' is not defined > I know this is probably very simple but for some reason i cannot get > my head around it. > thank you for any help in advance > shane > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > input() [1] expects a valid Python expression as input as it gets evaluated and is not technically safe. raw_input() [2] is what you should be using instead. [1] http://docs.python.org/library/functions.html#input [2] http://docs.python.org/library/functions.html#raw_input Hope that helps. Welcome to the list and enjoy your stay. -- Kind Regards, Christian Witts From alan.gauld at btinternet.com Wed Aug 18 10:15:13 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 Aug 2010 09:15:13 +0100 Subject: [Tutor] box drawing characters References: <4C6AA3F1.9090501@gmail.com> Message-ID: "Bill Allen" wrote >> I want to be able to create some user interfaces, similar to what >> you see > in console based programs like Midnight Commander or other TUI type > programs > that use box drawing characters to create a user interfaces for > input and > display of information. This is OK and you can use curses on Linux/Unix systems and something like Conio on Windows, but.... > However, I do want them to be portable to most > platforms that Python will run on. This is much more difficult. Terminals are non portable and neither of the libraries above work on the other system. You would probably have to build your UI twice. This is one area where real GUIs work better than a terminal. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Aug 18 10:18:28 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 Aug 2010 09:18:28 +0100 Subject: [Tutor] Error Using exec to Run Module Files References: <20100817.225422.29421.0@webmail11.vgs.untd.com> Message-ID: wrote >>>> exec(open('script1.py').read()) > Traceback (most recent call last): > File "", line 1, in > File "", line 1 > %!PS-Adobe-3.0 > ^ > SyntaxError: invalid syntax > > What is going on/ Looks like your script1.py file is actually a postscript file. exec expects to see valid Python code, it can't process Postscript. Can you run script1.py from the command line? Or can you import it at the >>> prompt? HTH, Alan G. From alan.gauld at btinternet.com Wed Aug 18 10:37:02 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 Aug 2010 09:37:02 +0100 Subject: [Tutor] Getting confusing NameError References: Message-ID: "shane brennan" wrote > In one of the code samples he supplies while doing loops ( namely if > and > else loops) im getting a NameError i dont understand and cannot find > any > help anywhere about it. Evert has already pointed out that the code is for Python v3 and it looks like you are using Python v2. If your other book is based on v2 then using the two side by side will be confusing. If both are on v3 then you need to upgrade your Python to v3. If they are mixed versions then you need to decide on only one book and follow whichever version it uses. You can find both v2 and v3 versions of my tutorial on my web site. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From wiserwaylander at gmail.com Wed Aug 18 10:48:28 2010 From: wiserwaylander at gmail.com (shane brennan) Date: Wed, 18 Aug 2010 09:48:28 +0100 Subject: [Tutor] Getting confusing NameError In-Reply-To: References: Message-ID: Hi all Thank you for all the help. I had upgraded the machine to v3 but for some reason 2 hadnt removed properly, once i did some digigng i found the redundant entries in the registry and the libraries that didnt remove and cleared them up . script is running fine now:) thanks for all the help Espcially thanks for the pointers and information on the difference between raw_input and input. again thanks for everything, and hopefully ill be around here for a long time and once i get a more experienced i can contribute back On Wed, Aug 18, 2010 at 09:37, Alan Gauld wrote: > "shane brennan" wrote > > In one of the code samples he supplies while doing loops ( namely if and >> else loops) im getting a NameError i dont understand and cannot find any >> help anywhere about it. >> > > Evert has already pointed out that the code is for Python v3 and it > looks like you are using Python v2. > > If your other book is based on v2 then using the two side by side will > be confusing. If both are on v3 then you need to upgrade your Python > to v3. If they are mixed versions then you need to decide on only one > book and follow whichever version it uses. > > You can find both v2 and v3 versions of my tutorial on my web site. > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From laurens at daemon.be Wed Aug 18 13:21:51 2010 From: laurens at daemon.be (Laurens Vets) Date: Wed, 18 Aug 2010 13:21:51 +0200 Subject: [Tutor] Need help understanding output... In-Reply-To: <201008120926.49330.steve@pearwood.info> References: <4C63104F.70104@daemon.be> <201008120926.49330.steve@pearwood.info> Message-ID: <4C6BC24F.1080000@daemon.be> On 8/12/2010 1:26 AM, Steven D'Aprano wrote: > On Thu, 12 Aug 2010 07:04:15 am Laurens Vets wrote: > >> I need to generate a list of 30 numbers randomly chosen from 1, 2, 3, >> 4, 5& 6. However, I cannot have more than 2 numbers which are the >> same next to each other. I came up with the following (Please ignore >> the fact that I'm trying to avoid an IndexError in a stupid way :)): > > I can't possible do that! :) > >> import random >> reeks = [] >> while len(reeks)<= 1: >> number = random.randrange(1, 7, 1) >> reeks.append(number) >> >> while len(reeks)<= 29: >> nummer = random.randrange(1, 7, 1) >> if nummer != reeks[-1] and nummer != reeks[-2]: >> reeks.append(nummer) >> print reeks > > This is probably a simpler way: > > import random > reeks = [] > for i in range(30): > temp = [random.randint(1, 6)] > while reeks[-2:-1] == reeks[-1:] == temp: > # print "Triplet found:", reeks, temp > temp = [random.randint(1, 6)] > reeks.extend(temp) > > print reeks Thank you all for your help! I've added another condition to this program, namely, in a range of 60, each 'random' number can only occur 10 times. I came up with the following: import random series = [] for i in range(60): temp = [random.randint(1, 6)] while series[-2:-1] == series[-1:] == temp: temp = [random.randint(1, 6)] while series.count(temp[0]) >= 10: temp = [random.randint(1, 6)] series.extend(temp) print series However, this also generates gems such as: [4, 4, 3, 6, 3, 2, 6, 3, 4, 3, 4, 1, 4, 2, 4, 3, 4, 4, 6, 2, 1, 5, 5, 6, 5, 6, 5, 6, 3, 3, 1, 6, 6, 4, 1, 5, 2, 6, 6, 4, 2, 5, 3, 1, 5, 5, 2, 1, _2_, _2_, _2_, 3, 3, 2, 1, 5, 1, 1, 5, 1] [1, 4, 3, 1, 5, 3, 5, 1, 5, 6, 5, 3, 2, 6, 1, 4, 1, 5, 5, 2, 6, 2, 4, 1, 3, 1, 2, 1, 1, 3, 1, 6, 6, 3, 2, 3, 6, 4, 5, 6, 5, 6, 3, 6, 2, 4, 5, 3, 3, 4, 6, _4_, _4_, _4_, 5, 4, _2_, _2_, _2_, _2_] I thought this needed to become the following: import random series = [] for i in range(60): temp = [random.randint(1, 6)] print "Temp", i, ":", temp while series[-2:-1] == series[-1:] == series: if series.count(temp[0]) >= 10: temp = [random.randint(1, 6)] series.extend(temp) print series But this just hangs whenever the while clause matches. I'm not sure what I'm doing wrong here. I do know the random.shuffle() function, but I can't put my conditions in there. Any push in the right direction would be greatly appreciated :) From evert.rol at gmail.com Wed Aug 18 14:16:45 2010 From: evert.rol at gmail.com (Evert Rol) Date: Wed, 18 Aug 2010 14:16:45 +0200 Subject: [Tutor] Need help understanding output... In-Reply-To: <4C6BC24F.1080000@daemon.be> References: <4C63104F.70104@daemon.be> <201008120926.49330.steve@pearwood.info> <4C6BC24F.1080000@daemon.be> Message-ID: On 18 Aug 2010, at 13:21 , Laurens Vets wrote: > On 8/12/2010 1:26 AM, Steven D'Aprano wrote: >> On Thu, 12 Aug 2010 07:04:15 am Laurens Vets wrote: >> >>> I need to generate a list of 30 numbers randomly chosen from 1, 2, 3, >>> 4, 5& 6. However, I cannot have more than 2 numbers which are the >>> same next to each other. I came up with the following (Please ignore >>> the fact that I'm trying to avoid an IndexError in a stupid way :)): >> >> I can't possible do that! :) >> >>> import random >>> reeks = [] >>> while len(reeks)<= 1: >>> number = random.randrange(1, 7, 1) >>> reeks.append(number) >>> >>> while len(reeks)<= 29: >>> nummer = random.randrange(1, 7, 1) >>> if nummer != reeks[-1] and nummer != reeks[-2]: >>> reeks.append(nummer) >>> print reeks >> >> This is probably a simpler way: >> >> import random >> reeks = [] >> for i in range(30): >> temp = [random.randint(1, 6)] >> while reeks[-2:-1] == reeks[-1:] == temp: >> # print "Triplet found:", reeks, temp >> temp = [random.randint(1, 6)] >> reeks.extend(temp) >> >> print reeks > > > > Thank you all for your help! I've added another condition to this program, namely, in a range of 60, each 'random' number can only occur 10 times. I came up with the following: > > import random > series = [] > for i in range(60): > temp = [random.randint(1, 6)] > while series[-2:-1] == series[-1:] == temp: > temp = [random.randint(1, 6)] > while series.count(temp[0]) >= 10: > temp = [random.randint(1, 6)] > series.extend(temp) > print series > > However, this also generates gems such as: > > [4, 4, 3, 6, 3, 2, 6, 3, 4, 3, 4, 1, 4, 2, 4, 3, 4, 4, 6, 2, 1, 5, 5, 6, 5, 6, 5, 6, 3, 3, 1, 6, 6, 4, 1, 5, 2, 6, 6, 4, 2, 5, 3, 1, 5, 5, 2, 1, _2_, _2_, _2_, 3, 3, 2, 1, 5, 1, 1, 5, 1] > > [1, 4, 3, 1, 5, 3, 5, 1, 5, 6, 5, 3, 2, 6, 1, 4, 1, 5, 5, 2, 6, 2, 4, 1, 3, 1, 2, 1, 1, 3, 1, 6, 6, 3, 2, 3, 6, 4, 5, 6, 5, 6, 3, 6, 2, 4, 5, 3, 3, 4, 6, _4_, _4_, _4_, 5, 4, _2_, _2_, _2_, _2_] > > I thought this needed to become the following: > > import random > series = [] > for i in range(60): > temp = [random.randint(1, 6)] > print "Temp", i, ":", temp > while series[-2:-1] == series[-1:] == series: > if series.count(temp[0]) >= 10: > temp = [random.randint(1, 6)] > series.extend(temp) > print series > > But this just hangs whenever the while clause matches. I'm not sure what I'm doing wrong here. I do know the random.shuffle() function, but I can't put my conditions in there. I assume the '== series:' is a typo, and should be '== temp'. Otherwise I don't see how this matches, unless series = [] (which means the while clause always matches, right at the start. Perhaps that actually is what you're seeing?). That's probably the disadvantage of using a list to avoid an IndexError (sorry Steven; I would have just caught the IndexError, or have an 'if i < 2: continue' statement in there.) As suggestion for avoiding occurrences of > 10 times: use a dict, where the random numbers become the keys and you add +1 every time to d[temp]. Checking if d[temp] > 10 is then very easy. Cheers, Evert > > Any push in the right direction would be greatly appreciated :) > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From waynejwerner at gmail.com Wed Aug 18 15:15:03 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Wed, 18 Aug 2010 08:15:03 -0500 Subject: [Tutor] Getting confusing NameError In-Reply-To: References: Message-ID: On Wed, Aug 18, 2010 at 3:48 AM, shane brennan wrote: > > > again thanks for everything, and hopefully ill be around here for a long > time and once i get a more experienced i can contribute back > You don't need to be /too/ experienced. Contributing here is actually how I learned Python as much and as well as I did. When someone asked a question (especially interesting ones), I made it a point to try and answer them. If I didn't already know the answer I would go Google and try to find the answer. Sometimes it was over my head and I wasn't able to form a decent reply before others, but many times I was able to understand the problem and question and fire off some fairly good information. And if you preface your post with "I'm new to this part of Python, but I looked it up and this is what I found..." or some other self effacing statement that shows you're pretty confident in your answer but you're perfectly willing to be taught if you were wrong - which will (usually) keep you from looking like a cocky noob, and look like more like a humble acolyte trying to do your best to help out a fellow Pythonista. At least that's my experience ;) -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From laurens at daemon.be Wed Aug 18 15:30:13 2010 From: laurens at daemon.be (Laurens Vets) Date: Wed, 18 Aug 2010 15:30:13 +0200 Subject: [Tutor] Need help understanding output... In-Reply-To: References: <4C63104F.70104@daemon.be> <201008120926.49330.steve@pearwood.info> <4C6BC24F.1080000@daemon.be> Message-ID: <4C6BE065.8050703@daemon.be> >> >> >> >> Thank you all for your help! I've added another condition to this program, namely, in a range of 60, each 'random' number can only occur 10 times. I came up with the following: >> >> import random >> series = [] >> for i in range(60): >> temp = [random.randint(1, 6)] >> while series[-2:-1] == series[-1:] == temp: >> temp = [random.randint(1, 6)] >> while series.count(temp[0])>= 10: >> temp = [random.randint(1, 6)] >> series.extend(temp) >> print series >> >> However, this also generates gems such as: >> >> [4, 4, 3, 6, 3, 2, 6, 3, 4, 3, 4, 1, 4, 2, 4, 3, 4, 4, 6, 2, 1, 5, 5, 6, 5, 6, 5, 6, 3, 3, 1, 6, 6, 4, 1, 5, 2, 6, 6, 4, 2, 5, 3, 1, 5, 5, 2, 1, _2_, _2_, _2_, 3, 3, 2, 1, 5, 1, 1, 5, 1] >> >> [1, 4, 3, 1, 5, 3, 5, 1, 5, 6, 5, 3, 2, 6, 1, 4, 1, 5, 5, 2, 6, 2, 4, 1, 3, 1, 2, 1, 1, 3, 1, 6, 6, 3, 2, 3, 6, 4, 5, 6, 5, 6, 3, 6, 2, 4, 5, 3, 3, 4, 6, _4_, _4_, _4_, 5, 4, _2_, _2_, _2_, _2_] >> >> I thought this needed to become the following: >> >> import random >> series = [] >> for i in range(60): >> temp = [random.randint(1, 6)] >> print "Temp", i, ":", temp >> while series[-2:-1] == series[-1:] == series: >> if series.count(temp[0])>= 10: >> temp = [random.randint(1, 6)] >> series.extend(temp) >> print series >> >> But this just hangs whenever the while clause matches. I'm not sure what I'm doing wrong here. I do know the random.shuffle() function, but I can't put my conditions in there. > > I assume the '== series:' is a typo, and should be '== temp'. Otherwise I don't see how this matches, unless series = [] (which means the while clause always matches, right at the start. Perhaps that actually is what you're seeing?). > That's probably the disadvantage of using a list to avoid an IndexError (sorry Steven; I would have just caught the IndexError, or have an 'if i< 2: continue' statement in there.) Yes of course :) That's a typo on my part. I came up with the following which I think works as well? import random reeks = [] for i in range(60): temp = [random.randint(1, 6)] while reeks[-2:-1] == reeks[-1:] == temp: temp = [random.randint(1, 6)] if reeks.count(temp[0]) >= 10: temp = [random.randint(1, 6)] reeks.extend(temp) print reeks > As suggestion for avoiding occurrences of> 10 times: use a dict, where the random numbers become the keys and you add +1 every time to d[temp]. Checking if d[temp]> 10 is then very easy. I'll check dicts as well. Thank you! :) From wallenpb at gmail.com Wed Aug 18 15:31:39 2010 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 18 Aug 2010 08:31:39 -0500 Subject: [Tutor] box drawing characters In-Reply-To: References: <4C6AA3F1.9090501@gmail.com> Message-ID: On Wed, Aug 18, 2010 at 3:15 AM, Alan Gauld wrote: > > "Bill Allen" wrote > >> I want to be able to create some user interfaces, similar to what you see >>> >> in console based programs like Midnight Commander or other TUI type >> programs >> that use box drawing characters to create a user interfaces for input and >> display of information. >> > > This is OK and you can use curses on Linux/Unix systems and something > like Conio on Windows, but.... > > > However, I do want them to be portable to most >> platforms that Python will run on. >> > > This is much more difficult. Terminals are non portable and neither > of the libraries above work on the other system. You would probably > have to build your UI twice. This is one area where real GUIs work > better than a terminal. > > This is good to know. For my purposes either will be an acceptable option for me as I am very much in learning mode. In the endgame, I can always do an OS detection and load whichever code is appropriate as the duplication does not bother me much. Thanks, Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From ewaldhorn at gmail.com Wed Aug 18 15:49:47 2010 From: ewaldhorn at gmail.com (Ewald Horn) Date: Wed, 18 Aug 2010 15:49:47 +0200 Subject: [Tutor] box drawing characters In-Reply-To: References: <4C6AA3F1.9090501@gmail.com> Message-ID: Hi Bill, have you given UniCurses a spin? See http://pyunicurses.sourceforge.net/ for more information. I recall finding it online, so it might be worth investigating. Good luck. Regards Ewald From davea at ieee.org Wed Aug 18 16:48:53 2010 From: davea at ieee.org (Dave Angel) Date: Wed, 18 Aug 2010 10:48:53 -0400 Subject: [Tutor] Need help understanding output... In-Reply-To: <4C6BE065.8050703@daemon.be> References: <4C63104F.70104@daemon.be> <201008120926.49330.steve@pearwood.info> <4C6BC24F.1080000@daemon.be> <4C6BE065.8050703@daemon.be> Message-ID: <4C6BF2D5.3010204@ieee.org> Laurens Vets wrote: > > > Yes of course :) That's a typo on my part. I came up with the > following which I think works as well? > > import random > reeks = [] > for i in range(60): > temp = [random.randint(1, 6)] > while reeks[-2:-1] == reeks[-1:] == temp: > temp = [random.randint(1, 6)] > if reeks.count(temp[0]) >= 10: > temp = [random.randint(1, 6)] > reeks.extend(temp) > print reeks > > Without actually trying it, I think you've got a problem in the reeks.count code. You only check the count if you've already match temp with the last two list items. I'd add the reeks.count logic as a compound "or" in the test of the while loop. And since that makes a pretty long line, I might then make a separate function of the "is temp a valid item to add to this list" *untested* : def is_valid(item, thelist): if len(list) >1 and (thelist[-2] == thelist[-1] == item): return False if thelist.count(item) >= 10: return False return True import random reeks = [] for i in range(60): temp = random.randint(1, 6) while not is_valid(temp): temp = random.randint(1, 6) reeks.append(temp) print reeks I also fixed the indentation to 4, and made temp a scalar instead of a list. DaveA From nitinchandra1 at gmail.com Wed Aug 18 17:14:36 2010 From: nitinchandra1 at gmail.com (nitin chandra) Date: Wed, 18 Aug 2010 20:44:36 +0530 Subject: [Tutor] Multiple file open Message-ID: Hi All, @ Alan - Thank you. Your suggestion worked. ( read 2 input file and 1 output file). I am on Python 2.6 I need to process two sets of 96 files and prepare equal no. of sets of 96 files. The first set of 96 files have a formula A and second set of 96 files have formula B. Formula A is derived as follows - from 2 input files in 2 different paths, read 4 columns each, (add, sub, div, etc) and write it to a One output file in 3rd different path.(This part is done, but will require me to run it 96 times, you can imagine my plight). Change the formula and make another PY script and then run it ..... 96 times ..... again ... So I was thinking like this create a CSV file with a list of files for formula A and create a 2nd CSV file with a list of files for formula B. as follows : column 1 will have full path of FIRST INPUT file to pass to the existing Program. column 2 will have full path of SECOND INPUT file to pass to the existing Program. column 3 will have full path of THIRD OUTPUT file to pass to the existing Program. a switch statement to choose between Formula A or Formula B or Exit. Please guide with the syntax. below is the existing program with Formula A (Mean). Formula B will be Extrapolation, also I have not been able to do justice to 'except IOError:' part.The program ends with an error. Thanks In Advance. Nitin ******************************** import sys,os, fileinput file11 = raw_input('Enter PR1 File name :') fp1 = open(file11,'r') file12 = raw_input('Enter PR3 File Name :') fp2 = open(file12,'r') file3 = raw_input('Enter PR2 / PR4 OUTPUT File Name :') fp3 = open(file3,'w') while True: try: line1A = fp1.readline() line1B = fp2.readline() line1 = line1A.split(",") col1 = line1[0] col2 = line1[1] col3 = line1[2] col4 = line1[3] col5 = line1[20] col6 = line1[21] col7 = line1[22] line2 = line1B.split(",") col8 = line2[1] col9 = line2[2] col10 = line2[3] col11 = line2[20] col12 = line2[21] col13 = line2[22] # calculation of PR2 as per formula #(A+B)/2 , ie. Mean of the two values col14 = ( (float(col2)) + (float(col8)) / 2) col15 = ( (float(col3)) + (float(col9)) / 2) col16 = ( (float(col4)) + (float(col10)) / 2) col17 = ( (float(col5)) + (float(col11)) / 2) col18 = ( (float(col6)) + (float(col12)) / 2) col19 = ( (float(col7)) + (float(col13)) / 2) print col1,col14,col15,col16,col17,col18,col19 str3 = '%s,%s,%s,%s,%s,%s,%s\n' % (col1,col14,col15,col16,col17,col18,col19) fp3.write(str3) except IOError: print 'Error in One of the Input Files' fp1.close() fp2.close() fp3.close() From alan.gauld at btinternet.com Wed Aug 18 19:36:48 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 18 Aug 2010 18:36:48 +0100 Subject: [Tutor] box drawing characters References: <4C6AA3F1.9090501@gmail.com> Message-ID: Looks interesting, a new one for me, thanks for posting. Alan G. "Ewald Horn" wrote in message news:AANLkTinMKzyXBd0T7rLdyExHbANw1tNFZac5Z2gEEO14 at mail.gmail.com... > Hi Bill, > > have you given UniCurses a spin? > > See http://pyunicurses.sourceforge.net/ for more information. > > I recall finding it online, so it might be worth investigating. > > Good luck. > > Regards > Ewald > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From wallenpb at gmail.com Wed Aug 18 21:13:57 2010 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 18 Aug 2010 14:13:57 -0500 Subject: [Tutor] box drawing characters In-Reply-To: References: <4C6AA3F1.9090501@gmail.com> Message-ID: On Wed, Aug 18, 2010 at 12:36 PM, Alan Gauld wrote: > Looks interesting, a new one for me, thanks for posting. > > Alan G. > > "Ewald Horn" wrote in message > news:AANLkTinMKzyXBd0T7rLdyExHbANw1tNFZac5Z2gEEO14 at mail.gmail.com... > > Hi Bill, >> >> have you given UniCurses a spin? >> >> See http://pyunicurses.sourceforge.net/ for more information. >> >> > This does look very interesting and the documentation seems to reflect a product that is quite complete. I will definitely give it a try. Thanks, Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Aug 18 23:24:24 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 19 Aug 2010 07:24:24 +1000 Subject: [Tutor] Need help understanding output... In-Reply-To: <4C6BC24F.1080000@daemon.be> References: <4C63104F.70104@daemon.be> <201008120926.49330.steve@pearwood.info> <4C6BC24F.1080000@daemon.be> Message-ID: <201008190724.25058.steve@pearwood.info> On Wed, 18 Aug 2010 09:21:51 pm Laurens Vets wrote: > On 8/12/2010 1:26 AM, Steven D'Aprano wrote: > > On Thu, 12 Aug 2010 07:04:15 am Laurens Vets wrote: > >> I need to generate a list of 30 numbers randomly chosen from 1, 2, > >> 3, 4, 5& 6. However, I cannot have more than 2 numbers which are > >> the same next to each other. [...] > Thank you all for your help! I've added another condition to this > program, namely, in a range of 60, each 'random' number can only > occur 10 times. I came up with the following: The more of these restrictions you add, the less random the sequence is. A truly random (that is, uniformly random) sequence should come up with 30 identical numbers occasionally. *Very* occasionally, to be sure, but it still should be possible. If what you need is a sequence of numbers which is only slightly random, then that's fine. But I don't fully understand what your aim is here. Anyway, here's my take on generating 30 semi-random integers from 1 to 6 where there are no more than 10 of each number and no more than two in a row of anything. Completely untested: def make_counts(total=30): counts = {} t = total for i in range(1, 7): n = random.randint(0, min(t, 10)) counts[i] = n t -= n assert sum(counts.values) == total # Is this guaranteed? return counts def make_seq(): result = [] counts = make_counts(30) for i in range(30): t = random.choose(counts.keys()) while [t] != result[-2:] if len(counts) == 1 and counts.keys() == result[-2:]: # Stuck! raise ValueError t = random.choose(counts.keys()) result.append(t) counts[t] -= 1 if counts[t] == 0: del counts[t] return result I'm a bit dubious about the assertion in make_counts... I think I need to be a bit more clever about generating the counts to guarantee that there will be exactly 30 in total. At the moment it only guarantees no more than 30. Note also the test inside the while loop in make_seq. Given your additional restriction, it might happen that you have a sequence like [blah blah... 3, 3] and 3 is the only remaining key in count. In that case, the while loop will never terminate. Another alternative is not to try to be clever at all. Instead, use a nice simple rejection method: * generate a list of thirty random numbers * reject it if it has 3 numbers in a row, or more than 10 of any number * if rejected, start again with a new random list -- Steven D'Aprano From sander.sweers at gmail.com Wed Aug 18 23:40:57 2010 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 18 Aug 2010 23:40:57 +0200 Subject: [Tutor] Multiple file open In-Reply-To: References: Message-ID: On 18 August 2010 17:14, nitin chandra wrote: > I am on Python 2.6 > > Please guide with the syntax. All beginners tutorials on the web teach the syntax of python.. I am unsure what your questions is. > below is the existing program with Formula A (Mean). Formula B will be > Extrapolation, > also I have not been able to do justice to 'except IOError:' part.The It has many errors which need fixing but.. > program ends with an error. And if you get an error always make sure you provide it to this list. People on this list can not read minds ;-). > ******************************** > import sys,os, fileinput > > > file11 = raw_input('Enter PR1 File name :') > fp1 = open(file11,'r') > > file12 = raw_input('Enter PR3 File Name :') > fp2 = open(file12,'r') > > file3 = raw_input('Enter PR2 / PR4 OUTPUT File Name :') > fp3 = open(file3,'w') What happens when you enter a wrong filename? It will raise IOError the moment you use open(). Below is 1 example of what you might want tot do. file11 = raw_input('Enter PR1 File name :') try: fp1 = open(ffile11, 'r') except IOError: sys.exit('Could not open file: %s' % file11) > while True: > ? try: > ? ? ? line1A = fp1.readline() You can read and split the line in 1 go. line1 = fp1.readline().split(",") > ? ? ? line1B = fp2.readline() > ? ? ? line1 = line1A.split(",") You can now remove the above, see earlier comment. > ? ? ? col1 = line1[0] > ? ? ? col2 = line1[1] > ? ? ? col3 = line1[2] > ? ? ? col4 = line1[3] > ? ? ? col5 = line1[20] > ? ? ? col6 = line1[21] > ? ? ? col7 = line1[22] > ? ? ? line2 = line1B.split(",") > ? ? ? col8 = line2[1] > ? ? ? col9 = line2[2] > ? ? ? col10 = line2[3] > ? ? ? col11 = line2[20] > ? ? ? col12 = line2[21] > ? ? ? col13 = line2[22] Above you create a list "line1 = fp1.readline().split(",")". Lists are mutable so you can add, remove and insert new items. You can also access the items in the list by index. You can even add 2 lists to make a new list, eg: . >>> [1,2,3,4,5] + [6,7,8,9,0] [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] Now try and apply this to all your col variables. > ? ? ? # calculation of PR2 as per formula > ? ? ? #(A+B)/2 , ie. Mean of the two values > ? ? ? col14 = ( (float(col2)) + (float(col8)) / 2) You can write this as: col14 = (float(line1[1])) + (float(line2[1])) / 2) And avoid creating all these col variables. But what would happen if col2/line1[1] has a value of "I am not a number"? Do note the comment below on the actual calculation. > ? ? ? col15 = ( (float(col3)) + (float(col9)) / 2) > ? ? ? col19 = ( (float(col7)) + (float(col13)) / 2) Your "mean" calculation is wrong (hint, division has precedence over adding). Greets Sander From nitin.162 at gmail.com Thu Aug 19 05:24:11 2010 From: nitin.162 at gmail.com (Nitin Das) Date: Thu, 19 Aug 2010 08:54:11 +0530 Subject: [Tutor] Immutable objects Message-ID: Hello, Can somebody help me how to make immutable objects in python. I have seen overriding the __new__, __setattr__ methods.. but not comfortable with how to use them to make the object immutable. thanks in advance --nitin -------------- next part -------------- An HTML attachment was scrubbed... URL: From nitin.162 at gmail.com Thu Aug 19 07:30:43 2010 From: nitin.162 at gmail.com (Nitin Das) Date: Thu, 19 Aug 2010 11:00:43 +0530 Subject: [Tutor] Immutable objects In-Reply-To: References: Message-ID: class mymut(object): def __setattr__(self,k,v): if hasattr(self,k): if self.__dict__.get(k) == None: self.__dict__[k] = v else: raise TypeError("Cant Modify Attribute Value") else: raise TypeError("Immutable Object") class mm(mymut): x = '' y = '' def __init__(self,x,y): self.x = x self.y = y p = mm(10,11) print p.x print p.y I have created this immutable object.Is there any other better implementation? thanks -- nitin On Thu, Aug 19, 2010 at 8:54 AM, Nitin Das wrote: > Hello, > > Can somebody help me how to make immutable objects in python. I have > seen overriding the __new__, __setattr__ methods.. but not comfortable with > how to use them to make the object immutable. > > thanks in advance > --nitin > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Aug 19 10:46:48 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 Aug 2010 09:46:48 +0100 Subject: [Tutor] Immutable objects References: Message-ID: "Nitin Das" wrote > class mymut(object): > > def __setattr__(self,k,v): > if hasattr(self,k): > if self.__dict__.get(k) == None: > self.__dict__[k] = v Do you need to look up the dict? Surely you could just use if self.k is None self.k = v which looks a lot simpler to me... > else: > raise TypeError("Cant Modify Attribute Value") You could mention the class for example. Compare it with the string and tuple messages: >>> 'fred'[2] = 'g' Traceback (most recent call last): File "", line 1, in TypeError: 'str' object does not support item assignment >>> (1,2,30)[1] = 5 Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment >>> So if your error said TypeError: mymut object does not support item assignment that would be more consistent with the Python internal objects. > else: > raise TypeError("Immutable Object") The Python immutables seem to raise an Attribute Error here rather than a Type error. And again mentioning the class name makes debugging easier: >>> 'l'.x = 4 Traceback (most recent call last): File "", line 1, in AttributeError: 'str' object has no attribute 'x' >>> HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From rwobben at hotmail.com Thu Aug 19 13:31:24 2010 From: rwobben at hotmail.com (Roelof Wobben) Date: Thu, 19 Aug 2010 11:31:24 +0000 Subject: [Tutor] question about a exercise. Message-ID: Hello, I follow the online book " How to think like a computer scientist". But now I have a problem with a exercise. This is not homework. The exercise is : Using a text editor, create a Python script named tryme3.py . Write a function in this file called nine_lines that uses three_lines to print nine blank lines. Now add a function named clear_screen that prints out twenty-five blank lines. The last line of your program should be a call to clear_screen. So I begin with this code : def threelines(): print print print print "regel 1" threelines() print "regel 2" But now I get a terminated at line 2 message. What did I do wrong. I work on a Win7 machine with python 2.7 and as a editor SPE. Regards, Roelof -------------- next part -------------- An HTML attachment was scrubbed... URL: From jdmccla at regence.com Thu Aug 19 13:02:16 2010 From: jdmccla at regence.com (James D Mcclatchey) Date: Thu, 19 Aug 2010 04:02:16 -0700 Subject: [Tutor] AUTO: James D Mcclatchey is out of the office. (returning 09/07/2010) Message-ID: I am out of the office until 09/07/2010. I will respond to your message when I return. Note: This is an automated response to your message "Tutor Digest, Vol 78, Issue 83" sent on 8/19/10 3:00:03. This is the only notification you will receive while this person is away. *IMPORTANT NOTICE: This communication, including any attachment, contains information that may be confidential or privileged, and is intended solely for the entity or individual to whom it is addressed. If you are not the intended recipient, you should delete this message and are hereby notified that any disclosure, copying, or distribution of this message is strictly prohibited. Nothing in this email, including any attachment, is intended to be a legally binding signature. * -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Aug 19 13:41:11 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 19 Aug 2010 21:41:11 +1000 Subject: [Tutor] Immutable objects In-Reply-To: References: Message-ID: <201008192141.12246.steve@pearwood.info> On Thu, 19 Aug 2010 01:24:11 pm Nitin Das wrote: > Hello, > > Can somebody help me how to make immutable objects in python. I > have seen overriding the __new__, __setattr__ methods.. but not > comfortable with how to use them to make the object immutable. > > thanks in advance > --nitin I have found this useful: http://northernplanets.blogspot.com/2007/01/immutable-instances-in-python.html Keep in mind that the only way to make *truly* immutable objects in Python is to write them in C. Immutability of pure-Python objects can be broken if you try hard enough. Immutability is by cooperation, not enforced. -- Steven D'Aprano From joel.goldstick at gmail.com Thu Aug 19 14:37:25 2010 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 19 Aug 2010 08:37:25 -0400 Subject: [Tutor] question about a exercise. In-Reply-To: References: Message-ID: Can you copy and paste the exact error message you receive in the traceback when you run your program. Also, copy the complete program here since it is only a handful of lines On Thu, Aug 19, 2010 at 7:31 AM, Roelof Wobben wrote: > Hello, > > I follow the online book " How to think like a computer scientist". > But now I have a problem with a exercise. > This is not homework. > > The exercise is : > > Using a text editor, create a Python script named tryme3.py . Write a > function in this file called nine_lines that uses three_lines to print > nine blank lines. Now add a function named clear_screen that prints out > twenty-five blank lines. The last line of your program should be a *call*to > clear_screen. > > So I begin with this code : > > def threelines(): > print > print > print > > print "regel 1" > threelines() > print "regel 2" > > But now I get a terminated at line 2 message. > What did I do wrong. > > I work on a Win7 machine with python 2.7 and as a editor SPE. > > Regards, > > Roelof > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Aug 19 14:53:43 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 19 Aug 2010 14:53:43 +0200 Subject: [Tutor] Immutable objects References: Message-ID: Nitin Das wrote: > class mymut(object): > > def __setattr__(self,k,v): > if hasattr(self,k): > if self.__dict__.get(k) == None: > self.__dict__[k] = v > else: > raise TypeError("Cant Modify Attribute Value") > else: > raise TypeError("Immutable Object") > > > class mm(mymut): > x = '' > y = '' > def __init__(self,x,y): > self.x = x > self.y = y > > > > p = mm(10,11) > print p.x > print p.y > > > I have created this immutable object.Is there any other better > implementation? How about >>> from collections import namedtuple >>> Mm = namedtuple("Mm", "x y") >>> p = Mm(10, 11) >>> p.x 10 >>> p.y 11 >>> p.x = 42 Traceback (most recent call last): File "", line 1, in AttributeError: can't set attribute >>> p.z = 42 Traceback (most recent call last): File "", line 1, in AttributeError: 'Mm' object has no attribute 'z' >>> Peter From rwobben at hotmail.com Thu Aug 19 14:55:16 2010 From: rwobben at hotmail.com (Roelof Wobben) Date: Thu, 19 Aug 2010 12:55:16 +0000 Subject: [Tutor] question about a exercise. In-Reply-To: References: , Message-ID: Hello, I don't see a traceback only this output. regel 1 regel 2 script terminated. And the code I gave you was the whole code because Im still working on this one. I have learned to do one problem at the time so in mu opion first make the part which prints out 3 lines and then expand to 9 lines and then expand to the function clear_screen Roelof Date: Thu, 19 Aug 2010 08:37:25 -0400 Subject: Re: [Tutor] question about a exercise. From: joel.goldstick at gmail.com To: rwobben at hotmail.com CC: tutor at python.org Can you copy and paste the exact error message you receive in the traceback when you run your program. Also, copy the complete program here since it is only a handful of lines On Thu, Aug 19, 2010 at 7:31 AM, Roelof Wobben wrote: Hello, I follow the online book " How to think like a computer scientist". But now I have a problem with a exercise. This is not homework. The exercise is : Using a text editor, create a Python script named tryme3.py . Write a function in this file called nine_lines that uses three_lines to print nine blank lines. Now add a function named clear_screen that prints out twenty-five blank lines. The last line of your program should be a call to clear_screen. So I begin with this code : def threelines(): print print print print "regel 1" threelines() print "regel 2" But now I get a terminated at line 2 message. What did I do wrong. I work on a Win7 machine with python 2.7 and as a editor SPE. Regards, Roelof _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Aug 19 14:58:12 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 19 Aug 2010 14:58:12 +0200 Subject: [Tutor] Immutable objects References: Message-ID: Peter Otten wrote: > Nitin Das wrote: > >> class mymut(object): >> >> def __setattr__(self,k,v): >> if hasattr(self,k): >> if self.__dict__.get(k) == None: >> self.__dict__[k] = v >> else: >> raise TypeError("Cant Modify Attribute Value") >> else: >> raise TypeError("Immutable Object") >> >> >> class mm(mymut): >> x = '' >> y = '' >> def __init__(self,x,y): >> self.x = x >> self.y = y >> >> >> >> p = mm(10,11) >> print p.x >> print p.y >> >> >> I have created this immutable object.Is there any other better >> implementation? > > How about > >>>> from collections import namedtuple >>>> Mm = namedtuple("Mm", "x y") >>>> p = Mm(10, 11) >>>> p.x > 10 >>>> p.y > 11 >>>> p.x = 42 > Traceback (most recent call last): > File "", line 1, in > AttributeError: can't set attribute >>>> p.z = 42 > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'Mm' object has no attribute 'z' >>>> By the way, you can see the class definition with namedtuple("Mm", "x y", verbose=True) Peter From alan.gauld at btinternet.com Thu Aug 19 15:28:02 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 Aug 2010 14:28:02 +0100 Subject: [Tutor] question about a exercise. References: , Message-ID: "Roelof Wobben" wrote > I don't see a traceback only this output. That looks about right to me, what did you expect to see that was different? ======================== regel 1 regel 2 script terminated. ========================= > I have learned to do one problem at the time so in mu opion first > make > the part which prints out 3 lines and then expand to 9 lines and > then > expand to the function clear_screen Yes thats good thinking. HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From nitinchandra1 at gmail.com Thu Aug 19 16:28:13 2010 From: nitinchandra1 at gmail.com (nitin chandra) Date: Thu, 19 Aug 2010 19:58:13 +0530 Subject: [Tutor] Multiple file open In-Reply-To: References: Message-ID: Hello All, >> Please guide with the syntax. > > All beginners tutorials on the web teach the syntax of python.. I am > unsure what your questions is. My bad .... with code. > >> below is the existing program with Formula A (Mean). Formula B will be >> Extrapolation, >> also I have not been able to do justice to 'except IOError:' part.The > > It has many errors which need fixing but.. > >> program ends with an error. > > And if you get an error always make sure you provide it to this list. > People on this list can not read minds ;-). I was wondering ... what else i need to post. Thank you. I REALLY need to keep that in mind. > >> ******************************** >> import sys,os, fileinput >> >> >> file11 = raw_input('Enter PR1 File name :') >> fp1 = open(file11,'r') >> >> file12 = raw_input('Enter PR3 File Name :') >> fp2 = open(file12,'r') >> >> file3 = raw_input('Enter PR2 / PR4 OUTPUT File Name :') >> fp3 = open(file3,'w') > > What happens when you enter a wrong filename? It will raise IOError > the moment you use open(). Below is 1 example of what you might want > tot do. > > file11 = raw_input('Enter PR1 File name :') > try: > ? ?fp1 = open(ffile11, 'r') > except IOError: > ? sys.exit('Could not open file: %s' % file11) > Adding this 'try-except' >> while True: >> ? try: >> ? ? ? line1A = fp1.readline() > > You can read and split the line in 1 go. > ? ? ? ? line1 = fp1.readline().split(",") :) so much better ... adding again. > >> ? ? ? line1B = fp2.readline() >> ? ? ? line1 = line1A.split(",") > > You can now remove the above, see earlier comment. > >> ? ? ? col1 = line1[0] >> ? ? ? col2 = line1[1] >> ? ? ? col3 = line1[2] >> ? ? ? col4 = line1[3] >> ? ? ? col5 = line1[20] >> ? ? ? col6 = line1[21] >> ? ? ? col7 = line1[22] >> ? ? ? line2 = line1B.split(",") >> ? ? ? col8 = line2[1] >> ? ? ? col9 = line2[2] >> ? ? ? col10 = line2[3] >> ? ? ? col11 = line2[20] >> ? ? ? col12 = line2[21] >> ? ? ? col13 = line2[22] > > Above you create a list "line1 = fp1.readline().split(",")". Lists are > mutable so you can add, remove and insert new items. You can also > access the items in the list by index. You can even add 2 lists to > make a new list, eg: . > >>>> [1,2,3,4,5] + [6,7,8,9,0] > [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] > > Now try and apply this to all your col variables. Actually I needed to do further computation, therefore I preferred to keep the values separate. > >> ? ? ? # calculation of PR2 as per formula >> ? ? ? #(A+B)/2 , ie. Mean of the two values >> ? ? ? col14 = ( (float(col2)) + (float(col8)) / 2) > > You can write this as: > ?col14 = (float(line1[1])) + (float(line2[1])) / 2) I did this in one of my attempts. Pl dont ask me what was the error. Did not save. > > And avoid creating all these col variables. But what would happen if > col2/line1[1] has a value of "I am not a number"? Do note the comment > below on the actual calculation. I am keeping (cleaning) the Input data file as per the program. > >> ? ? ? col15 = ( (float(col3)) + (float(col9)) / 2) > >> ? ? ? col19 = ( (float(col7)) + (float(col13)) / 2) > > Your "mean" calculation is wrong (hint, division has precedence over adding). THANKS .... aarrhh ... I missed another pair of braces. > > Greets > Sander > Once the Final version is over will post it. Thanks Nitin From nitin.162 at gmail.com Thu Aug 19 16:47:57 2010 From: nitin.162 at gmail.com (Nitin Das) Date: Thu, 19 Aug 2010 20:17:57 +0530 Subject: [Tutor] Immutable objects In-Reply-To: References: Message-ID: Thanks guys, NamedTuple implementation is preety nice solution. --nitin On Thu, Aug 19, 2010 at 6:28 PM, Peter Otten <__peter__ at web.de> wrote: > Peter Otten wrote: > > > Nitin Das wrote: > > > >> class mymut(object): > >> > >> def __setattr__(self,k,v): > >> if hasattr(self,k): > >> if self.__dict__.get(k) == None: > >> self.__dict__[k] = v > >> else: > >> raise TypeError("Cant Modify Attribute Value") > >> else: > >> raise TypeError("Immutable Object") > >> > >> > >> class mm(mymut): > >> x = '' > >> y = '' > >> def __init__(self,x,y): > >> self.x = x > >> self.y = y > >> > >> > >> > >> p = mm(10,11) > >> print p.x > >> print p.y > >> > >> > >> I have created this immutable object.Is there any other better > >> implementation? > > > > How about > > > >>>> from collections import namedtuple > >>>> Mm = namedtuple("Mm", "x y") > >>>> p = Mm(10, 11) > >>>> p.x > > 10 > >>>> p.y > > 11 > >>>> p.x = 42 > > Traceback (most recent call last): > > File "", line 1, in > > AttributeError: can't set attribute > >>>> p.z = 42 > > Traceback (most recent call last): > > File "", line 1, in > > AttributeError: 'Mm' object has no attribute 'z' > >>>> > > By the way, you can see the class definition with > > namedtuple("Mm", "x y", verbose=True) > > Peter > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pkoek11 at xs4all.nl Thu Aug 19 16:51:41 2010 From: pkoek11 at xs4all.nl (Pete) Date: Thu, 19 Aug 2010 10:51:41 -0400 Subject: [Tutor] List comprehension for dicts? Message-ID: <3D2D5909-C0E3-4086-86BC-863CF437F6C3@xs4all.nl> Hi, I've been reading up on list comprehensions lately, all userful and powerful stuff - trying to wrap my brain around it :) As the examples all seem to relate to lists, I was wondering if there is an elegant similar way to apply a function to all keys in a dictionary? (without looping over it, of course) I'm trying to convert all keys in a dict to uppercase, as in: INPUT: age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 } OUTPUT: age_dict = { 'PETE': 42, 'ANN': 25, 'CARL': 30, 'AMANDA': 64 } I googled 'dictionary comprehension' but couldn't get any code to work with the examples given. http://www.siafoo.net/article/52#dictionary-comprehensions thanks, Pete From vince at vinces.ca Thu Aug 19 17:02:07 2010 From: vince at vinces.ca (Vince Spicer) Date: Thu, 19 Aug 2010 09:02:07 -0600 Subject: [Tutor] List comprehension for dicts? In-Reply-To: <3D2D5909-C0E3-4086-86BC-863CF437F6C3@xs4all.nl> References: <3D2D5909-C0E3-4086-86BC-863CF437F6C3@xs4all.nl> Message-ID: Hey you can use list comprehension here age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 } you can create a dict from a list of tuples and you can access the dict as a list of tuples by accessing its items Example: age_dict = dict([(key.upper(), value) for key,value in age_dict.items()]) hope that helps, Vince On Thu, Aug 19, 2010 at 8:51 AM, Pete wrote: > Hi, > > I've been reading up on list comprehensions lately, all userful and > powerful stuff - trying to wrap my brain around it :) > > As the examples all seem to relate to lists, I was wondering if there is an > elegant similar way to apply a function to all keys in a dictionary? > > (without looping over it, of course) > > I'm trying to convert all keys in a dict to uppercase, as in: > > INPUT: > age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 } > > OUTPUT: > age_dict = { 'PETE': 42, 'ANN': 25, 'CARL': 30, 'AMANDA': 64 } > > I googled 'dictionary comprehension' but couldn't get any code to work with > the examples given. > > http://www.siafoo.net/article/52#dictionary-comprehensions > > thanks, > > Pete > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Aug 19 17:20:18 2010 From: __peter__ at web.de (Peter Otten) Date: Thu, 19 Aug 2010 17:20:18 +0200 Subject: [Tutor] List comprehension for dicts? References: <3D2D5909-C0E3-4086-86BC-863CF437F6C3@xs4all.nl> Message-ID: Pete wrote: > Hi, > > I've been reading up on list comprehensions lately, all userful and > powerful stuff - trying to wrap my brain around it :) > > As the examples all seem to relate to lists, I was wondering if there is > an elegant similar way to apply a function to all keys in a dictionary? > > (without looping over it, of course) > > I'm trying to convert all keys in a dict to uppercase, as in: > > INPUT: > age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 } > > OUTPUT: > age_dict = { 'PETE': 42, 'ANN': 25, 'CARL': 30, 'AMANDA': 64 } > > I googled 'dictionary comprehension' but couldn't get any code to work > with the examples given. Python 2.4-2.6 >>> dict((k.upper(), v) for k, v in age_dict.iteritems()) {'PETE': 42, 'ANN': 25, 'AMANDA': 64, 'CARL': 30} Python 2.7 >>> {k.upper(): v for k, v in age_dict.iteritems()} {'PETE': 42, 'ANN': 25, 'AMANDA': 64, 'CARL': 30} Python 3.x >>> {k.upper(): v for k, v in age_dict.items()} {'PETE': 42, 'ANN': 25, 'AMANDA': 64, 'CARL': 30} items() instead of iteritems() works in 2.x, too, but is less efficient. Peter From waynejwerner at gmail.com Thu Aug 19 17:40:54 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 19 Aug 2010 10:40:54 -0500 Subject: [Tutor] List comprehension for dicts? In-Reply-To: References: <3D2D5909-C0E3-4086-86BC-863CF437F6C3@xs4all.nl> Message-ID: On Thu, Aug 19, 2010 at 10:02 AM, Vince Spicer wrote: > Hey you can use list comprehension here > > > age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 } > > you can create a dict from a list of tuples and you can access the dict as > a > list of tuples by accessing its items > > Example: > > age_dict = dict([(key.upper(), value) for key,value in age_dict.items()]) > This is a bad place to use a list comprehension. This will create a list of values first and then create a dict from that list, so now you have a list floating around that you didn't need. Generator expressions, OTOH, generate the values on the fly, only as they're needed, so there's no extra list left over once the dict is created. Sure it will eventually be garbage collected, but "waste not, want not", as my grandmother used to say. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From anand.shashwat at gmail.com Thu Aug 19 17:42:31 2010 From: anand.shashwat at gmail.com (Shashwat Anand) Date: Thu, 19 Aug 2010 21:12:31 +0530 Subject: [Tutor] List comprehension for dicts? In-Reply-To: <3D2D5909-C0E3-4086-86BC-863CF437F6C3@xs4all.nl> References: <3D2D5909-C0E3-4086-86BC-863CF437F6C3@xs4all.nl> Message-ID: On Thu, Aug 19, 2010 at 8:21 PM, Pete wrote: > Hi, > > I've been reading up on list comprehensions lately, all userful and > powerful stuff - trying to wrap my brain around it :) > > As the examples all seem to relate to lists, I was wondering if there is an > elegant similar way to apply a function to all keys in a dictionary? > > (without looping over it, of course) > > I'm trying to convert all keys in a dict to uppercase, as in: > > INPUT: > age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 } > > OUTPUT: > age_dict = { 'PETE': 42, 'ANN': 25, 'CARL': 30, 'AMANDA': 64 } > > I googled 'dictionary comprehension' but couldn't get any code to work with > the examples given. > > http://www.siafoo.net/article/52#dictionary-comprehensions > > thanks, > There is dict comprehension too from python2.7 onwards. > > Pete > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- ~l0nwlf -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Thu Aug 19 19:20:12 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 20 Aug 2010 03:20:12 +1000 Subject: [Tutor] List comprehension for dicts? In-Reply-To: References: <3D2D5909-C0E3-4086-86BC-863CF437F6C3@xs4all.nl> Message-ID: <201008200320.12682.steve@pearwood.info> On Fri, 20 Aug 2010 01:40:54 am Wayne Werner wrote: > > age_dict = dict([(key.upper(), value) for key,value in > > age_dict.items()]) > > This is a bad place to use a list comprehension. This will create a > list of values first and then create a dict from that list, so now > you have a list floating around that you didn't need. How do you know that dict() doesn't need it the entire list at once? Unless you're an expert on the implementation, for all you know it looks something like this: class dict: def __new__(cls, arg): ... try: n = len(arg) except AttributeError: # probably a generator expression arg = list(arg) n = len(arg) allocate_memory_for_items(n) ... (only written in C). I'm not saying it does, or that it doesn't, but you're assuming a pattern of behaviour which might not be the case. Here's a similarly common idiom: which of these is faster? ' '.join(gen_expr) ' '.join(list_comp) [steve at sylar ~]$ python -m timeit "' '.join(str(n) for n in xrange(300000))" 10 loops, best of 3: 437 msec per loop [steve at sylar ~]$ python -m timeit "' '.join([str(n) for n in xrange(300000)])" 10 loops, best of 3: 401 msec per loop The list comprehension is consistently faster, because join() works more efficiently if it knows how many items it needs to pre-allocate memory for. > Generator expressions, OTOH, generate the values on the fly, only as > they're needed, so there's no extra list left over once the dict is > created. And sometimes that's a win, and sometimes it's not. Generator expressions are more computationally expensive than lists -- they're functions which remember their internal state so you can pause them and restart them at will. That doesn't happen for free -- it takes memory and time. The reason Python has generator expressions is that for large amounts of data, the saving you have by not needing to produce the entire list all at once more than makes up for the extra cost, but for small amounts of data, that's not always the case: [steve at sylar ~]$ python -m timeit "dict((k,k+1) for k in xrange(2))" 100000 loops, best of 3: 5.89 usec per loop [steve at sylar ~]$ python -m timeit "dict([(k,k+1) for k in xrange(2)])" 100000 loops, best of 3: 4.78 usec per loop Here, using a generator expression is a pessimation, not an optimization. > Sure it will eventually be garbage collected, but "waste not, want > not", as my grandmother used to say. Does your grandmother have a box labelled "Pieces of string, too short to use" as well? -- Steven D'Aprano From davea at ieee.org Thu Aug 19 20:27:55 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 19 Aug 2010 14:27:55 -0400 Subject: [Tutor] List comprehension for dicts? In-Reply-To: References: <3D2D5909-C0E3-4086-86BC-863CF437F6C3@xs4all.nl> Message-ID: <4C6D77AB.80904@ieee.org> (You top-posted, so now I have to delete the older part) Vince Spicer wrote: > Hey you can use list comprehension here > > age_dict = { 'pete': 42, 'ann': 25, 'carl': 30, 'amanda': 64 } > > you can create a dict from a list of tuples and you can access the dict as > a > list of tuples by accessing its items > > Example: > > age_dict = dict([(key.upper(), value) for key,value in age_dict.items()]) > > hope that helps, > > Vince > > The only catch to that is that two or more of the keys may map to the same uppercase key. If one needs to detect that, one has to write an explicit loop, rather than just converting with dict() DaveA From rwobben at hotmail.com Thu Aug 19 21:01:55 2010 From: rwobben at hotmail.com (Roelof Wobben) Date: Thu, 19 Aug 2010 19:01:55 +0000 Subject: [Tutor] flow problem with a exercise Message-ID: Hello, I have this exercise: Now write the function is_odd(n) that returns True when n is odd and False otherwise. Include doctests for this function as you write it. Finally, modify it so that it uses a call to is_even to determine if its argument is an odd integer. So I thought of this : def is_even(argument): remainder= argument%2 if remainder == 0 : return True else : return False def is_odd(argument): uitkomst=is_even(argument) return uitkomst even=is_odd(1) ; if even==True : print "Even getal" if even==False: print "Oneven getal" But now I get this error message : return uitkomst Syntax error : return outside function. In my opinon even calls is_odd , then uitkomst calls is_even which gives a true or false to uitkomst. So return uitkomst gives the outcome to even. But the intepreter thinks otherwise. I work on a Win7 machine with Python 2.7 Roelof -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Thu Aug 19 21:27:01 2010 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 19 Aug 2010 15:27:01 -0400 Subject: [Tutor] flow problem with a exercise In-Reply-To: References: Message-ID: On Thu, Aug 19, 2010 at 3:01 PM, Roelof Wobben wrote: > Hello, > > I have this exercise: > > > Now write the function is_odd(n) that returns True when n is odd and Falseotherwise. Include doctests for this function as you write it. > Finally, modify it so that it uses a call to is_even to determine if its > argument is an odd integer. > > So I thought of this : > > def is_even(argument): > remainder= argument%2 > if remainder == 0 : > return True > else : > return False > > def is_odd(argument): > uitkomst=is_even(argument) > return uitkomst > NOTE that your return statement is not indented properly. It must line up under uitkomst > > even=is_odd(1) ; > if even==True : > print "Even getal" > if even==False: > print "Oneven getal" > > > But now I get this error message : > > return uitkomst > Syntax error : return outside function. > > > In my opinon even calls is_odd , then uitkomst calls is_even which gives a > true or false to uitkomst. So return uitkomst gives the outcome to even. > But the intepreter thinks otherwise. > > I work on a Win7 machine with Python 2.7 > > Roelof > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Thu Aug 19 21:43:04 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Thu, 19 Aug 2010 14:43:04 -0500 Subject: [Tutor] flow problem with a exercise In-Reply-To: References: Message-ID: On Thu, Aug 19, 2010 at 2:01 PM, Roelof Wobben wrote: > > def is_odd(argument): > uitkomst=is_even(argument) > return uitkomst > > even=is_odd(1) ; > if even==True : > print "Even getal" > if even==False: > print "Oneven getal" > > > But now I get this error message : > > return uitkomst > Syntax error : return outside function. > Check your indention. In the email your return is at a different level than your function. Always use 4 spaces. If your editor can't convert, you need a better editor! > In my opinon even calls is_odd , then uitkomst calls is_even which gives a > true or false to uitkomst. So return uitkomst gives the outcome to even. > But the intepreter thinks otherwise. > Well, good thing opinions don't count for much when talking to a computer ;) You are correct that uitkomst contains the result of is_even, but your return is on a different indention level. Whitespace is significant here. If I were you, I would define is_odd this way: def is_odd(argument): uitkomst = not is_even(argument) return uitkomst > I work on a Win7 machine with Python 2.7 > Good job providing both the traceback and your system. They make every problem easier to debug. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From mehgcap at gmail.com Thu Aug 19 21:44:52 2010 From: mehgcap at gmail.com (Alex Hall) Date: Thu, 19 Aug 2010 15:44:52 -0400 Subject: [Tutor] flow problem with a exercise In-Reply-To: References: Message-ID: On 8/19/10, Roelof Wobben wrote: > > Hello, > > > > I have this exercise: > > > > Now write the function is_odd(n) that returns True when n is odd and False > otherwise. Include doctests for this function as you write it. > Finally, modify it so that it uses a call to is_even to determine if its > argument is an odd integer. > > > > So I thought of this : > > > > def is_even(argument): > remainder= argument%2 > if remainder == 0 : > return True > else : > return False > > > def is_odd(argument): > uitkomst=is_even(argument) > return uitkomst The above line, the return statement, has to be indented; it did not appear to be in your email. Also, maybe you want to return the opposite of is_even in is_odd? Right now it looks like you are going to get something like: is_odd(3): is_even(3)=False, so is_odd(3) will echo that False. Maybe return !uitkomst instead. I could have read it wrong, though. > > > even=is_odd(1) ; > if even==True : > print "Even getal" > if even==False: > print "Oneven getal" > > > > But now I get this error message : > > > > return uitkomst > > Syntax error : return outside function. > > > > > > In my opinon even calls is_odd , then uitkomst calls is_even which gives a > true or false to uitkomst. So return uitkomst gives the outcome to even. > > But the intepreter thinks otherwise. > > > > I work on a Win7 machine with Python 2.7 > > > > Roelof > > > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From davea at ieee.org Thu Aug 19 22:40:59 2010 From: davea at ieee.org (Dave Angel) Date: Thu, 19 Aug 2010 16:40:59 -0400 Subject: [Tutor] flow problem with a exercise In-Reply-To: References: Message-ID: <4C6D96DB.9050506@ieee.org> Roelof Wobben wrote: > > > def is_odd(argument): > uitkomst=is_even(argument) > return uitkomst > > > > > > You forgot to indent the return statement to match the other statement(s) in the function. DaveA From emile at fenx.com Thu Aug 19 23:25:34 2010 From: emile at fenx.com (Emile van Sebille) Date: Thu, 19 Aug 2010 14:25:34 -0700 Subject: [Tutor] List comprehension for dicts? In-Reply-To: <3D2D5909-C0E3-4086-86BC-863CF437F6C3@xs4all.nl> References: <3D2D5909-C0E3-4086-86BC-863CF437F6C3@xs4all.nl> Message-ID: On 8/19/2010 7:51 AM Pete said... > Hi, > > I've been reading up on list comprehensions lately, all userful and powerful stuff - trying to wrap my brain around it :) > > As the examples all seem to relate to lists, I was wondering if there is an elegant similar way to apply a function to all keys in a dictionary? > > (without looping over it, of course) Just fyi, as it sounds you may not understand. List Comprehensions loop over the list. There's no other magic going on that avoids that. result = [ ii for ii in lst if cond ] is just shorthand for result = [] for ii in lst: if cond: result.append(ii) Emile From pkoek11 at xs4all.nl Fri Aug 20 01:51:08 2010 From: pkoek11 at xs4all.nl (Pete) Date: Thu, 19 Aug 2010 19:51:08 -0400 Subject: [Tutor] List comprehension for dicts? In-Reply-To: References: <3D2D5909-C0E3-4086-86BC-863CF437F6C3@xs4all.nl> Message-ID: On 2010-08-19, at 5:25 PM, Emile van Sebille wrote: > On 8/19/2010 7:51 AM Pete said... >> Hi, >> >> I've been reading up on list comprehensions lately, all userful and powerful stuff - trying to wrap my brain around it :) >> >> As the examples all seem to relate to lists, I was wondering if there is an elegant similar way to apply a function to all keys in a dictionary? >> >> (without looping over it, of course) > > Just fyi, as it sounds you may not understand. List Comprehensions loop over the list. There's no other magic going on that avoids that. > > result = [ ii for ii in lst if cond ] > > is just shorthand for > > result = [] > for ii in lst: > if cond: > result.append(ii) > > Emile Ah, so list comprehensions are a purely syntactic construct? I had the feeling there might be a performance benefit of some kind. thanks for all the contributions on this topic, it's been greatly helpful to my understanding. -Pete From steve at pearwood.info Fri Aug 20 03:00:10 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 20 Aug 2010 11:00:10 +1000 Subject: [Tutor] List comprehension for dicts? In-Reply-To: References: <3D2D5909-C0E3-4086-86BC-863CF437F6C3@xs4all.nl> Message-ID: <201008201100.10856.steve@pearwood.info> On Fri, 20 Aug 2010 09:51:08 am Pete wrote: [...] > Ah, so list comprehensions are a purely syntactic construct? No, I don't think that's what Emile was trying to say. It's not like list comps are macros that are expanded into the explicit for-loop like that. All he is saying is that both the for-loop and the list comprehension loop over the list. There are some functional differences: for example, the list comp avoids needing to look up result.append over and over again. Because it knows it is dealing with a list, rather than some arbitrary object that conceivably might have some weird append method with strange side-effects, it can take optimizing short-cuts that aren't applicable to general for-loops. > I had the feeling there might be a performance benefit of some kind. If you write the for-loop in the most straight forward, obvious fashion, then there is a small but measurable performance cost from repeatedly looking up the append method. On the other hand, for-loops are more general -- you can call break to exit early, or continue to skip an iteration, so they're easier to optimize. There's no way to break out of a list comp early (other than raising an exception, which defeats the purpose). No matter how fast you can perform a loop, it's always faster to avoid it altogether, so this: seq = xrange(10000000) result = [] for i in seq: if i >= 10: break result.append(i%2) will be much faster than this: seq = xrange(10000000) result = [i%2 for i in seq if i < 10] Other than that, the speed of the loop itself is virtually the same as the speed of the list comprehension. -- Steven D'Aprano From nitinchandra1 at gmail.com Fri Aug 20 09:28:42 2010 From: nitinchandra1 at gmail.com (nitin chandra) Date: Fri, 20 Aug 2010 12:58:42 +0530 Subject: [Tutor] Multiple file open In-Reply-To: References: Message-ID: Hello All, I am getting the "Invalid Syntax" error. I am on Python 2.6. Thanks In Advance Nitin **************************************************** import sys,os, fileinput FileA = raw_input('Enter CSV file with lists of Files:') try: fp6 = open(FileA,'r') except IOError: ## I am getting the following error at this line:- ## ## File "mer5Pr2.py", line 7 ## except IOError: ## ^ ## SyntaxError: invalid syntax sys.exit('Could not open file: %s' % FileA) while True: lines = fp6.readline().split(",") file11 = lines[0] file12 = lines[1] file3 = lines[2] #file11 = raw_input('Enter PR1 File name :') #fp1 = open(file11,'r') try: fp1 = open(file11, 'r') except IOError: sys.exit('Could not open file: %s' % file11) #file12 = raw_input('Enter PR3 File Name :') #fp2 = open(file12,'r') try: fp2 = open(file12, 'r') except IOError: sys.exit('Could not open file: %s' % file12) #file3 = raw_input('Enter PR2 OUTPUT File Name :') try: fp3 = open(file3,'w') except IOError: sys.exit('Could not open file %s to Write' % file3) while True: try: line1 = fp1.readline().split(",") line2 = fp2.readline().split(",") #line1 = line1A.split(",") col1 = line1[0] col2 = line1[1] col3 = line1[2] col4 = line1[3] col5 = line1[20] col6 = line1[21] col7 = line1[22] #line2 = line1B.split(",") col8 = line2[1] col9 = line2[2] col10 = line2[3] col11 = line2[20] col12 = line2[21] col13 = line2[22] #def __FormulaPR2(): #claculation of PR2 as per formula #(A+B)/2 , ie. Mean of the two values col14 = (((float(col2)) + (float(col8))) / 2) col15 = (((float(col3)) + (float(col9))) / 2) col16 = (((float(col4)) + (float(col10))) / 2) col17 = (((float(col5)) + (float(col11))) / 2) col18 = (((float(col6)) + (float(col12))) / 2) col19 = (((float(col7)) + (float(col13))) / 2) print col1,col14,col15,col16,col17,col18,col19 str3 = '%s,%s,%s,%s,%s,%s,%s\n' % (col1,col14,col15,col16,col17,col18,col19) fp3.write(str3) #def __FormulaPR4(): #calculation of PR4 as per formula #(B-C)+3 , ie. Extrapolation of the values fp1.close() fp2.close() fp3.close() From knacktus at googlemail.com Fri Aug 20 09:49:26 2010 From: knacktus at googlemail.com (Knacktus) Date: Fri, 20 Aug 2010 09:49:26 +0200 Subject: [Tutor] Elementtree and pretty printing in Python 2.7 Message-ID: <4C6E3386.9070903@googlemail.com> Hi guys, I'm using Python 2.7 and the ElementTree standard-lib to write some xml. My output xml has no line breaks! So, it looks like that: instead of something like this: I'm aware of lxml which seems to have a pretty print option, but I would prefer to use the standard-lib ElementTree which seems not to have a feature like this. Do I miss something using the ElementTree-lib or is it bug? Cheers, Jan From steve at pearwood.info Fri Aug 20 09:57:31 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 20 Aug 2010 17:57:31 +1000 Subject: [Tutor] Multiple file open In-Reply-To: References: Message-ID: <201008201757.31919.steve@pearwood.info> On Fri, 20 Aug 2010 05:28:42 pm nitin chandra wrote: > try: > fp6 = open(FileA,'r') > except IOError: You need to outdent the except line: try: fp6 = open(FileA,'r') except IOError: sys.exit('Could not open file: %s' % FileA) -- Steven D'Aprano From alan.gauld at btinternet.com Fri Aug 20 09:58:56 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 20 Aug 2010 08:58:56 +0100 Subject: [Tutor] Multiple file open References: Message-ID: "nitin chandra" wrote > FileA = raw_input('Enter CSV file with lists of Files:') > try: > fp6 = open(FileA,'r') > except IOError: > > ## I am getting the following error at this line:- > ## > ## File "mer5Pr2.py", line 7 > ## except IOError: > ## ^ > ## SyntaxError: invalid syntax The except needs to align with the try. try: #code here except: HTH -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Aug 20 10:10:59 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 20 Aug 2010 09:10:59 +0100 Subject: [Tutor] List comprehension for dicts? References: <3D2D5909-C0E3-4086-86BC-863CF437F6C3@xs4all.nl> <201008201100.10856.steve@pearwood.info> Message-ID: "Steven D'Aprano" wrote > the purpose). No matter how fast you can perform a loop, it's always > faster to avoid it altogether, so this: > > seq = xrange(10000000) > result = [] > for i in seq: > if i >= 10: break > result.append(i%2) > > > will be much faster than this: > > seq = xrange(10000000) > result = [i%2 for i in seq if i < 10] Although it should be pointed out that these are doing very different things. The equivalent loop would use continue rather than break, in which case the LC might be faster. But where you do only want to partially process a list the explicit loop is the best solution for now. I've always wanted an until clause in the LC structure: result = [i%2 for i in seq until i>10] -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Aug 20 10:16:57 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 20 Aug 2010 09:16:57 +0100 Subject: [Tutor] flow problem with a exercise References: Message-ID: "Roelof Wobben" wrote Others have pointed out the lack of indentation. I'll point out some shortcuts you can use... def is_even(argument): remainder= argument%2 if remainder == 0 : return True else : return False You can abbreviate this to just def is_even(arg): return not arg%2 def is_odd(argument): uitkomst=is_even(argument) return uitkomst and this to: def is_odd(arg): return not is_even(arg) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From nitinchandra1 at gmail.com Fri Aug 20 10:27:01 2010 From: nitinchandra1 at gmail.com (nitin chandra) Date: Fri, 20 Aug 2010 13:57:01 +0530 Subject: [Tutor] Multiple file open In-Reply-To: References: Message-ID: Thank you, Alan and Steven. Now i am facing some thing 'different' This is even when i have not done a carriage return to create line "66". This is after i have done fp1.close() fp2.close() fp3.close() ****************************************************** File "mer5Pr2.py", line 66 ^ IndentationError: unexpected unindent ************************************************ Thank you Nitin On Fri, Aug 20, 2010 at 1:28 PM, Alan Gauld wrote: > > "nitin chandra" wrote >> >> FileA = raw_input('Enter CSV file with lists of Files:') >> try: >> ?fp6 = open(FileA,'r') >> ?except IOError: >> >> ## ?I am getting the following error at this line:- >> ## >> ## ? ?File "mer5Pr2.py", line 7 >> ## ? ?except IOError: >> ## ? ? ? ? ? ?^ >> ## ? ?SyntaxError: invalid syntax > > > The except needs to align with the try. > > > ?try: > ? ? #code here > ?except: > > HTH > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From knacktus at googlemail.com Fri Aug 20 10:39:47 2010 From: knacktus at googlemail.com (Knacktus) Date: Fri, 20 Aug 2010 10:39:47 +0200 Subject: [Tutor] Done -- Elementtree and pretty printing in Python 2.7 Message-ID: <4C6E3F53.3030309@googlemail.com> Hi guys, just found "hidden" in the "Schema change in Etree"-Thread the answer to my formatting question: Quotation: " ElementTree doesn't have a way of formatting (pretty printing) XML files, so there can't be that many newline characters in the structure (they may be in the occur, though!). There's a pretty printing recipe on the effbot site that you can easily adapt to inject the newline characters you need. " The recipe works fine. Cheers, Jan From steve at pearwood.info Fri Aug 20 11:44:38 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 20 Aug 2010 19:44:38 +1000 Subject: [Tutor] List comprehension for dicts? In-Reply-To: References: <3D2D5909-C0E3-4086-86BC-863CF437F6C3@xs4all.nl> <201008201100.10856.steve@pearwood.info> Message-ID: <201008201944.38378.steve@pearwood.info> On Fri, 20 Aug 2010 06:10:59 pm Alan Gauld wrote: > "Steven D'Aprano" wrote > > > the purpose). No matter how fast you can perform a loop, it's > > always faster to avoid it altogether, so this: > > > > seq = xrange(10000000) > > result = [] > > for i in seq: > > if i >= 10: break > > result.append(i%2) > > > > > > will be much faster than this: > > > > seq = xrange(10000000) > > result = [i%2 for i in seq if i < 10] > > Although it should be pointed out that these are doing very different > things. Well yes, but I pointed out that you *can* bail out early of for-loops, but not list comprehensions. The whole point is with a list comp, you're forced to iterate over the entire sequence, even if you know that you're done and would like to exit. -- Steven D'Aprano From steve at pearwood.info Fri Aug 20 13:18:29 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 20 Aug 2010 21:18:29 +1000 Subject: [Tutor] Multiple file open In-Reply-To: References: Message-ID: <201008202118.29761.steve@pearwood.info> On Fri, 20 Aug 2010 06:27:01 pm nitin chandra wrote: > Thank you, Alan and Steven. > > Now i am facing some thing 'different' > > This is even when i have not done a carriage return to create line > "66". This is after i have done > fp1.close() > fp2.close() > fp3.close() > ****************************************************** > > File "mer5Pr2.py", line 66 > > ^ > IndentationError: unexpected unindent Without seeing the actual code, it's hard to say. But you need to learn to read the error message: it says you have unexpectedly unindented (outdented). My guess is you've done something like this: if something: line indented with 4 spaces line indented with 2 spaces You need to indent consistently. Set your editor to always use 4 spaces for indents. If you can't do that, then get a better editor, or use a single tab instead of four spaces. Some people will say don't use tabs. I say phooey to them. It's better to use tabs than to have inconsistent indentation. -- Steven D'Aprano From nitinchandra1 at gmail.com Fri Aug 20 17:21:26 2010 From: nitinchandra1 at gmail.com (nitin chandra) Date: Fri, 20 Aug 2010 20:51:26 +0530 Subject: [Tutor] Multiple file open In-Reply-To: <201008202118.29761.steve@pearwood.info> References: <201008202118.29761.steve@pearwood.info> Message-ID: import sys,os, fileinput FileA = raw_input('Enter CSV file with lists of Files:') try: fp6 = open(FileA,'r') except IOError: sys.exit('Could not open file: %s' % FileA) while True: lines = fp6.readline().split(",") file11 = lines[0] file12 = lines[1] file3 = lines[2] #file11 = raw_input('Enter PR1 File name :') #fp1 = open(file11,'r') try: fp1 = open(file11, 'r') except IOError: sys.exit('Could not open file: %s' % file11) #file12 = raw_input('Enter PR3 File Name :') #fp2 = open(file12,'r') try: fp2 = open(file12, 'r') except IOError: sys.exit('Could not open file: %s' % file12) #file3 = raw_input('Enter PR2 OUTPUT File Name :') try: fp3 = open(file3, 'w') except IOError: sys.exit('Could not open file %s to Write' % file3) while True: try: line1 = fp1.readline().split(",") line2 = fp2.readline().split(",") #line1 = line1A.split(",") col1 = line1[0] col2 = line1[1] col3 = line1[2] col4 = line1[3] col5 = line1[20] col6 = line1[21] col7 = line1[22] #line2 = line1B.split(",") col8 = line2[1] col9 = line2[2] col10 = line2[3] col11 = line2[20] col12 = line2[21] col13 = line2[22] #def __FormulaPR2(): #claculation of PR2 as per formula #(A+B)/2 , ie. Mean of the two values col14 = (((float(col2)) + (float(col8))) / 2) col15 = (((float(col3)) + (float(col9))) / 2) col16 = (((float(col4)) + (float(col10))) / 2) col17 = (((float(col5)) + (float(col11))) / 2) col18 = (((float(col6)) + (float(col12))) / 2) col19 = (((float(col7)) + (float(col13))) / 2) print col1,col14,col15,col16,col17,col18,col19 str3 = '%s,%s,%s,%s,%s,%s,%s\n' % (col1,col14,col15,col16,col17,col18,col19) fp3.write(str3) On Fri, Aug 20, 2010 at 4:48 PM, Steven D'Aprano wrote: > On Fri, 20 Aug 2010 06:27:01 pm nitin chandra wrote: >> Thank you, Alan and Steven. >> >> Now i am facing some thing 'different' >> >> This is even when i have not done a carriage return to create line >> "66". This is after i have done >> fp1.close() >> fp2.close() >> fp3.close() >> ****************************************************** >> >> ? File "mer5Pr2.py", line 66 >> >> ? ? ? ? ? ? ? ? ? ? ? ? ? ^ >> IndentationError: unexpected unindent > > > Without seeing the actual code, it's hard to say. But you need to learn > to read the error message: it says you have unexpectedly unindented > (outdented). My guess is you've done something like this: > > if something: > ? ?line indented with 4 spaces > ?line indented with 2 spaces > > > You need to indent consistently. Set your editor to always use 4 spaces > for indents. If you can't do that, then get a better editor, or use a > single tab instead of four spaces. > > Some people will say don't use tabs. I say phooey to them. It's better > to use tabs than to have inconsistent indentation. > > > > -- > Steven D'Aprano > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From matt.gregory at oregonstate.edu Fri Aug 20 17:45:18 2010 From: matt.gregory at oregonstate.edu (Gregory, Matthew) Date: Fri, 20 Aug 2010 08:45:18 -0700 Subject: [Tutor] design of Point class Message-ID: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu> Hi all, I often struggle with object design and inheritance. I'd like opinions on how best to design a Point class to be used in multiple circumstances. I typically deal with geographic (either 2D or 3D) data, yet there are occasions when I need n-dimensional points as well. My thought was to create a superclass which was an n-dimensional point and then subclass that to 2- and 3-dimensional cases. The rub to this is that in the n-dimensional case, it probably makes most sense to store the actual coordinates as a list whereas with the 2- and 3-D cases, I would want 'named' variables, such as x, y, z. Here's a (very rough) first cut at the constructor and a generic distance function for the n-dimensional case: class PointND(object): def __init__(self, a_list): self.a_list = a_list[:] def distance(self, right): assert(len(self.coord) == len(right)) squared_diffs = [(i-j)*(i-j) for (i,j) in zip(self.coord, right)] return math.sqrt(sum(squared_diffs)) But how can I subclass this in such a way to be able to: 1) Have named variables in the 2- and 3-D cases 2) Be able to initialize with separate passed values, e.g. 'p = Point2D(3.0, 5.0)' rather than passing in a list Or am I totally off on thinking this is a good place for inheritance? Thanks for any help, matt From bgailer at gmail.com Fri Aug 20 17:47:12 2010 From: bgailer at gmail.com (bob gailer) Date: Fri, 20 Aug 2010 11:47:12 -0400 Subject: [Tutor] List comprehension for dicts? In-Reply-To: <201008201944.38378.steve@pearwood.info> References: <3D2D5909-C0E3-4086-86BC-863CF437F6C3@xs4all.nl> <201008201100.10856.steve@pearwood.info> <201008201944.38378.steve@pearwood.info> Message-ID: <4C6EA380.7050406@gmail.com> On 8/20/2010 5:44 AM, Steven D'Aprano wrote: > On Fri, 20 Aug 2010 06:10:59 pm Alan Gauld wrote: >> "Steven D'Aprano" wrote >> >>> the purpose). No matter how fast you can perform a loop, it's >>> always faster to avoid it altogether, so this: >>> >>> seq = xrange(10000000) >>> result = [] >>> for i in seq: >>> if i>= 10: break >>> result.append(i%2) >>> >>> >>> will be much faster than this: >>> >>> seq = xrange(10000000) >>> result = [i%2 for i in seq if i< 10] >> Although it should be pointed out that these are doing very different >> things. > Well yes, but I pointed out that you *can* bail out early of for-loops, > but not list comprehensions. The whole point is with a list comp, > you're forced to iterate over the entire sequence, even if you know > that you're done and would like to exit. > Take a look at itertools.takewhile! result = [i%2 for i in itertools.takewhile(lamda x:i< 10, seq)] -- Bob Gailer 919-636-4239 Chapel Hill NC From mehgcap at gmail.com Fri Aug 20 17:54:19 2010 From: mehgcap at gmail.com (Alex Hall) Date: Fri, 20 Aug 2010 11:54:19 -0400 Subject: [Tutor] design of Point class In-Reply-To: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu> References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu> Message-ID: On 8/20/10, Gregory, Matthew wrote: > Hi all, > > I often struggle with object design and inheritance. I'd like opinions on > how best to design a Point class to be used in multiple circumstances. > > I typically deal with geographic (either 2D or 3D) data, yet there are > occasions when I need n-dimensional points as well. My thought was to > create a superclass which was an n-dimensional point and then subclass that > to 2- and 3-dimensional cases. The rub to this is that in the n-dimensional > case, it probably makes most sense to store the actual coordinates as a list > whereas with the 2- and 3-D cases, I would want 'named' variables, such as > x, y, z. > > Here's a (very rough) first cut at the constructor and a generic distance > function for the n-dimensional case: > > class PointND(object): > def __init__(self, a_list): > self.a_list = a_list[:] > > def distance(self, right): > assert(len(self.coord) == len(right)) > squared_diffs = [(i-j)*(i-j) for (i,j) in zip(self.coord, right)] > return math.sqrt(sum(squared_diffs)) > > But how can I subclass this in such a way to be able to: > > 1) Have named variables in the 2- and 3-D cases I assume you will have separate subclasses for both 2d and 3d, so just set up each subclass's __init__ to accept the proper amount and order of arguments. > 2) Be able to initialize with separate passed values, e.g. 'p = Point2D(3.0, > 5.0)' > rather than passing in a list class 2dPoint(point): def __init__(self, x, y): self.x=x self.y=y self.points=[x,y] > > Or am I totally off on thinking this is a good place for inheritance? I would use subclassing. Designed right, this gives you access to common functions like distance but also lets you customize each subclass with specific methods unique to that subclass. Just my 2 cents, though, and I am not too experienced here. > > Thanks for any help, > matt > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Have a great day, Alex (msg sent from GMail website) mehgcap at gmail.com; http://www.facebook.com/mehgcap From bgailer at gmail.com Fri Aug 20 18:08:44 2010 From: bgailer at gmail.com (bob gailer) Date: Fri, 20 Aug 2010 12:08:44 -0400 Subject: [Tutor] design of Point class In-Reply-To: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu> References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu> Message-ID: <4C6EA88C.9020006@gmail.com> On 8/20/2010 11:45 AM, Gregory, Matthew wrote: > Hi all, > > I often struggle with object design and inheritance. I'd like opinions on how best to design a Point class to be used in multiple circumstances. > > I typically deal with geographic (either 2D or 3D) data, yet there are occasions when I need n-dimensional points as well. My thought was to create a superclass which was an n-dimensional point and then subclass that to 2- and 3-dimensional cases. The rub to this is that in the n-dimensional case, it probably makes most sense to store the actual coordinates as a list whereas with the 2- and 3-D cases, I would want 'named' variables, such as x, y, z. > > Here's a (very rough) first cut at the constructor and a generic distance function for the n-dimensional case: > > class PointND(object): > def __init__(self, a_list): > self.a_list = a_list[:] > > def distance(self, right): > assert(len(self.coord) == len(right)) > squared_diffs = [(i-j)*(i-j) for (i,j) in zip(self.coord, right)] > return math.sqrt(sum(squared_diffs)) > > But how can I subclass this in such a way to be able to: > > 1) Have named variables in the 2- and 3-D cases > 2) Be able to initialize with separate passed values, e.g. 'p = Point2D(3.0, 5.0)' rather than passing in a list One class fits all: class PointND(list): def __init__(self, *a_list): super(PointND, self).__init__(a_list) if len(self)<= 2: self.x = self[0] if len(self) == 2: self.y = self[1] -- Bob Gailer 919-636-4239 Chapel Hill NC From waynejwerner at gmail.com Fri Aug 20 18:14:38 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 20 Aug 2010 11:14:38 -0500 Subject: [Tutor] design of Point class In-Reply-To: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu> References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu> Message-ID: On Fri, Aug 20, 2010 at 10:45 AM, Gregory, Matthew < matt.gregory at oregonstate.edu> wrote: > Hi all, > > I often struggle with object design and inheritance. I'd like opinions on > how best to design a Point class to be used in multiple circumstances. > > I typically deal with geographic (either 2D or 3D) data, yet there are > occasions when I need n-dimensional points as well. My thought was to > create a superclass which was an n-dimensional point and then subclass that > to 2- and 3-dimensional cases. The rub to this is that in the n-dimensional > case, it probably makes most sense to store the actual coordinates as a list > whereas with the 2- and 3-D cases, I would want 'named' variables, such as > x, y, z. > > Here's a (very rough) first cut at the constructor and a generic distance > function for the n-dimensional case: > > class PointND(object): > def __init__(self, a_list): > self.a_list = a_list[:] > > def distance(self, right): > assert(len(self.coord) == len(right)) > squared_diffs = [(i-j)*(i-j) for (i,j) in zip(self.coord, right)] > return math.sqrt(sum(squared_diffs)) > > But how can I subclass this in such a way to be able to: > > 1) Have named variables in the 2- and 3-D cases > 2) Be able to initialize with separate passed values, e.g. 'p = > Point2D(3.0, 5.0)' > rather than passing in a list > class Point2D(PointND): def __init__(self, x = 0, y = 0): super(Point2D, self).__init__([x,y]) self.x = 0 self.y = 0 though you wouldn't be able to directly modify the values, or you'll lose the distance function. You'd have to create setter functions, and as such should rename x and y to _x and _y, to indicate that sure you *can* touch these, but really you shouldn't. For the 3d, you'd just add a z param, although to really generalize your ND class you could do this instead: class PointND(object): def __init__(self, x=0, y=0, z=0, a_list=None): if a_list is not None: self.a_list = a_list[:] self.x = x self.y = y self.z = z def coords(self): return [self.x, self.y, self.z] + self.a_list ... Then your subclass takes less effort: class Point2D(PointND): def __init__(self, x=0, y=0): super(Point2D, self).__init__(x,y) and this allows you to access point.x, point.y, and point.z directly. Of course you could also subclass list with ND and just use descriptors for self[0], self[1], and self[2]: http://users.rcn.com/python/download/Descriptor.htm HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From nitin.162 at gmail.com Fri Aug 20 18:40:48 2010 From: nitin.162 at gmail.com (Nitin Das) Date: Fri, 20 Aug 2010 22:10:48 +0530 Subject: [Tutor] List comprehension for dicts? In-Reply-To: <4C6EA380.7050406@gmail.com> References: <3D2D5909-C0E3-4086-86BC-863CF437F6C3@xs4all.nl> <201008201100.10856.steve@pearwood.info> <201008201944.38378.steve@pearwood.info> <4C6EA380.7050406@gmail.com> Message-ID: result = [i%2 for i in itertools.takewhile(lamda x:i< 10, seq)] is a good approach but it is taking little more time than the for loop over iterator. def takewhile(predicate, iterable): # takewhile(lambda x: x<5, [1,4,6,4,1]) --> 1 4 for x in iterable: if predicate(x): yield x else: break I don't know why? As it seems that this for loop and the other for loop doing the same thing. --nitin On Fri, Aug 20, 2010 at 9:17 PM, bob gailer wrote: > On 8/20/2010 5:44 AM, Steven D'Aprano wrote: > >> On Fri, 20 Aug 2010 06:10:59 pm Alan Gauld wrote: >> >>> "Steven D'Aprano" wrote >>> >>> the purpose). No matter how fast you can perform a loop, it's >>>> always faster to avoid it altogether, so this: >>>> >>>> seq = xrange(10000000) >>>> result = [] >>>> for i in seq: >>>> if i>= 10: break >>>> result.append(i%2) >>>> >>>> >>>> will be much faster than this: >>>> >>>> seq = xrange(10000000) >>>> result = [i%2 for i in seq if i< 10] >>>> >>> Although it should be pointed out that these are doing very different >>> things. >>> >> Well yes, but I pointed out that you *can* bail out early of for-loops, >> but not list comprehensions. The whole point is with a list comp, >> you're forced to iterate over the entire sequence, even if you know >> that you're done and would like to exit. >> >> Take a look at itertools.takewhile! > > result = [i%2 for i in itertools.takewhile(lamda x:i< 10, seq)] > > > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From matt.gregory at oregonstate.edu Fri Aug 20 19:55:02 2010 From: matt.gregory at oregonstate.edu (Gregory, Matthew) Date: Fri, 20 Aug 2010 10:55:02 -0700 Subject: [Tutor] design of Point class In-Reply-To: References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu> Message-ID: <1D673F86DDA00841A1216F04D1CE70D6426032DE61@EXCH2.nws.oregonstate.edu> Wayne Werner wrote: > class Point2D(PointND): > ?? ?def __init__(self, x = 0, y = 0): > ?? ? ? ?super(Point2D, self).__init__([x,y]) > ?? ? ? ?self.x = 0 > ?? ? ? ?self.y = 0 > > though you wouldn't be able to directly modify the values, or you'll > lose the distance function. You'd have to create setter functions, and as > such should rename x and y to _x and _y, to indicate that sure you *can* touch > these, but really you shouldn't. > > For the 3d, you'd just add a z param, although to really generalize your > ND class you could do this instead: > > class PointND(object): > ? ?def __init__(self, x=0, y=0, z=0, a_list=None): > ?? ? ? if a_list is not None: > ?? ? ? ? ? self.a_list = a_list[:] > ?? ? ? self.x = x > ?? ? ? self.y = y > ?? ? ? self.z = z > ?? > ?? def coords(self): > ?? ? ? return [self.x, self.y, self.z] + self.a_list > ?? ... > > Then your subclass takes less effort: > > class Point2D(PointND): > ?? ?def __init__(self, x=0, y=0): > ?? ? ? ?super(Point2D, self).__init__(x,y) > > and this allows you to access point.x, point.y, and point.z directly. > > Of course you could also subclass list with ND and just use descriptors > for self[0], self[1], and self[2]: > http://users.rcn.com/python/download/Descriptor.htm Thanks all for good suggestions. I'm intrigued by the idea of subclassing list (suggested by both Bob and Wayne) and using x, y and z as descriptors to the elements in the list. Obviously, it's important that the descriptors (x,y,z) stay in sync with the list itself so that: >>> p = PointND(1,2,3) >>> p.x = 10 >>> p [10,2,3] >From what I understood of the link Wayne sent, I should be able to use __set__ to create this relationship between the labels and the list, but I'm totally lost on how to do this. It seems like x,y,z need to be instances of descriptor objects who have values that are associated with the list. In the mean time, I've overridden __setattr__ to enforce this, but it looks a bit crufty. Any further suggestions are most welcome. class PointND(list): def __init__(self, *a_list): super(PointND, self).__init__(a_list) if len(self) <= 3: self.x = self[0] if len(self) >= 2 and len(self) <= 3: self.y = self[1] if len(self) == 3: self.z = self[2] def __setattr__(self, attr, value): if attr in ('x', 'y', 'z'): self.__dict__[attr] = value if attr == 'x': self[0] = value elif attr == 'y': self[1] = value else: self[2] = value From rwobben at hotmail.com Fri Aug 20 21:48:39 2010 From: rwobben at hotmail.com (Roelof Wobben) Date: Fri, 20 Aug 2010 19:48:39 +0000 Subject: [Tutor] flow problem with a exercise Message-ID: Oke, I don''t understand it complety. return not arg%2 Why use not here ? I think that arg%2 is True not makes it false. Another question. How can I round outcome of a calculation. round ( ( t-32)/1.8) does not work because I get a message that there are two arguments. Outcome = (t-32)/1.8 outcome2 = round (outcome) does not work because the argument must be a string or a number Roelof -------------- next part -------------- An HTML attachment was scrubbed... URL: From waynejwerner at gmail.com Fri Aug 20 22:07:56 2010 From: waynejwerner at gmail.com (Wayne Werner) Date: Fri, 20 Aug 2010 15:07:56 -0500 Subject: [Tutor] flow problem with a exercise In-Reply-To: References: Message-ID: On Fri, Aug 20, 2010 at 2:48 PM, Roelof Wobben wrote: > Oke, > > I don''t understand it complety. > > return not arg%2 > > Why use not here ? > > I think that arg%2 is True not makes it false. > What happens when you replace arg with a value? % is modulo division, so it just returns the remainder. 2 % 2 = ? 4 % 2 = ? 7 % 2 = ? 11 % 2 = ? What is the truth value of 0 and 1? print 'True' if 0 else 'False' print 'True' if 1 else 'False' So what is the outcome of the following? result = 2 % 2 print result, not result if not result: print 'Even' if result: print 'odd' > > Another question. > > How can I round outcome of a calculation. > > round ( ( t-32)/1.8) does not work because I get a message that there are > two arguments. > > Outcome = (t-32)/1.8 > outcome2 = round (outcome) does not work because the argument must be a > string or a number > What is the type of t? In [39]: t = 3 In [40]: round((t-32)/1.8) Out[40]: -16.0 In [41]: t = 3.0 In [42]: round((t-32)/1.8) Out[42]: -16.0 Works fine for me. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Fri Aug 20 22:47:31 2010 From: wprins at gmail.com (Walter Prins) Date: Fri, 20 Aug 2010 21:47:31 +0100 Subject: [Tutor] Multiple file open In-Reply-To: References: <201008202118.29761.steve@pearwood.info> Message-ID: <4C6EE9E3.9080800@gmail.com> Hello Nitin, On 20/08/10 16:21, nitin chandra wrote: > import sys,os, fileinput > [...] > while True: > try: > line1 = fp1.readline().split(",") > line2 = fp2.readline().split(",") > [...] > fp3.write(str3) > You're missing the completion for the try/finally block. Try adding an exception handler or comment out the "try" statement for the time being. Walter From hugo.yoshi at gmail.com Fri Aug 20 23:32:12 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 20 Aug 2010 16:32:12 -0500 Subject: [Tutor] design of Point class In-Reply-To: <1D673F86DDA00841A1216F04D1CE70D6426032DE61@EXCH2.nws.oregonstate.edu> References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu> <1D673F86DDA00841A1216F04D1CE70D6426032DE61@EXCH2.nws.oregonstate.edu> Message-ID: On Fri, Aug 20, 2010 at 12:55 PM, Gregory, Matthew wrote: > Wayne Werner wrote: >> class Point2D(PointND): >> ?? ?def __init__(self, x = 0, y = 0): >> ?? ? ? ?super(Point2D, self).__init__([x,y]) >> ?? ? ? ?self.x = 0 >> ?? ? ? ?self.y = 0 >> >> though you wouldn't be able to directly modify the values, or you'll >> lose the distance function. You'd have to create setter functions, and as >> such should rename x and y to _x and _y, to indicate that sure you *can* touch >> these, but really you shouldn't. >> >> For the 3d, you'd just add a z param, although to really generalize your >> ND class you could do this instead: >> >> class PointND(object): >> ? ?def __init__(self, x=0, y=0, z=0, a_list=None): >> ?? ? ? if a_list is not None: >> ?? ? ? ? ? self.a_list = a_list[:] >> ?? ? ? self.x = x >> ?? ? ? self.y = y >> ?? ? ? self.z = z >> >> ?? def coords(self): >> ?? ? ? return [self.x, self.y, self.z] + self.a_list >> ?? ... >> >> Then your subclass takes less effort: >> >> class Point2D(PointND): >> ?? ?def __init__(self, x=0, y=0): >> ?? ? ? ?super(Point2D, self).__init__(x,y) >> >> and this allows you to access point.x, point.y, and point.z directly. >> >> Of course you could also subclass list with ND and just use descriptors >> for self[0], self[1], and self[2]: >> http://users.rcn.com/python/download/Descriptor.htm > > Thanks all for good suggestions. ?I'm intrigued by the idea of subclassing list (suggested by both Bob and Wayne) and using x, y and z as descriptors to the elements in the list. ?Obviously, it's important that the descriptors (x,y,z) stay in sync with the list itself so that: > > ?>>> p = PointND(1,2,3) > ?>>> p.x = 10 > ?>>> p > ?[10,2,3] > > >From what I understood of the link Wayne sent, I should be able to use __set__ to create this relationship between the labels and the list, but I'm totally lost on how to do this. ?It seems like x,y,z need to be instances of descriptor objects who have values that are associated with the list. > > In the mean time, I've overridden __setattr__ to enforce this, but it looks a bit crufty. ?Any further suggestions are most welcome. > > class PointND(list): > ? ?def __init__(self, *a_list): > ? ? ? ?super(PointND, self).__init__(a_list) > ? ? ? ?if len(self) <= 3: > ? ? ? ? ? ?self.x = self[0] > ? ? ? ?if len(self) >= 2 and len(self) <= 3: > ? ? ? ? ? ?self.y = self[1] > ? ? ? ?if len(self) == 3: > ? ? ? ? ? ?self.z = self[2] > > ? ?def __setattr__(self, attr, value): > ? ? ? ?if attr in ('x', 'y', 'z'): > ? ? ? ? ? ?self.__dict__[attr] = value > ? ? ? ? ? ?if attr == 'x': > ? ? ? ? ? ? ? ?self[0] = value > ? ? ? ? ? ?elif attr == 'y': > ? ? ? ? ? ? ? ?self[1] = value > ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ?self[2] = value perhaps properties could be of some use? from operator import itemgetter, setitem def named_index(index): getter = itemgetter(index) setter = lambda self, val: setitem(self, index, val) return property(getter, setter) class NPoint(list): x = named_index(0) y = named_index(1) z = named_index(2) p = NPoint([3, 4, 50]) print p.x, p.y, p.z p.x = p.y + 13 print p Note that trying to access z when there are not enough items in the list will raise an IndexError, not an AttributeError. You might want to adjust the getter/setter functions a little. Alternatively, I'm not sure if you can add properties in __init__ or __new__, but if not that, you can probably write a metaclass that adds in the right properties based on list length. Hugo From alan.gauld at btinternet.com Fri Aug 20 23:53:20 2010 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 20 Aug 2010 14:53:20 -0700 (PDT) Subject: [Tutor] flow problem with a exercise In-Reply-To: References: , Message-ID: <919223.54627.qm@web86706.mail.ird.yahoo.com> Please use ReplyAll when responding to posts from the tutor list. > I don''t understand it complety. > return not arg%2 >> >> Why use not here ? >> >> I think that arg%2 is True not makes it false. > >For an even number arg % 2 will be 0 which Python considers to be False. So for a True result when arg%2 is zero, you must negate the logic Another question. > >How can I round outcome of a calculation. > >round ( ( t-32)/1.8) does not work because I get a message that there are two >arguments. > >Check your code because thre is only one arg here. Therefore the actual code giving the error must be different in some way. Outcome = (t-32)/1.8 >outcome2 = round (outcome) does not work because the argument must be a string >or a number > > > Assuming t is a number the outcome will be a number so it should work. It helps if you cut n paste the real code and the real error message, do not just summarise. Python error messages are extremely helpful, but only if we can see them. Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Sat Aug 21 01:13:30 2010 From: emile at fenx.com (Emile van Sebille) Date: Fri, 20 Aug 2010 16:13:30 -0700 Subject: [Tutor] Overloaded Brackets Message-ID: Hi All, I just had reason the write the following: itemCodes = [UPCxref['0'+xx[:10]][0] for xx in itemUPCs] ... and it occurred to me exactly how overloaded square brackets are. This is certainly not something you want to see as a beginning python programmer, but I thought it might be an interesting example to parse. Regards, Emile From bgailer at gmail.com Sat Aug 21 01:57:40 2010 From: bgailer at gmail.com (bob gailer) Date: Fri, 20 Aug 2010 19:57:40 -0400 Subject: [Tutor] design of Point class In-Reply-To: <1D673F86DDA00841A1216F04D1CE70D6426032DE61@EXCH2.nws.oregonstate.edu> References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu> <1D673F86DDA00841A1216F04D1CE70D6426032DE61@EXCH2.nws.oregonstate.edu> Message-ID: <4C6F1674.4030601@gmail.com> On 8/20/2010 1:55 PM, Gregory, Matthew wrote: > Wayne Werner wrote: >> class Point2D(PointND): >> def __init__(self, x = 0, y = 0): >> super(Point2D, self).__init__([x,y]) >> self.x = 0 >> self.y = 0 >> >> though you wouldn't be able to directly modify the values, or you'll >> lose the distance function. You'd have to create setter functions, and as >> such should rename x and y to _x and _y, to indicate that sure you *can* touch >> these, but really you shouldn't. >> >> For the 3d, you'd just add a z param, although to really generalize your >> ND class you could do this instead: >> >> class PointND(object): >> def __init__(self, x=0, y=0, z=0, a_list=None): >> if a_list is not None: >> self.a_list = a_list[:] >> self.x = x >> self.y = y >> self.z = z >> >> def coords(self): >> return [self.x, self.y, self.z] + self.a_list >> ... >> >> Then your subclass takes less effort: >> >> class Point2D(PointND): >> def __init__(self, x=0, y=0): >> super(Point2D, self).__init__(x,y) >> >> and this allows you to access point.x, point.y, and point.z directly. >> >> Of course you could also subclass list with ND and just use descriptors >> for self[0], self[1], and self[2]: >> http://users.rcn.com/python/download/Descriptor.htm > Thanks all for good suggestions. I'm intrigued by the idea of subclassing list (suggested by both Bob and Wayne) and using x, y and z as descriptors to the elements in the list. Obviously, it's important that the descriptors (x,y,z) stay in sync with the list itself so that: > > >>> p = PointND(1,2,3) > >>> p.x = 10 > >>> p > [10,2,3] > > > From what I understood of the link Wayne sent, I should be able to use __set__ to create this relationship between the labels and the list, but I'm totally lost on how to do this. It seems like x,y,z need to be instances of descriptor objects who have values that are associated with the list. > > In the mean time, I've overridden __setattr__ to enforce this, but it looks a bit crufty. Any further suggestions are most welcome. > > class PointND(list): > def __init__(self, *a_list): > super(PointND, self).__init__(a_list) > if len(self)<= 3: > self.x = self[0] > if len(self)>= 2 and len(self)<= 3: > self.y = self[1] > if len(self) == 3: > self.z = self[2] > > def __setattr__(self, attr, value): > if attr in ('x', 'y', 'z'): > self.__dict__[attr] = value > if attr == 'x': > self[0] = value > elif attr == 'y': > self[1] = value > else: > self[2] = value class PointND(list): def __init__(self, *a_list): super(PointND, self).__init__(a_list) def get(self, ix): if len(self)>= ix + 1: return self[ix] else: raise AttributeError def set(self, ix, value): if len(self)>= ix + 1: self[ix] = value else: raise AttributeError def getx(self): return self.get(0) def setx(self, value): self.set(0, value) x = property(getx, setx) def gety(self): return self.get(1) def sety(self, value): self.set(1, value) y = property(gety, sety) # repeat for z -- Bob Gailer 919-636-4239 Chapel Hill NC From bgailer at gmail.com Sat Aug 21 02:35:01 2010 From: bgailer at gmail.com (bob gailer) Date: Fri, 20 Aug 2010 20:35:01 -0400 Subject: [Tutor] design of Point class In-Reply-To: <1D673F86DDA00841A1216F04D1CE70D6426032DE61@EXCH2.nws.oregonstate.edu> References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu> <1D673F86DDA00841A1216F04D1CE70D6426032DE61@EXCH2.nws.oregonstate.edu> Message-ID: <4C6F1F35.8040007@gmail.com> On 8/20/2010 1:55 PM, Gregory, Matthew wrote: > Wayne Werner wrote: >> class Point2D(PointND): >> def __init__(self, x = 0, y = 0): >> super(Point2D, self).__init__([x,y]) >> self.x = 0 >> self.y = 0 >> >> though you wouldn't be able to directly modify the values, or you'll >> lose the distance function. You'd have to create setter functions, and as >> such should rename x and y to _x and _y, to indicate that sure you *can* touch >> these, but really you shouldn't. >> >> For the 3d, you'd just add a z param, although to really generalize your >> ND class you could do this instead: >> >> class PointND(object): >> def __init__(self, x=0, y=0, z=0, a_list=None): >> if a_list is not None: >> self.a_list = a_list[:] >> self.x = x >> self.y = y >> self.z = z >> >> def coords(self): >> return [self.x, self.y, self.z] + self.a_list >> ... >> >> Then your subclass takes less effort: >> >> class Point2D(PointND): >> def __init__(self, x=0, y=0): >> super(Point2D, self).__init__(x,y) >> >> and this allows you to access point.x, point.y, and point.z directly. >> >> Of course you could also subclass list with ND and just use descriptors >> for self[0], self[1], and self[2]: >> http://users.rcn.com/python/download/Descriptor.htm > Thanks all for good suggestions. I'm intrigued by the idea of subclassing list (suggested by both Bob and Wayne) and using x, y and z as descriptors to the elements in the list. Obviously, it's important that the descriptors (x,y,z) stay in sync with the list itself so that: > > >>> p = PointND(1,2,3) > >>> p.x = 10 > >>> p > [10,2,3] > > > From what I understood of the link Wayne sent, I should be able to use __set__ to create this relationship between the labels and the list, but I'm totally lost on how to do this. It seems like x,y,z need to be instances of descriptor objects who have values that are associated with the list. > > In the mean time, I've overridden __setattr__ to enforce this, but it looks a bit crufty. Any further suggestions are most welcome. > > class PointND(list): > def __init__(self, *a_list): > super(PointND, self).__init__(a_list) > if len(self)<= 3: > self.x = self[0] > if len(self)>= 2 and len(self)<= 3: > self.y = self[1] > if len(self) == 3: > self.z = self[2] > > def __setattr__(self, attr, value): > if attr in ('x', 'y', 'z'): > self.__dict__[attr] = value > if attr == 'x': > self[0] = value > elif attr == 'y': > self[1] = value > else: > self[2] = value After more thought it gets even better: class PointND(list): def __init__(self, *a_list): super(PointND, self).__init__(a_list) def get(ix): def g(self): if len(self) >= ix + 1: return self[ix] else: raise AttributeError return g def set(ix): def s(self, value): if len(self) >= ix + 1: self[ix] = value else: raise AttributeError return s x = property(get(0), set(0)) y = property(get(1), set(1)) z = property(get(2), set(2)) -- Bob Gailer 919-636-4239 Chapel Hill NC From alan.gauld at btinternet.com Sat Aug 21 00:08:56 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 20 Aug 2010 23:08:56 +0100 Subject: [Tutor] design of Point class References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu> Message-ID: "Gregory, Matthew" wrote > I typically deal with geographic (either 2D or 3D) data, yet > there are occasions when I need n-dimensional points as well. Thats OK. > The rub to this is that in the n-dimensional case, it probably > makes most sense to store the actual coordinates as a list > whereas with the 2- and 3-D cases, I would want 'named' > variables, such as x, y, z. Thats OK too but adds some overhead. Remember that inheritance should be based on behaviour not data so determine the common methods of a Point. Write the ND version of those methods. Then create subclasses for 2D and 3D which convert the named args to a list equivalent then call the superclass ND versions. Every time you change the interface of inherited methods you create for yourself extra work in converting types to match the superclass. But that is often easier than rewriting the methods from scratch. Just remember that to get the best out of polymorphism - the primary reason for inheritance - you should be able to mix n match instances of the subclasses with instances of the superclass - the Liskov Substitution Principle(LSP) - and if you break that you lose for yourself much of the power of inheritance. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ > > Here's a (very rough) first cut at the constructor and a generic > distance function for the n-dimensional case: > > class PointND(object): > def __init__(self, a_list): > self.a_list = a_list[:] > > def distance(self, right): > assert(len(self.coord) == len(right)) > squared_diffs = [(i-j)*(i-j) for (i,j) in zip(self.coord, > right)] > return math.sqrt(sum(squared_diffs)) > > But how can I subclass this in such a way to be able to: > > 1) Have named variables in the 2- and 3-D cases > 2) Be able to initialize with separate passed values, e.g. 'p = > Point2D(3.0, 5.0)' > rather than passing in a list > > Or am I totally off on thinking this is a good place for > inheritance? > > Thanks for any help, > matt > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From steve at pearwood.info Sat Aug 21 03:24:28 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 21 Aug 2010 11:24:28 +1000 Subject: [Tutor] design of Point class In-Reply-To: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu> References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu> Message-ID: <201008211124.29475.steve@pearwood.info> On Sat, 21 Aug 2010 01:45:18 am Gregory, Matthew wrote: > Hi all, > > I often struggle with object design and inheritance. I'd like > opinions on how best to design a Point class to be used in multiple > circumstances. > > I typically deal with geographic (either 2D or 3D) data, yet there > are occasions when I need n-dimensional points as well. My thought > was to create a superclass which was an n-dimensional point and then > subclass that to 2- and 3-dimensional cases. The rub to this is that > in the n-dimensional case, it probably makes most sense to store the > actual coordinates as a list whereas with the 2- and 3-D cases, I > would want 'named' variables, such as x, y, z. It would surprise me greatly if numpy didn't already have such a class. Other than using numpy, probably the simplest solution is to just subclass tuple and give it named properties and whatever other methods you want. Here's a simple version: class Point(tuple): def __new__(cls, *args): if len(args) == 1 and isinstance(args, tuple): args = args[0] for a in args: try: a+0 except TypeError: raise TypeError('ordinate %s is not a number' % a) return super(Point, cls).__new__(cls, args) @property def x(self): return self[0] @property def y(self): return self[1] @property def z(self): return self[2] def dist(self, other): if isinstance(other, Point): if len(self) == len(other): sq_diffs = sum((a-b)**2 for (a,b) in zip(self, other)) return math.sqrt(sq_diffs) else: raise ValueError('incompatible dimensions') raise TypeError('not a Point') def __repr__(self): return "%s(%r)" % (self.__class__.__name__, tuple(self)) class Point2D(Point): def __init__(self, *args): if len(self) != 2: raise ValueError('need exactly two ordinates') class Point3D(Point): def __init__(self, *args): if len(self) != 3: raise ValueError('need exactly three ordinates') These classes gives you: * immutability; * the first three ordinates are named x, y and z; * any ordinate can be accessed by index with pt[3]; * distance is only defined if the dimensions are the same; * nice string form; * input validation. What it doesn't give you (yet!) is: * distance between Points with different dimensions could easily be defined just by removing the len() comparison. zip() will automatically terminate at the shortest input, thus projecting the higher-dimension point down to the lower-dimension point; * other distance methods, such as Manhattan distance; * a nice exception when you as for (say) pt.z from a 2-D point, instead of raising IndexError; * point arithmetic (say, adding two points to get a third). But you can't expect me to do all your work :) An alternative would be to have the named ordinates return 0 rather than raise an error. Something like this would work: @property def y(self): try: return self[1] except IndexError: return 0 -- Steven D'Aprano From steve at pearwood.info Sat Aug 21 03:50:40 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 21 Aug 2010 11:50:40 +1000 Subject: [Tutor] design of Point class In-Reply-To: References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu> Message-ID: <201008211150.41362.steve@pearwood.info> On Sat, 21 Aug 2010 08:08:56 am Alan Gauld wrote: > Every time you change the interface of inherited methods you > create for yourself extra work in converting types to match the > superclass. But that is often easier than rewriting the methods > from scratch. Every time you change the interface of inherited methods, you probably shouldn't. Firstly, it probably breaks the Liskov Substitution Principle. The LSP says, essentially, if you subclass A to make B, you should be able to use a B anywhere you can use an A. (After all, instances of B are also instances of A.) Here's an example of what not to do: class Vehicle: def start(self, key): ignition.insert(key) ignition.turn() # raises exception if out of fuel def go(self, key): self.start(key) self.handbrake = 'off' self.gear = 'drive' self.accelerate() class Truck(Vehicle): # add other truck-like methods class KeylessTruck(Truck): # Some military vehicles are designed to not require keys. # When on a battlefield, there's nothing worse than being # unable to find the car keys! def go(self): self.start() self.handbrake = 'off' self.gear = 'drive' self.accelerate() def start(self): ignition.turn() # Actually a push button, but nevermind. Can you see the problem? If the caller is expecting a Truck, and pass a key to the truck.go() method, they will get an exception if you give them a KeylessTruck instead of a Truck. This is a Bad Thing. Secondly, changing method interfaces is not compatible with multiple inheritance and super(). You can probably get away with it if you stick to single inheritance, but it's still a bad thing to do. -- Steven D'Aprano From steve at pearwood.info Sat Aug 21 03:51:24 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 21 Aug 2010 11:51:24 +1000 Subject: [Tutor] List comprehension for dicts? In-Reply-To: <4C6EA380.7050406@gmail.com> References: <3D2D5909-C0E3-4086-86BC-863CF437F6C3@xs4all.nl> <201008201944.38378.steve@pearwood.info> <4C6EA380.7050406@gmail.com> Message-ID: <201008211151.25253.steve@pearwood.info> On Sat, 21 Aug 2010 01:47:12 am bob gailer wrote: > > Well yes, but I pointed out that you *can* bail out early of > > for-loops, but not list comprehensions. The whole point is with a > > list comp, you're forced to iterate over the entire sequence, even > > if you know that you're done and would like to exit. > > Take a look at itertools.takewhile! > > result = [i%2 for i in itertools.takewhile(lamda x:i< 10, seq)] Which is an excellent solution to the problem, and I had forgotten about it, but takewhile doesn't magically cause the list comprehension to exit. The list comp still runs over the entire input list, it's just that it sees a smaller input list. takewhile replaces the input sequence with a new sequence that stops at a certain point, so you could write: result = [] for i in itertools.takewhile(lambda x:i<10, seq): result.append(i) as well. Next time some Perl hacker accuses Python of being "Only one way to do it", you can just laugh at them :) -- Steven D'Aprano From steve at pearwood.info Sat Aug 21 03:53:22 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 21 Aug 2010 11:53:22 +1000 Subject: [Tutor] design of Point class In-Reply-To: <201008211150.41362.steve@pearwood.info> References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu> <201008211150.41362.steve@pearwood.info> Message-ID: <201008211153.22496.steve@pearwood.info> On Sat, 21 Aug 2010 11:50:40 am Steven D'Aprano wrote: > On Sat, 21 Aug 2010 08:08:56 am Alan Gauld wrote: > > Every time you change the interface of inherited methods you > > create for yourself extra work in converting types to match the > > superclass. But that is often easier than rewriting the methods > > from scratch. > > Every time you change the interface of inherited methods, you > probably shouldn't. Oops, that's a generic "you", not Alan. After all, he went on to mention Liskov in the very next paragraph. -- Steven D'Aprano From nitinchandra1 at gmail.com Sat Aug 21 05:51:04 2010 From: nitinchandra1 at gmail.com (nitin chandra) Date: Sat, 21 Aug 2010 09:21:04 +0530 Subject: [Tutor] Multiple file open In-Reply-To: <4C6EE9E3.9080800@gmail.com> References: <201008202118.29761.steve@pearwood.info> <4C6EE9E3.9080800@gmail.com> Message-ID: Thank You Very Much :) Walter..... It WOrked ....I did the "except" closing. Thanks Nitin On Sat, Aug 21, 2010 at 2:17 AM, Walter Prins wrote: > > Hello Nitin, > > On 20/08/10 16:21, nitin chandra wrote: >> >> import sys,os, fileinput >> > > [...] >> >> while True: >> ? ?try: >> ? ? ? ?line1 = fp1.readline().split(",") >> ? ? ? ?line2 = fp2.readline().split(",") >> > > [...] >> >> ? ? ? ?fp3.write(str3) >> > > You're missing the completion for the try/finally block. ?Try adding an > exception handler or comment out the "try" statement for the time being. > > Walter > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Sat Aug 21 10:20:56 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 21 Aug 2010 09:20:56 +0100 Subject: [Tutor] Windows Power Shell Message-ID: A recent windows update delivered the Windows Power Shell to my desktop. I'd heard of this but never used it till now. I've only started playing with it but it is essentially DOS on steroids. It brings Windows users a shell that seems to be very close to Unix shells like Bash in power and flexibility (and scripting language). It's very early days yet, but I wondered if any other tutor members had started using WPS? Some examples of the extra features include regex, objects, process control, remote invocation, better loop structures etc... Regards, Alan G. From rwobben at hotmail.com Sat Aug 21 11:57:06 2010 From: rwobben at hotmail.com (Roelof Wobben) Date: Sat, 21 Aug 2010 09:57:06 +0000 Subject: [Tutor] flow problem with a exercise In-Reply-To: References: , Message-ID: From: waynejwerner at gmail.com Date: Fri, 20 Aug 2010 15:07:56 -0500 Subject: Re: [Tutor] flow problem with a exercise To: rwobben at hotmail.com CC: tutor at python.org On Fri, Aug 20, 2010 at 2:48 PM, Roelof Wobben wrote: Oke, I don''t understand it complety. return not arg%2 Why use not here ? I think that arg%2 is True not makes it false. What happens when you replace arg with a value? % is modulo division, so it just returns the remainder. 2 % 2 = ? 2%2=0 4 % 2 = ? 4%2=0 7 % 2 = ? 7%2=1 11 % 2 = ? 11%2 =1 What is the truth value of 0 and 1? print 'True' if 0 else 'False' False print 'True' if 1 else 'False' True So what is the outcome of the following? result = 2 % 2 print result, not result if not result: print 'Even' if result: print 'odd' 0 True Even So 1 is True and 0 is False according to Python. Another question. How can I round outcome of a calculation. round ( ( t-32)/1.8) does not work because I get a message that there are two arguments. Outcome = (t-32)/1.8 outcome2 = round (outcome) does not work because the argument must be a string or a number What is the type of t? In [39]: t = 3 In [40]: round((t-32)/1.8) Out[40]: -16.0 In [41]: t = 3.0 In [42]: round((t-32)/1.8) Out[42]: -16.0 Works fine for me. Correct, But I see one wierd thing. round ((42-32)/1.8) gives a output -16.0 but (42-32)/1.8) gives also -16.0 I was expectting that round will give 16 as output because round (32.0) is the same as round (32.0, 0) so there will be 0 decimals. And I see one decimal. Roelof HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Sat Aug 21 12:39:05 2010 From: evert.rol at gmail.com (Evert Rol) Date: Sat, 21 Aug 2010 12:39:05 +0200 Subject: [Tutor] flow problem with a exercise In-Reply-To: References: , Message-ID: > In [39]: t = 3 > > In [40]: round((t-32)/1.8) > Out[40]: -16.0 > > In [41]: t = 3.0 > > In [42]: round((t-32)/1.8) > Out[42]: -16.0 > > Works fine for me. > > Correct, > But I see one wierd thing. > > round ((42-32)/1.8) gives a output -16.0 but (42-32)/1.8) gives also -16.0 > I was expectting that round will give 16 as output because round (32.0) is the same as round (32.0, 0) so there will be 0 decimals. > And I see one decimal. The rounding doesn't influence how it's printed. From help(round): """ round(...) round(number[, ndigits]) -> floating point number Round a number to a given precision in decimal digits (default 0 digits). This always returns a floating point number. Precision may be negative. """ It *rounds* the number to ndigits, not prints. It always returns a floating point number though (not an integer). Since floats are normally represented with at least one trailing digit after the decimal dot, you see a zero. Eg, >>> float(1) 1.0 If you want to get rid of the trailing .0, convert it to an integer: >>> int(round(1.1)) 1 Also consider: >>> round(1.15, 0) 1.0 >>> round(1.15, 1) 1.2 >>> round(1.15, 2) 1.1499999999999999 (Note again how the last rounded 1.15 is represented. It's just a representation though, and showing the imprecision you intrinsicaly get when dealing with floating point numbers.) If you really want different behaviour when printing (or using) floating point numbers, perhaps have a look at the decimal module: http://docs.python.org/library/decimal.html From davea at ieee.org Sat Aug 21 12:42:33 2010 From: davea at ieee.org (Dave Angel) Date: Sat, 21 Aug 2010 06:42:33 -0400 Subject: [Tutor] flow problem with a exercise In-Reply-To: References: , Message-ID: <4C6FAD99.4080700@ieee.org> You need to figure out how to get your email program to do quoting. As it stands, there's no good way to tell what part of the following message was from you, and what part was from wayne, or maybe others. Probably all you need to do is to do a reply-all to the message, and it'll mark the existing text with a ">" symbol. Then make sure everything you type is *not* quoted. Roelof Wobben wrote: > > > > From: waynejwerner at gmail.com > > > result = 2 % 2 > print result, not result > if not result: > print 'Even' > if result: > print 'odd' > > 0 True > Even > > So 1 is True and 0 is False according to Python. > > > No, True is a specific object that differs from all other objects. Likewise False. However, other objects, including especially integers, lists, and strings, can be used in a boolean context, and there are specific rules that decide whether a given object will be used as true (lowercase) or false. For integers values, all nonzero items are considered true, while zero is considered false. > > > > Another question. > > How can I round outcome of a calculation. > > round ( ( t-32)/1.8) does not work because I get a message that there are two arguments. > > Outcome = (t-32)/1.8 > outcome2 = round (outcome) does not work because the argument must be a string or a number > > > What is the type of t? > > > In [39]: t = 3 > > > In [40]: round((t-32)/1.8) > Out[40]: -16.0 > > > In [41]: t = 3.0 > > > In [42]: round((t-32)/1.8) > Out[42]: -16.0 > > > Works fine for me. > > Correct, > But I see one wierd thing. > > round ((42-32)/1.8) gives a output -16.0 but (42-32)/1.8) gives also -16.0 > I was expectting that round will give 16 as output because round (32.0) is the same as round (32.0, 0) so there will be 0 decimals. > And I see one decimal. > > Roelof > > > > HTH, > Wayne You're confusing the operation of round() with the operation of converting to a string for printing. Round changes a floating point (binary) value to have a certain quantization, which approximates what you might want to print. It does not, however, affect the way print will subsequently deal with that floating point number. It's no different than when you use a numeric literal with varying amounts of apparent precision. x = 4.2 x = 4.20 x = 4.2000000000 all produce precisely the same floating point object. DaveA From rwobben at hotmail.com Sat Aug 21 12:43:28 2010 From: rwobben at hotmail.com (Roelof Wobben) Date: Sat, 21 Aug 2010 10:43:28 +0000 Subject: [Tutor] flow problem with a exercise In-Reply-To: References: , , Message-ID: > Subject: Re: [Tutor] flow problem with a exercise > From: evert.rol at gmail.com > Date: Sat, 21 Aug 2010 12:39:05 +0200 > CC: tutor at python.org > To: rwobben at hotmail.com > > > In [39]: t = 3 > > > > In [40]: round((t-32)/1.8) > > Out[40]: -16.0 > > > > In [41]: t = 3.0 > > > > In [42]: round((t-32)/1.8) > > Out[42]: -16.0 > > > > Works fine for me. > > > > Correct, > > But I see one wierd thing. > > > > round ((42-32)/1.8) gives a output -16.0 but (42-32)/1.8) gives also -16.0 > > I was expectting that round will give 16 as output because round (32.0) is the same as round (32.0, 0) so there will be 0 decimals. > > And I see one decimal. > > The rounding doesn't influence how it's printed. > From help(round): > > """ > round(...) > round(number[, ndigits]) -> floating point number > > Round a number to a given precision in decimal digits (default 0 digits). > This always returns a floating point number. Precision may be negative. > """ > > It *rounds* the number to ndigits, not prints. It always returns a floating point number though (not an integer). > Since floats are normally represented with at least one trailing digit after the decimal dot, you see a zero. > Eg, > >>> float(1) > 1.0 > > If you want to get rid of the trailing .0, convert it to an integer: > >>> int(round(1.1)) > 1 > > Also consider: > >>> round(1.15, 0) > 1.0 > >>> round(1.15, 1) > 1.2 > >>> round(1.15, 2) > 1.1499999999999999 > > > (Note again how the last rounded 1.15 is represented. It's just a representation though, and showing the imprecision you intrinsicaly get when dealing with floating point numbers.) > > If you really want different behaviour when printing (or using) floating point numbers, perhaps have a look at the decimal module: http://docs.python.org/library/decimal.html > > Oke, Thank you. Learned another thing about Python. Roelof -------------- next part -------------- An HTML attachment was scrubbed... URL: From coolankur2006 at gmail.com Sat Aug 21 15:07:52 2010 From: coolankur2006 at gmail.com (ANKUR AGGARWAL) Date: Sat, 21 Aug 2010 18:37:52 +0530 Subject: [Tutor] check the terminal keyword Message-ID: i m making a app in which i launch application using os.system("input from user"). I want to check whether the input entered by the user matches with the exact keyword in terminal or not. like i want to launch vlc so user should provide me input as " vlc" in order to launch the app just like he did from terminal. I want to make a check on the input spell so that if he type "wlc" it shows an error to it. I have an little idea abt sys.agrv but don't know how to use it... Plz help me guys. Thanks in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: From rwobben at hotmail.com Sat Aug 21 15:35:38 2010 From: rwobben at hotmail.com (Roelof Wobben) Date: Sat, 21 Aug 2010 13:35:38 +0000 Subject: [Tutor] prime test problem Message-ID: Hello, I have to make a programm which can test if a number is a prime. I know a prime is a number which can only be diveded by 1 and itself. One way is was thinking about is to make a loop which try if % has output 0. But that don't work. Can someone give me a hint what's the best approach is. Roelof -------------- next part -------------- An HTML attachment was scrubbed... URL: From nitin.162 at gmail.com Sat Aug 21 15:45:03 2010 From: nitin.162 at gmail.com (Nitin Das) Date: Sat, 21 Aug 2010 19:15:03 +0530 Subject: [Tutor] prime test problem In-Reply-To: References: Message-ID: For this problem u will get lots of solutions on the net. e.g wilson's theorem , sieve of eranthoses etc. --nitin On Sat, Aug 21, 2010 at 7:05 PM, Roelof Wobben wrote: > Hello, > > I have to make a programm which can test if a number is a prime. > I know a prime is a number which can only be diveded by 1 and itself. > > One way is was thinking about is to make a loop which try if % has output > 0. > But that don't work. > > Can someone give me a hint what's the best approach is. > > Roelof > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bermanrl at cfl.rr.com Sat Aug 21 15:44:56 2010 From: bermanrl at cfl.rr.com (Robert Berman) Date: Sat, 21 Aug 2010 09:44:56 -0400 Subject: [Tutor] prime test problem In-Reply-To: References: Message-ID: <002701cb4137$0aba2850$202e78f0$@rr.com> Googling 'computing prime numbers' produced about 64,100,000 results . That should certainly get you started. Robert From: tutor-bounces+bermanrl=cfl.rr.com at python.org [mailto:tutor-bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Roelof Wobben Sent: Saturday, August 21, 2010 9:36 AM To: tutor at python.org Subject: [Tutor] prime test problem Hello, I have to make a programm which can test if a number is a prime. I know a prime is a number which can only be diveded by 1 and itself. One way is was thinking about is to make a loop which try if % has output 0. But that don't work. Can someone give me a hint what's the best approach is. Roelof -------------- next part -------------- An HTML attachment was scrubbed... URL: From nitin.162 at gmail.com Sat Aug 21 15:48:01 2010 From: nitin.162 at gmail.com (Nitin Das) Date: Sat, 21 Aug 2010 19:18:01 +0530 Subject: [Tutor] check the terminal keyword In-Reply-To: References: Message-ID: You can use raw_input like for e.g. u_input = raw_input("user_command") n then u can check u_input against anything. if doesn't matches then u can throw an error. I hope it shall help you. --nitin On Sat, Aug 21, 2010 at 6:37 PM, ANKUR AGGARWAL wrote: > i m making a app in which i launch application using os.system("input from > user"). I want to check whether the input entered by the user matches with > the exact keyword in terminal or not. > like i want to launch vlc so user should provide me input as " vlc" in > order to launch the app just like he did from terminal. I want to make a > check on the input spell so that if he type "wlc" it shows an error to it. I > have an little idea abt sys.agrv but don't know how to use it... Plz help me > guys. > Thanks in advance > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Sat Aug 21 15:53:34 2010 From: evert.rol at gmail.com (Evert Rol) Date: Sat, 21 Aug 2010 15:53:34 +0200 Subject: [Tutor] check the terminal keyword In-Reply-To: References: Message-ID: <25FC30D4-A51A-4F7E-9A5B-94B9E753035F@gmail.com> > i m making a app in which i launch application using os.system("input from user"). I want to check whether the input entered by the user matches with the exact keyword in terminal or not. > like i want to launch vlc so user should provide me input as " vlc" in order to launch the app just like he did from terminal. I want to make a check on the input spell so that if he type "wlc" it shows an error to it. I have an little idea abt sys.agrv but don't know how to use it... Plz help me guys. Check the return value from os.system. If it's not 0, there was an error, likely caused by incorrect input. Better yet, catch the error message you get back from the command line, and act on that (eg, show it to the user). Eg, >>> r = os.system("hello") sh: hello: command not found >>> print r 32512 And have a look at the subprocess module, which I think is now the de facto module to run external processes. From rwobben at hotmail.com Sat Aug 21 16:41:03 2010 From: rwobben at hotmail.com (Roelof Wobben) Date: Sat, 21 Aug 2010 14:41:03 +0000 Subject: [Tutor] prime test problem In-Reply-To: References: , Message-ID: Hello, I know. I have read them all I believe but I can't see how I can convert the algebra to a working programm. Roelof Date: Sat, 21 Aug 2010 19:15:03 +0530 Subject: Re: [Tutor] prime test problem From: nitin.162 at gmail.com To: rwobben at hotmail.com CC: tutor at python.org For this problem u will get lots of solutions on the net. e.g wilson's theorem , sieve of eranthoses etc. --nitin On Sat, Aug 21, 2010 at 7:05 PM, Roelof Wobben wrote: Hello, I have to make a programm which can test if a number is a prime. I know a prime is a number which can only be diveded by 1 and itself. One way is was thinking about is to make a loop which try if % has output 0. But that don't work. Can someone give me a hint what's the best approach is. Roelof _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From rwobben at hotmail.com Sat Aug 21 16:58:31 2010 From: rwobben at hotmail.com (Roelof Wobben) Date: Sat, 21 Aug 2010 14:58:31 +0000 Subject: [Tutor] prime test problem In-Reply-To: References: , , , Message-ID: Hello, I forget to mention that I try to follow this book : Think like a computer scientist and I'm now working on chapter 4. Roelof From: rwobben at hotmail.com To: tutor at python.org Date: Sat, 21 Aug 2010 14:41:03 +0000 Subject: Re: [Tutor] prime test problem Hello, I know. I have read them all I believe but I can't see how I can convert the algebra to a working programm. Roelof Date: Sat, 21 Aug 2010 19:15:03 +0530 Subject: Re: [Tutor] prime test problem From: nitin.162 at gmail.com To: rwobben at hotmail.com CC: tutor at python.org For this problem u will get lots of solutions on the net. e.g wilson's theorem , sieve of eranthoses etc. --nitin On Sat, Aug 21, 2010 at 7:05 PM, Roelof Wobben wrote: Hello, I have to make a programm which can test if a number is a prime. I know a prime is a number which can only be diveded by 1 and itself. One way is was thinking about is to make a loop which try if % has output 0. But that don't work. Can someone give me a hint what's the best approach is. Roelof _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Sat Aug 21 17:11:53 2010 From: evert.rol at gmail.com (Evert Rol) Date: Sat, 21 Aug 2010 17:11:53 +0200 Subject: [Tutor] prime test problem In-Reply-To: References: , Message-ID: <6732A98E-E155-41B4-9330-FF78DB90F900@gmail.com> > Hello, > > I know. > I have read them all I believe but I can't see how I can convert the algebra to a working programm. And if you just search Google for "Python prime number algorithm"? Perhaps it's cheating, so you'll have to try and fully understand the code first before you run it (be sure to read comments if there are any, eg the activatestate recipes; can have tons of useful extra info & links). Generally, try to start with a program yourself, and then see where you get stuck. You could then post your stuck algorithm to the list and ask for advice; your current question is a bit too general, and thus harder to answer. Evert > > Roelof > > > Date: Sat, 21 Aug 2010 19:15:03 +0530 > Subject: Re: [Tutor] prime test problem > From: nitin.162 at gmail.com > To: rwobben at hotmail.com > CC: tutor at python.org > > For this problem u will get lots of solutions on the net. > e.g wilson's theorem , sieve of eranthoses etc. > > --nitin > > On Sat, Aug 21, 2010 at 7:05 PM, Roelof Wobben wrote: > Hello, > > I have to make a programm which can test if a number is a prime. > I know a prime is a number which can only be diveded by 1 and itself. > > One way is was thinking about is to make a loop which try if % has output 0. > But that don't work. > > Can someone give me a hint what's the best approach is. > > Roelof > From steve at pearwood.info Sat Aug 21 18:49:26 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 22 Aug 2010 02:49:26 +1000 Subject: [Tutor] prime test problem In-Reply-To: References: Message-ID: <201008220249.27986.steve@pearwood.info> On Sun, 22 Aug 2010 12:41:03 am Roelof Wobben wrote: > Hello, > > I know. > I have read them all I believe You've read all 64 million pages that Google finds? Wow, you must be a fast reader! Well done! > but I can't see how I can convert the > algebra to a working programm. Have you *tried*? Perhaps you should try something a little bit less ambitious. Write a program to test whether a number is divisible by 3. Then write a program to test whether a number is divisible by 3 or 5. Then write a third program to test whether a number is divisible by 3, 5 or 7. Then generalise that third program. Off you go. Come back when you have some code. Even if it isn't working code, at least try something. -- Steven D'Aprano From rwobben at hotmail.com Sat Aug 21 19:14:05 2010 From: rwobben at hotmail.com (Roelof Wobben) Date: Sat, 21 Aug 2010 17:14:05 +0000 Subject: [Tutor] prime test problem In-Reply-To: <201008220249.27986.steve@pearwood.info> References: , , , <201008220249.27986.steve@pearwood.info> Message-ID: Hello, I tried it with this simple programm def is_prime(n): x=2 while x <= int(n**0.5)+1: if n % x == 0: return False x=x+1; return True x=is_prime(7) if x==True: print 7, "is een prime getal" else : print 7, "is geen prime getal" But this one gets in a indefinitive loop. Roelof > From: steve at pearwood.info > To: tutor at python.org > Date: Sun, 22 Aug 2010 02:49:26 +1000 > Subject: Re: [Tutor] prime test problem > > On Sun, 22 Aug 2010 12:41:03 am Roelof Wobben wrote: > > Hello, > > > > I know. > > I have read them all I believe > > You've read all 64 million pages that Google finds? Wow, you must be a > fast reader! Well done! > > > but I can't see how I can convert the > > algebra to a working programm. > > Have you *tried*? > > Perhaps you should try something a little bit less ambitious. Write a > program to test whether a number is divisible by 3. Then write a > program to test whether a number is divisible by 3 or 5. Then write a > third program to test whether a number is divisible by 3, 5 or 7. > > Then generalise that third program. > > Off you go. Come back when you have some code. Even if it isn't working > code, at least try something. > > > > -- > Steven D'Aprano > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Sat Aug 21 19:21:10 2010 From: wallenpb at gmail.com (Bill Allen) Date: Sat, 21 Aug 2010 12:21:10 -0500 Subject: [Tutor] Windows Power Shell In-Reply-To: References: Message-ID: Alan, I have used WPS 1.0 for some time at work to script software installs, etc. It is very powerful and gives full .NET visibility to "DOS" level scripts. In fact, it is a plausible replacement for VB for most administrative scripting work in the Windows environment. Some good resources: The Hey Scripting Guy ! Technet blog is an execellent place to start as he focuses heavily on WPS. PowerShell.com WPS community (you can also sign up for really good daily WPS tips sent straight to you email here, I recommend these tips!) TechNet Learning to Script Center, focuses on WPS. Bill On Sat, Aug 21, 2010 at 3:20 AM, Alan Gauld wrote: > A recent windows update delivered the Windows Power Shell to my desktop. > > I'd heard of this but never used it till now. I've only started playing > with it but > it is essentially DOS on steroids. It brings Windows users a shell that > seems > to be very close to Unix shells like Bash in power and flexibility (and > scripting > language). It's very early days yet, but I wondered if any other tutor > members > had started using WPS? > > Some examples of the extra features include regex, objects, process > control, > remote invocation, better loop structures etc... > > Regards, > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From evert.rol at gmail.com Sat Aug 21 19:24:51 2010 From: evert.rol at gmail.com (Evert Rol) Date: Sat, 21 Aug 2010 19:24:51 +0200 Subject: [Tutor] prime test problem In-Reply-To: References: , , , <201008220249.27986.steve@pearwood.info> Message-ID: <89E5B3D1-3759-42E1-8E20-A3492545CA39@gmail.com> > Hello, > > I tried it with this simple programm > > def is_prime(n): > x=2 > while x <= int(n**0.5)+1: > if n % x == 0: > return False If your while condition is True, you get into the loop. Inside the loop, however, you never change anything that could change the condition (ie, neither x nor n get changed). So the while condition stays the same, ie, True, and you loop indefinitely. > x=x+1; Ah, but here you actually change something so that the while condition could become False. Sadly, this statement is outside the loop (hint hint). > > return True > > x=is_prime(7) > if x==True: > print 7, "is een prime getal" > else : > print 7, "is geen prime getal" > > > But this one gets in a indefinitive loop. Try to mentally follow the logic of the loop. Or use print statements and some small, easily checkable, numbers (prime and non-prime) to see what happens. Print statements (functions, if you're on Python >= 3) are a simple, but at times extremely quick and useful way to debug scripts. Ah yes, and either use "is een priemgetal" or "is a prime number", not a mix of both (sorry, couldn't help myself ;-). Evert > > Roelof > > > > From: steve at pearwood.info > > To: tutor at python.org > > Date: Sun, 22 Aug 2010 02:49:26 +1000 > > Subject: Re: [Tutor] prime test problem > > > > On Sun, 22 Aug 2010 12:41:03 am Roelof Wobben wrote: > > > Hello, > > > > > > I know. > > > I have read them all I believe > > > > You've read all 64 million pages that Google finds? Wow, you must be a > > fast reader! Well done! > > > > > but I can't see how I can convert the > > > algebra to a working programm. > > > > Have you *tried*? > > > > Perhaps you should try something a little bit less ambitious. Write a > > program to test whether a number is divisible by 3. Then write a > > program to test whether a number is divisible by 3 or 5. Then write a > > third program to test whether a number is divisible by 3, 5 or 7. > > > > Then generalise that third program. > > > > Off you go. Come back when you have some code. Even if it isn't working > > code, at least try something. > > > > > > > > -- > > Steven D'Aprano > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From rwobben at hotmail.com Sat Aug 21 19:30:57 2010 From: rwobben at hotmail.com (Roelof Wobben) Date: Sat, 21 Aug 2010 17:30:57 +0000 Subject: [Tutor] prime test problem In-Reply-To: <89E5B3D1-3759-42E1-8E20-A3492545CA39@gmail.com> References: , , , <201008220249.27986.steve@pearwood.info> , <89E5B3D1-3759-42E1-8E20-A3492545CA39@gmail.com> Message-ID: Hello, Thank you. It worked now. x=x+1 must have the same indention als the if then and the return. Roelof > Subject: Re: [Tutor] prime test problem > From: evert.rol at gmail.com > Date: Sat, 21 Aug 2010 19:24:51 +0200 > CC: tutor at python.org > To: rwobben at hotmail.com > > > Hello, > > > > I tried it with this simple programm > > > > def is_prime(n): > > x=2 > > while x <= int(n**0.5)+1: > > if n % x == 0: > > return False > > If your while condition is True, you get into the loop. > Inside the loop, however, you never change anything that could change the condition (ie, neither x nor n get changed). > So the while condition stays the same, ie, True, and you loop indefinitely. > > > > x=x+1; > > Ah, but here you actually change something so that the while condition could become False. Sadly, this statement is outside the loop (hint hint). > > > > > > return True > > > > x=is_prime(7) > > if x==True: > > print 7, "is een prime getal" > > else : > > print 7, "is geen prime getal" > > > > > > But this one gets in a indefinitive loop. > > Try to mentally follow the logic of the loop. > Or use print statements and some small, easily checkable, numbers (prime and non-prime) to see what happens. > Print statements (functions, if you're on Python >= 3) are a simple, but at times extremely quick and useful way to debug scripts. > > Ah yes, and either use "is een priemgetal" or "is a prime number", not a mix of both (sorry, couldn't help myself ;-). > > > Evert > > > > > > > Roelof > > > > > > > From: steve at pearwood.info > > > To: tutor at python.org > > > Date: Sun, 22 Aug 2010 02:49:26 +1000 > > > Subject: Re: [Tutor] prime test problem > > > > > > On Sun, 22 Aug 2010 12:41:03 am Roelof Wobben wrote: > > > > Hello, > > > > > > > > I know. > > > > I have read them all I believe > > > > > > You've read all 64 million pages that Google finds? Wow, you must be a > > > fast reader! Well done! > > > > > > > but I can't see how I can convert the > > > > algebra to a working programm. > > > > > > Have you *tried*? > > > > > > Perhaps you should try something a little bit less ambitious. Write a > > > program to test whether a number is divisible by 3. Then write a > > > program to test whether a number is divisible by 3 or 5. Then write a > > > third program to test whether a number is divisible by 3, 5 or 7. > > > > > > Then generalise that third program. > > > > > > Off you go. Come back when you have some code. Even if it isn't working > > > code, at least try something. > > > > > > > > > > > > -- > > > Steven D'Aprano > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > To unsubscribe or change subscription options: > > > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wallenpb at gmail.com Sat Aug 21 19:31:21 2010 From: wallenpb at gmail.com (Bill Allen) Date: Sat, 21 Aug 2010 12:31:21 -0500 Subject: [Tutor] Windows Power Shell In-Reply-To: References: Message-ID: The very best first feature to learn is the "foreach" command. It elegantly solves the icky, age old, problem in DOS batch of reading in a list of values from a file and doing something with them. This alone sold me completely on WPS. For instance, here is and actual script I used to push an install source to all my engineering systems at work, listed in computers.txt, by invoking richcopy(also a fantastic utility, Microsoft's modern replacement for robocopy. get-content computers.txt | foreach -process {richcopy "\\myNAS\NasShare\NX6\nx6028" "\\$_\c$\nx6028" /TD 10 /QA /QP "c:\results.log" /US /UD /UE} Sorry for taking up additional "non-Python" bandwidth, but I got excited about being able to contribute something back to the group that I actual know about! ;-D Bill On Sat, Aug 21, 2010 at 12:21 PM, Bill Allen wrote: > Alan, > > I have used WPS 1.0 for some time at work to script software installs, > etc. It is very powerful and gives full .NET visibility to "DOS" level > scripts. In fact, it is a plausible replacement for VB for most > administrative scripting work in the Windows environment. > > Some good resources: > The Hey Scripting Guy ! > Technet blog is an execellent place to start as he focuses heavily on WPS. > PowerShell.com WPS community (you can also > sign up for really good daily WPS tips sent straight to you email here, I > recommend these tips!) > TechNet Learning to Script Center, > focuses on WPS. > > > Bill > > > > > > On Sat, Aug 21, 2010 at 3:20 AM, Alan Gauld wrote: > >> A recent windows update delivered the Windows Power Shell to my desktop. >> >> I'd heard of this but never used it till now. I've only started playing >> with it but >> it is essentially DOS on steroids. It brings Windows users a shell that >> seems >> to be very close to Unix shells like Bash in power and flexibility (and >> scripting >> language). It's very early days yet, but I wondered if any other tutor >> members >> had started using WPS? >> >> Some examples of the extra features include regex, objects, process >> control, >> remote invocation, better loop structures etc... >> >> Regards, >> >> Alan G. >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Aug 21 20:14:14 2010 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 21 Aug 2010 19:14:14 +0100 Subject: [Tutor] prime test problem References: , , , <201008220249.27986.steve@pearwood.info>, <89E5B3D1-3759-42E1-8E20-A3492545CA39@gmail.com> Message-ID: "Roelof Wobben" wrote > It worked now. > x=x+1 must have the same indention als the if then and the return. Or more specifically, it must be indented further than the while statement. The fact thatv the other commands inside the while loop happen to be an if/else is incidental x=1 while x < 10: x = x+1 works as a loop too. Alan G. From bgailer at gmail.com Sat Aug 21 20:28:41 2010 From: bgailer at gmail.com (bob gailer) Date: Sat, 21 Aug 2010 14:28:41 -0400 Subject: [Tutor] design of Point class In-Reply-To: <4C6F1F35.8040007@gmail.com> References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu> <1D673F86DDA00841A1216F04D1CE70D6426032DE61@EXCH2.nws.oregonstate.edu> <4C6F1F35.8040007@gmail.com> Message-ID: <4C701AD9.3010209@gmail.com> On 8/20/2010 8:35 PM, bob gailer wrote: > After yet more thought it gets even more better: I even added a unit test. class PointND(list): def __init__(self, *a_list): super(PointND, self).__init__(a_list) def getSet(ix): def chklen(self): if len(self) < ix + 1: raise AttributeError def get(self): chklen(self) return self[ix] def set(self, value): chklen(self) self[ix] = value return property(get, set) def set(self, ix): return s x = getSet(0) y = getSet(1) z = getSet(2) p = PointND(1,2,3) assert (p.x, p.y, p.z) == (1, 2, 3) p.x = 6; p.y = 9; p.z = 5 assert (p.x, p.y, p.z) == (6, 9, 5) try: p = PointND(1,2) p.z = 3 except AttributeError: print 'Passed all tests' except: print 'some other exception' -- Bob Gailer 919-636-4239 Chapel Hill NC From rwobben at hotmail.com Sat Aug 21 20:36:00 2010 From: rwobben at hotmail.com (Roelof Wobben) Date: Sat, 21 Aug 2010 18:36:00 +0000 Subject: [Tutor] newline problem Message-ID: Hello, I have this programm : def print_digits(n): """ >>> print_digits(13789) 9 8 7 3 1 >>> print_digits(39874613) 3 1 6 4 7 8 9 3 >>> print_digits(213141) 1 4 1 3 1 2 """ count = 0 while n: count = count + 1 n = n / 10 return count getal=13789 x=print_digits(getal) teller=1 while teller <=x : digit=float(getal/10.0) digit2=float(digit-int(digit))*10 getal=digit print int(digit2) teller=teller+1 But now every digit is placed on another line. How can I prevent this ? Roelof -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sat Aug 21 21:09:04 2010 From: bgailer at gmail.com (bob gailer) Date: Sat, 21 Aug 2010 15:09:04 -0400 Subject: [Tutor] newline problem In-Reply-To: References: Message-ID: <4C702450.7000704@gmail.com> On 8/21/2010 2:36 PM, Roelof Wobben wrote: > Hello, > > I have this programm : > > def print_digits(n): > """ > >>> print_digits(13789) > 9 8 7 3 1 > >>> print_digits(39874613) > 3 1 6 4 7 8 9 3 > >>> print_digits(213141) > 1 4 1 3 1 2 """ > > count = 0 > while n: > count = count + 1 > n = n / 10 > return count > getal=13789 > x=print_digits(getal) > teller=1 > while teller <=x : > digit=float(getal/10.0) > digit2=float(digit-int(digit))*10 > getal=digit > print int(digit2) > teller=teller+1 > > > But now every digit is placed on another line. > How can I prevent this ? print int(digit2), # add a comma Your algorithm is unnecessarily complicated. You don't need to count first. You don't need float. getal=13789 while getal > 0: getal, digit = divmod(getal, 10) print digit, But it is easier to just: print " ".join(str(getal)) -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From tfultz33 at gmail.com Sat Aug 21 21:37:09 2010 From: tfultz33 at gmail.com (Thomas) Date: Sat, 21 Aug 2010 15:37:09 -0400 Subject: [Tutor] monodevelop 2.2 Message-ID: I was wondering if someone could tell me if you can use the gui designer in monodevelop 2.2+ with python. Thanks, Thomas From emile at fenx.com Sat Aug 21 22:17:56 2010 From: emile at fenx.com (Emile van Sebille) Date: Sat, 21 Aug 2010 13:17:56 -0700 Subject: [Tutor] monodevelop 2.2 In-Reply-To: References: Message-ID: On 8/21/2010 12:37 PM Thomas said... > I was wondering if someone could tell me if you can use the gui designer > in monodevelop 2.2+ with python. > Searching groups.google.com with "use the gui designer in monodevelop 2.2+ with python" yields a first hit that says "I just used MonoDevelop 2.2 for Python under Ubuntu. IT'S AMAZING!" http://www.daniweb.com/forums/thread286328.html So, sounds like a yes to me. Emile From nblack3 at student.gsu.edu Sun Aug 22 01:06:52 2010 From: nblack3 at student.gsu.edu (Nick) Date: Sat, 21 Aug 2010 23:06:52 +0000 Subject: [Tutor] Tutor Digest, Vol 78, Issue 97 In-Reply-To: References: Message-ID: ________________________________________ From: tutor-bounces+nblack3=student.gsu.edu at python.org [tutor-bounces+nblack3=student.gsu.edu at python.org] on behalf of tutor-request at python.org [tutor-request at python.org] Sent: Saturday, August 21, 2010 1:25 PM To: tutor at python.org Subject: Tutor Digest, Vol 78, Issue 97 Send Tutor mailing list submissions to tutor at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-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: prime test problem (Evert Rol) 2. Re: prime test problem (Steven D'Aprano) 3. Re: prime test problem (Roelof Wobben) 4. Re: Windows Power Shell (Bill Allen) 5. Re: prime test problem (Evert Rol) ---------------------------------------------------------------------- Message: 1 Date: Sat, 21 Aug 2010 17:11:53 +0200 From: Evert Rol To: Roelof Wobben Cc: tutor at python.org Subject: Re: [Tutor] prime test problem Message-ID: <6732A98E-E155-41B4-9330-FF78DB90F900 at gmail.com> Content-Type: text/plain; charset=us-ascii > Hello, > > I know. > I have read them all I believe but I can't see how I can convert the algebra to a working programm. And if you just search Google for "Python prime number algorithm"? Perhaps it's cheating, so you'll have to try and fully understand the code first before you run it (be sure to read comments if there are any, eg the activatestate recipes; can have tons of useful extra info & links). Generally, try to start with a program yourself, and then see where you get stuck. You could then post your stuck algorithm to the list and ask for advice; your current question is a bit too general, and thus harder to answer. Evert > > Roelof > > > Date: Sat, 21 Aug 2010 19:15:03 +0530 > Subject: Re: [Tutor] prime test problem > From: nitin.162 at gmail.com > To: rwobben at hotmail.com > CC: tutor at python.org > > For this problem u will get lots of solutions on the net. > e.g wilson's theorem , sieve of eranthoses etc. > > --nitin > > On Sat, Aug 21, 2010 at 7:05 PM, Roelof Wobben wrote: > Hello, > > I have to make a programm which can test if a number is a prime. > I know a prime is a number which can only be diveded by 1 and itself. > > One way is was thinking about is to make a loop which try if % has output 0. > But that don't work. > > Can someone give me a hint what's the best approach is. > > Roelof > ------------------------------ Message: 2 Date: Sun, 22 Aug 2010 02:49:26 +1000 From: Steven D'Aprano To: tutor at python.org Subject: Re: [Tutor] prime test problem Message-ID: <201008220249.27986.steve at pearwood.info> Content-Type: text/plain; charset="utf-8" On Sun, 22 Aug 2010 12:41:03 am Roelof Wobben wrote: > Hello, > > I know. > I have read them all I believe You've read all 64 million pages that Google finds? Wow, you must be a fast reader! Well done! > but I can't see how I can convert the > algebra to a working programm. Have you *tried*? Perhaps you should try something a little bit less ambitious. Write a program to test whether a number is divisible by 3. Then write a program to test whether a number is divisible by 3 or 5. Then write a third program to test whether a number is divisible by 3, 5 or 7. Then generalise that third program. Off you go. Come back when you have some code. Even if it isn't working code, at least try something. -- Steven D'Aprano -------- My reply: I may be formatting this wrong. This is my first time posting to this list as I'm a relatively new subscriber. I think I read the directions right in that it said don't top post, post under what you're responding to. I'm sorry to anyone I offend if I got this wrong. I was interested in this specific topic as I've been working some problems on project euler. I've been stuck on a prime one more or less because I don't understand all the scripts I've been viewing (trying to learn how to approach it). I get stuck in various areas specific to each one. While that is general here is my real question. "Perhaps you should try something a little bit less ambitious. Write a program to test whether a number is divisible by 3. Then write a program to test whether a number is divisible by 3 or 5. Then write a third program to test whether a number is divisible by 3, 5 or 7." The very first problem for projecteuler.net makes you write a program that finds all factors of 3 and 5 for n < 1000. Were they trying to lead me down the path you're alluding to? I'm not seeing the connection between that particular problem and finding primes. I would appreciate more insight. Thanks everyone! ------------------------------ Message: 3 Date: Sat, 21 Aug 2010 17:14:05 +0000 From: Roelof Wobben To: Subject: Re: [Tutor] prime test problem Message-ID: Content-Type: text/plain; charset="iso-8859-1" Hello, I tried it with this simple programm def is_prime(n): x=2 while x <= int(n**0.5)+1: if n % x == 0: return False x=x+1; return True x=is_prime(7) if x==True: print 7, "is een prime getal" else : print 7, "is geen prime getal" But this one gets in a indefinitive loop. Roelof > From: steve at pearwood.info > To: tutor at python.org > Date: Sun, 22 Aug 2010 02:49:26 +1000 > Subject: Re: [Tutor] prime test problem > > On Sun, 22 Aug 2010 12:41:03 am Roelof Wobben wrote: > > Hello, > > > > I know. > > I have read them all I believe > > You've read all 64 million pages that Google finds? Wow, you must be a > fast reader! Well done! > > > but I can't see how I can convert the > > algebra to a working programm. > > Have you *tried*? > > Perhaps you should try something a little bit less ambitious. Write a > program to test whether a number is divisible by 3. Then write a > program to test whether a number is divisible by 3 or 5. Then write a > third program to test whether a number is divisible by 3, 5 or 7. > > Then generalise that third program. > > Off you go. Come back when you have some code. Even if it isn't working > code, at least try something. > > > > -- > Steven D'Aprano > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 4 Date: Sat, 21 Aug 2010 12:21:10 -0500 From: Bill Allen To: Alan Gauld Cc: tutor at python.org Subject: Re: [Tutor] Windows Power Shell Message-ID: Content-Type: text/plain; charset="iso-8859-1" Alan, I have used WPS 1.0 for some time at work to script software installs, etc. It is very powerful and gives full .NET visibility to "DOS" level scripts. In fact, it is a plausible replacement for VB for most administrative scripting work in the Windows environment. Some good resources: The Hey Scripting Guy ! Technet blog is an execellent place to start as he focuses heavily on WPS. PowerShell.com WPS community (you can also sign up for really good daily WPS tips sent straight to you email here, I recommend these tips!) TechNet Learning to Script Center, focuses on WPS. Bill On Sat, Aug 21, 2010 at 3:20 AM, Alan Gauld wrote: > A recent windows update delivered the Windows Power Shell to my desktop. > > I'd heard of this but never used it till now. I've only started playing > with it but > it is essentially DOS on steroids. It brings Windows users a shell that > seems > to be very close to Unix shells like Bash in power and flexibility (and > scripting > language). It's very early days yet, but I wondered if any other tutor > members > had started using WPS? > > Some examples of the extra features include regex, objects, process > control, > remote invocation, better loop structures etc... > > Regards, > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 5 Date: Sat, 21 Aug 2010 19:24:51 +0200 From: Evert Rol To: Roelof Wobben Cc: tutor at python.org Subject: Re: [Tutor] prime test problem Message-ID: <89E5B3D1-3759-42E1-8E20-A3492545CA39 at gmail.com> Content-Type: text/plain; charset=us-ascii > Hello, > > I tried it with this simple programm > > def is_prime(n): > x=2 > while x <= int(n**0.5)+1: > if n % x == 0: > return False If your while condition is True, you get into the loop. Inside the loop, however, you never change anything that could change the condition (ie, neither x nor n get changed). So the while condition stays the same, ie, True, and you loop indefinitely. > x=x+1; Ah, but here you actually change something so that the while condition could become False. Sadly, this statement is outside the loop (hint hint). > > return True > > x=is_prime(7) > if x==True: > print 7, "is een prime getal" > else : > print 7, "is geen prime getal" > > > But this one gets in a indefinitive loop. Try to mentally follow the logic of the loop. Or use print statements and some small, easily checkable, numbers (prime and non-prime) to see what happens. Print statements (functions, if you're on Python >= 3) are a simple, but at times extremely quick and useful way to debug scripts. Ah yes, and either use "is een priemgetal" or "is a prime number", not a mix of both (sorry, couldn't help myself ;-). Evert > > Roelof > > > > From: steve at pearwood.info > > To: tutor at python.org > > Date: Sun, 22 Aug 2010 02:49:26 +1000 > > Subject: Re: [Tutor] prime test problem > > > > On Sun, 22 Aug 2010 12:41:03 am Roelof Wobben wrote: > > > Hello, > > > > > > I know. > > > I have read them all I believe > > > > You've read all 64 million pages that Google finds? Wow, you must be a > > fast reader! Well done! > > > > > but I can't see how I can convert the > > > algebra to a working programm. > > > > Have you *tried*? > > > > Perhaps you should try something a little bit less ambitious. Write a > > program to test whether a number is divisible by 3. Then write a > > program to test whether a number is divisible by 3 or 5. Then write a > > third program to test whether a number is divisible by 3, 5 or 7. > > > > Then generalise that third program. > > > > Off you go. Come back when you have some code. Even if it isn't working > > code, at least try something. > > > > > > > > -- > > Steven D'Aprano > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor ------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 78, Issue 97 ************************************* From steve at pearwood.info Sun Aug 22 02:01:22 2010 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 22 Aug 2010 10:01:22 +1000 Subject: [Tutor] Tutor Digest, Vol 78, Issue 97 In-Reply-To: References: Message-ID: <201008221001.23221.steve@pearwood.info> Nick, You have replied to a mailing digest containing five different messages. I have NO IDEA what you have to say, because I'm not going to read through all five messages, over 400 lines of text, trying to determine which bits you are commenting on and which bits you are not. You have a delete or backspace key on your keyboard. Please learn to use it by trimming the quoted text so that ONLY the parts you are replying to are there. Leave enough test quoted to establish context of what you are discussing, and delete everything else from your reply. We don't need to see the entire day's worth of emails again, we've already seen them. Also, change the subject line to something meaningful, instead of the useless "Re: [Tutor] Tutor Digest...". Just like the digest already suggests: > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." If you're replying to a message, you should change the subject line to match the subject line of that message (plus "Re: " at the beginning, if it's not already there). Personally, I find the digest setting of mailing lists to be worse than useless. I recommend that you change to individual mail, but of course that's up to you. Regards, -- Steven D'Aprano From nblack3 at student.gsu.edu Sun Aug 22 05:54:43 2010 From: nblack3 at student.gsu.edu (Nick) Date: Sun, 22 Aug 2010 03:54:43 +0000 Subject: [Tutor] Tutor Digest, Vol 78, Issue 99 -- Prime numbers Message-ID: "Perhaps you should try something a little bit less ambitious. Write a program to test whether a number is divisible by 3. Then write a program to test whether a number is divisible by 3 or 5. Then write a third program to test whether a number is divisible by 3, 5 or 7. Then generalise that third program. Steven D'Aprano" *** Sorry for posting like that to the list. I thought I was doing it correctly, but really messed that one up. I think I'm doing everything correctly now, but please tell me what I'm not-- if such is the case. I was interested in this specific topic as I've been working some problems on project euler. I've been trying to generate prime numbers as a first step to go about solving a problem. I don't have a particular question about solving the problem, but want to ask about a relationship. The very first problem for projecteuler.net makes you write a program that finds all factors of 3 and 5 for n < 1000. Were they trying to lead me down the path you're alluding to? I'm not seeing the connection between that particular problem and finding primes. I would appreciate more insight. Thanks everyone! From wallenpb at gmail.com Sun Aug 22 06:10:19 2010 From: wallenpb at gmail.com (Bill Allen) Date: Sat, 21 Aug 2010 23:10:19 -0500 Subject: [Tutor] inserting variables into a docstring Message-ID: I am trying to build an HTML body text for an email using a docstring with variables inserted a certain points. It all works just fine, except that the first instance of the variable "pecn" in the HTML link does not get inserted into the text. The second instance of "pecn" gets inserted ok into that HTML link. What is the right way to do this or is there a better way in general? This my code: pecn = "5022543" pecn_project = "F876540" pdesc = "some sort of ECN for who knows what reason!" newMail.HTMLBody = """

ECN number """+pecn+""" on Project """+pecn_project+""" has been closed.
Below is a link to the ECN on the intranet.
"""+pecn+"""
ECN Description:
"""+pdesc+"""

ECN Effect of Change Comments:
    (still need to work on this part)

R&D Information:
    (still need to work on this part)
""" -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Sun Aug 22 06:27:36 2010 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Sat, 21 Aug 2010 23:27:36 -0500 Subject: [Tutor] inserting variables into a docstring In-Reply-To: References: Message-ID: On Sat, Aug 21, 2010 at 11:10 PM, Bill Allen wrote: > I am trying to build an HTML body text for an email using a docstring with > variables inserted a certain points.? It all works just fine, except that > the first instance of the variable "pecn" in the HTML link does not get > inserted into the text.? The second instance of "pecn" gets inserted ok into > that HTML link.?? What is the right way to do this or is there a better way > in general? > The variable is inserted just fine for me, though there's some problems with the tag, because you shouldn't surround GET variables with quotation marks, e.g. you should do this: http://example.com/?ecn=423434 NOT this: http://example.com/?ecn="423434" If you do this, the HTML parser will encounter the first ", think that it's come to the end of the href="" attribute, and ignore the rest. But that's an HTML issue, not a python one. As an aside, consider using string formatting operations like so: newMail.HTMLBody = """
ECN number {0} on Project {1} has been closed.
Below is a link to the ECN on the intranet.
{0}
ECN Description:
{2}""".format(pecn, pecn_project, pdesc)

Hugo

From wallenpb at gmail.com  Sun Aug 22 06:49:05 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Sat, 21 Aug 2010 23:49:05 -0500
Subject: [Tutor] inserting variables into a docstring
In-Reply-To: 
References: 
	
Message-ID: 

On Sat, Aug 21, 2010 at 11:27 PM, Hugo Arts  wrote:

>
> The variable is inserted just fine for me, though there's some
> problems with the  tag, because you shouldn't surround GET
> variables with quotation marks, e.g. you should do this:
>
> http://example.com/?ecn=423434
> NOT this:
> http://example.com/?ecn="423434"
>
> If you do this, the HTML parser will encounter the first ", think that
> it's come to the end of the href="" attribute, and ignore the rest.
> But that's an HTML issue, not a python one.
>
> As an aside, consider using string formatting operations like so:
>
> newMail.HTMLBody = """
> 
> ECN number {0} on Project {1} has been closed.
> Below is a link to the ECN on the intranet.
> {0}
> ECN Description:
> {2}""".format(pecn, pecn_project, pdesc)
>
>
> Hugo,

Thank you for the reminder of the problem with the HTML.  I see that now.
You are right, however, using that format method works wonderfully and is
definitely the way to go!   I see how I can apply that in lots of ways.

Thanks for the help,
Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From steve at pearwood.info  Sun Aug 22 07:23:06 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 22 Aug 2010 15:23:06 +1000
Subject: [Tutor] Tutor Digest, Vol 78, Issue 99 --  Prime numbers
In-Reply-To: 
References: 
Message-ID: <201008221523.07846.steve@pearwood.info>

On Sun, 22 Aug 2010 01:54:43 pm Nick wrote:

> I was interested in this specific topic as I've been working some
> problems on project euler. I've been trying to generate prime numbers
> as a first step to go about solving a problem.  I don't have a
> particular question about solving the problem, but want to ask about
> a relationship.
>
> The very first problem for projecteuler.net makes you write a program
> that finds all factors of 3 and 5 for n < 1000.  Were they trying to
> lead me down the path you're alluding to?  I'm not seeing the
> connection between that particular problem and finding primes.  I
> would appreciate more insight.  Thanks everyone!

Think about the definition of prime numbers. A number is prime if it has 
no factors other than itself and 1. (Except for 1, which is excluded by 
definition.)

So if you know that these numbers are divisible by 3:

3, 6, 9, 12, 15, 18, 21, ... 

and these numbers are divisible by 5:

5, 10, 15, 20, 25, 30, ... 

then you know that apart from the first number in each list (3 and 5) 
none of the other numbers could be prime. 12, for example, is not prime 
because it is divisible by 3 (also by 2), and 15 is not prime because 
it is divisible by 5 (also by 3).

More importantly, the code you write to detect *non-primes* will be 
quite similar to the code you write to detect primes. They're nearly 
checking the same thing:

If n is divisible by 3, then it goes in the "multiples of 3" list.
If n is divisible by 5, then it goes in the "multiples of 5" list.
If n is divisible by 7, then it goes in the "multiples of 7" list.
...

Compare that to primes:

If n is divisible by 2 (apart from 2 itself), then it is not a prime.
If n is divisible by 3 (apart from 3 itself), then it is not a prime.
If n is divisible by 4 (apart from 4 itself), then it is not a prime.
If n is divisible by 5 (apart from 5 itself), then it is not a prime.
If n is divisible by 6 (apart from 6 itself), then it is not a prime.
If n is divisible by 7 (apart from 7 itself), then it is not a prime.
...
Otherwise, if we get to n, and there are no other factors, then it is a 
prime.

But wait, this is doing too much work. If a number is divisible by 4, 
then it's also divisible by 2. Likewise if it is divisible by 6, 8, 10, 
12, ... any even number. So we eliminated all the even numbers (other 
than 2 itself) and there's no point in testing for divisibility by 4, 
6, 8, ...


If n is divisible by 2 (apart from 2 itself), then it is not a prime.
If n is divisible by 3 (apart from 3 itself), then it is not a prime.
If n is divisible by 5 (apart from 5 itself), then it is not a prime.
If n is divisible by 7 (apart from 7 itself), then it is not a prime.
...
Otherwise, if we get to n, and there are no other factors, then it is a 
prime.

We're still doing too much work. Why go all the way up to n? We know 
that (say) 93 can't possibly divide into 99, or 57 into 59. The largest 
number we need to check is the square root of n. The reason is a little 
subtle, so think about it, don't just take my word.

Hint: write down the factors of, say, 60: Can you see the pattern?

2*30, 3*10, 5*6, 6*5, 10*3, 30*2




-- 
Steven D'Aprano

From nblack3 at student.gsu.edu  Sun Aug 22 07:47:21 2010
From: nblack3 at student.gsu.edu (Nick)
Date: Sun, 22 Aug 2010 05:47:21 +0000
Subject: [Tutor] Tutor Digest, Vol 78,
 Issue 100 -- Prime numbers using square root of n
Message-ID: 

"We're still doing too much work. Why go all the way up to n? We know
that (say) 93 can't possibly divide into 99, or 57 into 59. The largest
number we need to check is the square root of n. The reason is a little
subtle, so think about it, don't just take my word.

Hint: write down the factors of, say, 60: Can you see the pattern?

2*30, 3*10, 5*6, 6*5, 10*3, 30*2
--
Steven D'Aprano"

Thanks so much Steven.  I get it all except I don't think I see the pattern.  I see that we're already covering those higher factors since they're divisble by 2, 3, 5, etc.  I'm just not connecting the final dot with the square root of n.  It's almost there in my mind!  I just need a little more of a push!  Also I can write a program that tests whether the number is a factor of 2, 3, 5, 7, but I think you're trying to point to me that this is cumbersome and not necessary.  I just don't see the rest of the light quite yet.  I have been looking at code on the internet too, but there are lots of different ways to skin a cat and it seems people are taking advantage of that.  I keep hitting road blocks in code.  I want to understand!

From steve at pearwood.info  Sun Aug 22 08:25:06 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 22 Aug 2010 16:25:06 +1000
Subject: [Tutor] Tutor Digest, Vol 78,
	Issue 100 -- Prime numbers using square root of n
In-Reply-To: 
References: 
Message-ID: <201008221625.07329.steve@pearwood.info>

On Sun, 22 Aug 2010 03:47:21 pm Nick wrote:

> Thanks so much Steven.  I get it all except I don't think I see the
> pattern.  I see that we're already covering those higher factors
> since they're divisble by 2, 3, 5, etc.  I'm just not connecting the
> final dot with the square root of n.  It's almost there in my mind! 
> I just need a little more of a push!

Okay, let's consider an example: n = 100. We start checking factors of 
100 by dividing by 1, 2, 3, 4, ... and so on:

1 * 100 = 100
2 * 50 = 100
4 * 25 = 100
5 * 20 = 100
...

As the first factor increases, the second factor decreases 
proportionally. It has to, because the product is always 100. So, if 
you have one pattern going up (1, 2, 4, 5, ...), and another pattern 
going down (100, 50, 25, 20, ...), there must be a point where the two 
patterns cross! That point is at the square root:

10 * 10 = 100

Once you pass the square root, any factors you find will be the same as 
the factors you've already seen, only reversed:

20 * 5 = 100  # Seen this one before as 5*20.

Not all numbers have a whole number square root, but the principle still 
holds:


1 * 120 = 120
2 * 60 = 120
3 * 40 = 120
4 * 30 = 120
5 * 24 = 120
6 * 20 = 120
8 * 15 = 120
10 * 12 = 120
10.9545 * 10.9545 = 120
12 * 10 = 120  <=== already seen this one!



> Also I can write a program that 
> tests whether the number is a factor of 2, 3, 5, 7, but I think
> you're trying to point to me that this is cumbersome and not
> necessary.

Sort of. I'm not suggest that you create lists of multiples of 2, 3, 5, 
7 etc, and then cross off non-primes by checking to see if they are in 
one of those lists. That truly would be cumbersome and slow. But the 
two problems are similar. For simplicity, let's ignore 2 as a prime, 
and only think about odd numbers:

(1) For each odd number N between 3 and (say) 1000, check if it is a 
multiple of 3, 5, 7, 9, ... and IF SO, put it in the list "nonprimes".

versus:

(2) For each odd number N between 3 and (say) 1000, check if it is a 
multiple of 3, 5, 7, 9, ... and IF NOT, put it in the list "primes".


See, they are very nearly the same problem. The tricky bits are:

* dealing with 2 is a special case;

* you don't want to exclude (say) 3 from being a prime because it is 
divisible by 3; and

* you can stop testing at square-root of N.



-- 
Steven D'Aprano

From alan.gauld at btinternet.com  Sun Aug 22 10:31:47 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 22 Aug 2010 09:31:47 +0100
Subject: [Tutor] Tutor Digest, Vol 78, Issue 99 --  Prime numbers
References: 
Message-ID: 


"Nick"  wrote

> I think I'm doing everything correctly now, but please tell me what 
> I'm not-- if such is the case.


One last thing - change the subject line to reflect the actual 
subject.

Alan G. 



From rwobben at hotmail.com  Sun Aug 22 12:05:03 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sun, 22 Aug 2010 10:05:03 +0000
Subject: [Tutor] type()  problem
Message-ID: 


Hello, 

 

This is my exercise:

 

Write Python code to make each of the following doctests pass:

"""
  >>> type(fruit)
  
  >>> len(fruit)
  8
  >>> fruit[:3]
  'ram'
"""
I have made this :""""
  >>> type(fruit)
  
  >>> len(fruit)
  8
  >>> fruit[:3]
  'ram'
"""
fruit="ramadana"
print "fruit heeft als type", type(fruit)
y=len(fruit)
print yz=fruit[:3]
print zEverything works fine except the type () does not give any input.WWhat am I doing wrong Roelof  		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From malaclypse2 at gmail.com  Sun Aug 22 16:51:47 2010
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Sun, 22 Aug 2010 10:51:47 -0400
Subject: [Tutor] Elementtree and pretty printing in Python 2.7
In-Reply-To: <4C6E3386.9070903@googlemail.com>
References: <4C6E3386.9070903@googlemail.com>
Message-ID: 

On Fri, Aug 20, 2010 at 3:49 AM, Knacktus  wrote:
> Hi guys,
>
> I'm using Python 2.7 and the ElementTree standard-lib to write some xml.
>
> My output xml has no line breaks! So, it looks like that:
>
> 
>
> instead of something like this:
>
> 
> ? ?
> 
>
> I'm aware of lxml which seems to have a pretty print option, but I would
> prefer to use the standard-lib ElementTree which seems not to have a feature
> like this.
>
> Do I miss something using the ElementTree-lib or is it bug?

Neither, as far as I know.  The XML you get is perfectly valid XML.
If you want to pretty print it, there's a recipe here:
http://effbot.org/zone/element-lib.htm#prettyprint, but I don't think
it's been included in the standard library yet.

-- 
Jerry

From karim.liateni at free.fr  Sun Aug 22 17:27:39 2010
From: karim.liateni at free.fr (Karim)
Date: Sun, 22 Aug 2010 17:27:39 +0200
Subject: [Tutor] Elementtree and pretty printing in Python 2.7
In-Reply-To: <4C714122.1000303@free.fr>
References: <4C6E3386.9070903@googlemail.com>
	
	<4C714122.1000303@free.fr>
Message-ID: <4C7141EB.9000602@free.fr>


Sorry wrong import!

from xml.minidom import parseString
from xml.etree import ElementTree

Karim

On 08/22/2010 05:24 PM, Karim wrote:
>
> Hello Jerry,
>
> Tricky solution using minidom (standard) Not tested:
>
> import ElementTree
> import minidom
>
> def prettyPrint(element):
>    txt = ElementTree.tostring(element)
>    print minidom.parseString(txt).toprettyxml()
>
>
> Regards
> Karim
>
> On 08/22/2010 04:51 PM, Jerry Hill wrote:
>> On Fri, Aug 20, 2010 at 3:49 AM, Knacktus  
>> wrote:
>>> Hi guys,
>>>
>>> I'm using Python 2.7 and the ElementTree standard-lib to write some 
>>> xml.
>>>
>>> My output xml has no line breaks! So, it looks like that:
>>>
>>> 
>>>
>>> instead of something like this:
>>>
>>> 
>>> 
>>> 
>>>
>>> I'm aware of lxml which seems to have a pretty print option, but I 
>>> would
>>> prefer to use the standard-lib ElementTree which seems not to have a 
>>> feature
>>> like this.
>>>
>>> Do I miss something using the ElementTree-lib or is it bug?
>> Neither, as far as I know.  The XML you get is perfectly valid XML.
>> If you want to pretty print it, there's a recipe here:
>> http://effbot.org/zone/element-lib.htm#prettyprint, but I don't think
>> it's been included in the standard library yet.
>>
>


From knacktus at googlemail.com  Sun Aug 22 19:47:09 2010
From: knacktus at googlemail.com (Knacktus)
Date: Sun, 22 Aug 2010 19:47:09 +0200
Subject: [Tutor] type()  problem
In-Reply-To: 
References: 
Message-ID: <4C71629D.8010904@googlemail.com>


> fruit="ramadana"
> print "fruit heeft als type", type(fruit)
> y=len(fruit)
> print y
>
> z=fruit[:3]
> print z
>

These lines put in a module and executed print (using Python 2.7):

fruit heeft als type 
8
ram

Strange that it doesn't work for you.

I can only advice you to check the file again or run the code from the 
Python shell.

HTH,

Jan



From rwobben at hotmail.com  Sun Aug 22 19:51:20 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sun, 22 Aug 2010 17:51:20 +0000
Subject: [Tutor] type()  problem
In-Reply-To: <4C71629D.8010904@googlemail.com>
References: ,
	<4C71629D.8010904@googlemail.com>
Message-ID: 


Hello, 

 

Very wierd.

>From a python shell it works.

If a type it as module in SPE , it doesn't work.

 

Roelof


 
> Date: Sun, 22 Aug 2010 19:47:09 +0200
> From: knacktus at googlemail.com
> To: tutor at python.org
> Subject: Re: [Tutor] type() problem
> 
> 
> > fruit="ramadana"
> > print "fruit heeft als type", type(fruit)
> > y=len(fruit)
> > print y
> >
> > z=fruit[:3]
> > print z
> >
> 
> These lines put in a module and executed print (using Python 2.7):
> 
> fruit heeft als type 
> 8
> ram
> 
> Strange that it doesn't work for you.
> 
> I can only advice you to check the file again or run the code from the 
> Python shell.
> 
> HTH,
> 
> Jan
> 
> 
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rwobben at hotmail.com  Sun Aug 22 20:35:15 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sun, 22 Aug 2010 18:35:15 +0000
Subject: [Tutor] input problem
Message-ID: 


Hello, 

 

I made this programm :

 

def count_letters(n,a):
    count = 0
    for char in n:
        if char == a:
            count += 1
    return count

fruit=""
letter=""
fruit= input("Enter a sort of fruit: ")
teller = input("Enter the character which must be counted: ")
x=count_letters (fruit,letter) 
print "De letter", letter , "komt", x , "maal voor in het woord", fruit

 

The problem is that I can't have the opportuntity for input anything.

I use python 2.7 on a Win7 machine with as editor SPE.

 

Roelof

 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From mehgcap at gmail.com  Sun Aug 22 20:49:03 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Sun, 22 Aug 2010 14:49:03 -0400
Subject: [Tutor] input problem
In-Reply-To: 
References: 
Message-ID: 

On 8/22/10, Roelof Wobben  wrote:
>
> Hello,
>
>
>
> I made this programm :
>
>
>
> def count_letters(n,a):
>     count = 0
>     for char in n:
>         if char == a:
>             count += 1
>     return count
>
> fruit=""
> letter=""
> fruit= input("Enter a sort of fruit: ")
> teller = input("Enter the character which must be counted: ")
> x=count_letters (fruit,letter)
> print "De letter", letter , "komt", x , "maal voor in het woord", fruit
>
>
>
> The problem is that I can't have the opportuntity for input anything.
Try replacing the two lines where you say "input" with "raw_input" and
see if that works.
>
> I use python 2.7 on a Win7 machine with as editor SPE.
>
>
>
> Roelof
>
>
>  		 	   		


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From airscorp at otenet.gr  Sun Aug 22 20:52:33 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Sun, 22 Aug 2010 21:52:33 +0300
Subject: [Tutor] input problem
In-Reply-To: 
References: 
Message-ID: <4C7171F1.3030504@otenet.gr>

On 08/22/2010 09:35 PM, Roelof Wobben wrote:
> Hello,
>
> I made this programm :
>
> def count_letters(n,a):
>     count = 0
>     for char in n:
>         if char == a:
>             count += 1
>     return count
> fruit=""
> letter=""
> fruit= input("Enter a sort of fruit: ")
> teller = input("Enter the character which must be counted: ")
> x=count_letters (fruit,letter)
> print "De letter", letter , "komt", x , "maal voor in het woord", fruit
>
> The problem is that I can't have the opportuntity for input anything.
> I use python 2.7 on a Win7 machine with as editor SPE.
>
> Roelof
>
You are using Python 2.x, so you should use raw_input() instead of input().

Note that in Python 3.x, raw_input() has been renamed to just input(), 
with the old 2.x input() gone.

Nick

From nblack3 at student.gsu.edu  Sun Aug 22 20:55:15 2010
From: nblack3 at student.gsu.edu (Nick)
Date: Sun, 22 Aug 2010 18:55:15 +0000
Subject: [Tutor] Writing a prime number program using upper bound of
 square root of n
Message-ID: 

"1 * 120 = 120
2 * 60 = 120
3 * 40 = 120
4 * 30 = 120
5 * 24 = 120
6 * 20 = 120
8 * 15 = 120
10 * 12 = 120
10.9545 * 10.9545 = 120
12 * 10 = 120  <=== already seen this one!


> Also I can write a program that
> tests whether the number is a factor of 2, 3, 5, 7, but I think
> you're trying to point to me that this is cumbersome and not
> necessary.

Sort of. I'm not suggest that you create lists of multiples of 2, 3, 5,
7 etc, and then cross off non-primes by checking to see if they are in
one of those lists. That truly would be cumbersome and slow. But the
two problems are similar. For simplicity, let's ignore 2 as a prime,
and only think about odd numbers:

(1) For each odd number N between 3 and (say) 1000, check if it is a
multiple of 3, 5, 7, 9, ... and IF SO, put it in the list "nonprimes".

versus:

(2) For each odd number N between 3 and (say) 1000, check if it is a
multiple of 3, 5, 7, 9, ... and IF NOT, put it in the list "primes".


See, they are very nearly the same problem. The tricky bits are:

* dealing with 2 is a special case;

* you don't want to exclude (say) 3 from being a prime because it is
divisible by 3; and

* you can stop testing at square-root of N.

Steven D'Aprano"

--------------------

Is there a way I can set my email program to insert the ">" symbol to mark what I'm replying to without manually doing it?

I get the picture now, that was a great example.  I wrote some code last night before going to bed that did what you were saying checking if it was divisible by 2, 3, 5, or 7.  I'm going to paste that.  
And so in my range function in this code could the upper bound be n*.5 instead of n+1 ?  is that how I would eliminate the checking of the repeated factors ?  I hope I'm not beating a dead horse guys.  thankis


primes = [2, 3, 5, 7]
def p(n):
    for i in range(3, n+1, 2):   
        if i % 3 == 0 or i % 5 == 0 or i % 7 == 0:
            pass
        else:
            primes.append(i)



From airscorp at otenet.gr  Sun Aug 22 21:05:27 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Sun, 22 Aug 2010 22:05:27 +0300
Subject: [Tutor] input problem
In-Reply-To: 
References: 
Message-ID: <4C7174F7.8040308@otenet.gr>

On 08/22/2010 09:35 PM, Roelof Wobben wrote:
> Hello,
>
> I made this programm :
>
> def count_letters(n,a):
>     count = 0
>     for char in n:
>         if char == a:
>             count += 1
>     return count
> fruit=""
> letter=""
> fruit= input("Enter a sort of fruit: ")
> teller = input("Enter the character which must be counted: ")
> x=count_letters (fruit,letter)
> print "De letter", letter , "komt", x , "maal voor in het woord", fruit
>
> The problem is that I can't have the opportuntity for input anything.
> I use python 2.7 on a Win7 machine with as editor SPE.
>
> Roelof
>
Also, you have a typo in your code (teller instead of letter) so fix 
that too :)

A couple more comments:
- You don't have to initialize fruit and letter. Doesn't make sense in 
this context.

- Although I can see you made the count_letters() function as an 
exercise, there is a build in method of string that accomplishes the 
same effect.
Try x=fruit.count(letter)

- Give a bit of thought about what would happen if someone enters a 
whole string instead of a character for letter. How should your program 
accommodate that?

Nick

From airscorp at otenet.gr  Sun Aug 22 21:20:13 2010
From: airscorp at otenet.gr (Nick Raptis)
Date: Sun, 22 Aug 2010 22:20:13 +0300
Subject: [Tutor] input problem
In-Reply-To: 
References: ,
	<4C7174F7.8040308@otenet.gr>
	
Message-ID: <4C71786D.50803@otenet.gr>

Please try and reply to the list instead of just me.

> raw_input did not the trick.
> fruit.count is the next exercise.
> Oke, I deleted the initialazion and change teller into letter.
>
> Roelof
>
>
Should be alright now.. Hmmm

Can you paste your exact code AND the error you're getting? As I 
understand you never get the prompts, right?

Nick

From alan.gauld at btinternet.com  Sun Aug 22 21:49:39 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 22 Aug 2010 20:49:39 +0100
Subject: [Tutor] Writing a prime number program using upper bound of
	square root of n
References: 
Message-ID: 


"Nick"  wrote

> Is there a way I can set my email program to insert
> the ">" symbol to mark what I'm replying to without manually doing 
> it?

Give us a clue. What is your email program?
You can do it in most programs but the method will be different in 
each!

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From denisg640 at gmail.com  Sun Aug 22 23:48:03 2010
From: denisg640 at gmail.com (Denis Gomes)
Date: Sun, 22 Aug 2010 17:48:03 -0400
Subject: [Tutor] Writing a prime number program using upper bound of
 square root of n
In-Reply-To: 
References: 
	
	
Message-ID: 

Nick,

   If you are using python 2.X, xrange(2,n) is just like range(2,n), the
xrange function is faster.  In python 3.X, they got rid of the slower range
function and renamed xrange to range.  The x in [x for x in xrange...] will
just go from 2 to the number n, but not including n.  This brings up a
possible issue.  You may or may not want to include that number n if n
itself is a prime number, therefore you should add 1 to n.  The code should
then go as follows.

def p(n):
     return [2,3,5,7]+[x for x in xrange(2,n+1) if x%2!=0 and x%3!=0 and
x%5!=0 and x%7!=0]

Denis


On Sun, Aug 22, 2010 at 5:10 PM, Nick  wrote:

>  I will play with this and see what happens.  One question though,  [x for
> x in xrange(2,n) ..  what is xrange or is this an error?
>  ------------------------------
> *From:* Denis Gomes [denisg640 at gmail.com]
> *Sent:* Sunday, August 22, 2010 4:07 PM
> *To:* Nick
> *Subject:* Re: [Tutor] Writing a prime number program using upper bound of
> square root of n
>
>  Hey Nick,
>
>    You can also try using list comprehensions to do the same thing.  You
> could do something as follows:
>
> def p(n):
>      return [2,3,5,7]+[x for x in xrange(2,n) if x%2!=0 and x%3!=0 and
> x%5!=0 and x%7!=0]
>
>    This is cleaner and probably faster. More Pythonic.
>
> Denis
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From steve at pearwood.info  Mon Aug 23 02:45:29 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 23 Aug 2010 10:45:29 +1000
Subject: [Tutor] Writing a prime number program using upper bound of
	square root of n
In-Reply-To: 
References: 
Message-ID: <201008231045.30610.steve@pearwood.info>

On Mon, 23 Aug 2010 04:55:15 am Nick wrote:

> Is there a way I can set my email program to insert the ">" symbol to
> mark what I'm replying to without manually doing it?

Depends on your mail client.

What are you using? Outlook?


> I get the picture now, that was a great example.  I wrote some code
> last night before going to bed that did what you were saying checking
> if it was divisible by 2, 3, 5, or 7.  I'm going to paste that. And
> so in my range function in this code could the upper bound be n*.5
> instead of n+1 ?


I think you mean n**0.5, not half n.


> primes = [2, 3, 5, 7]
> def p(n):
>     for i in range(3, n+1, 2):
>         if i % 3 == 0 or i % 5 == 0 or i % 7 == 0:
>             pass
>         else:
>             primes.append(i)


Some criticisms... 

(1) The name "p" for the function doesn't give much hint as to what it 
does. What does it mean? 

"print"?
"probability"?
"prime numbers less than n"?
"the first n primes"?
"is n a prime number"?
"prime factorization of n"?

You know the answer *now*, but will you remember in six months?


(2) Using global data is usually a bad thing. You should be able to call 
the function twice without breaking things, but in this case, if you 
call it twice, the primes list will have numbers added twice.


My suggestion is to move the list of primes into the function, rather 
than a global variable, and start with a function like this:


def primes(n):
    """Return a list of primes less than or equal to n."""
    if n < 2:
        return []  # No primes less than two, so we're done.
    results = [2]
    for i in xrange(3, n+1):
        if is_prime(i):
            results.append(i)
    return results


Now all you need is to write a function is_prime(n) that decides whether 
or not n is prime.


def is_prime(n):
    """Returns True if n is prime, otherwise False."""
    if n == 2:
        return True
    elif (n % 2 == 0) or (n < 2):
        return False
    # If we get here, we know that n is an odd number.


is_prime() is not complete. You have to write the rest.


(Note: this approach isn't the most efficient way of doing it, but it is 
probably the simplest. Once you have this working, you can think about 
ways to make it more efficient.)


-- 
Steven D'Aprano

From steve at pearwood.info  Mon Aug 23 02:53:03 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 23 Aug 2010 10:53:03 +1000
Subject: [Tutor] Writing a prime number program using upper bound of
	square root of n
In-Reply-To: 
References: 
	
	
Message-ID: <201008231053.04065.steve@pearwood.info>

On Mon, 23 Aug 2010 07:48:03 am Denis Gomes wrote:
> Nick,
>
>    If you are using python 2.X, xrange(2,n) is just like range(2,n),
> the xrange function is faster.  In python 3.X, they got rid of the
> slower range function and renamed xrange to range.

A slight over-simplification, but broadly correct.

> The x in [x for x 
> in xrange...] will just go from 2 to the number n, but not including
> n.  


I see people using list comprehensions like this:

[x for x in xrange(20)]  # for example

quite frequently. I've even done it myself. But it's silly and wasteful. 
That is exactly the same, only slower and more complicated, as:

list(xrange(20))

or

range(20)


Any time you write [x for x in SOMETHING] just drop the list 
comprehension and use SOMETHING on it's own. (You might need to call 
list(SOMETHING), but often you don't.)


-- 
Steven D'Aprano

From gregbair at gmail.com  Mon Aug 23 07:00:06 2010
From: gregbair at gmail.com (Greg Bair)
Date: Mon, 23 Aug 2010 01:00:06 -0400
Subject: [Tutor] continuous running of a method
Message-ID: <4C720056.3070309@gmail.com>

I have a method (I'll call it foo) that will either return None or an 
object depending on a random value generated.  What I want to happen is 
that if I call foo(), i.e, f = foo() and it returns None, to re-call it 
until it returns something else.  I would think this would be done with 
a while loop, but can't seem to get the details right.

Any help would be greatly appreciated.

Greg

From prologic at shortcircuit.net.au  Mon Aug 23 07:10:38 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Mon, 23 Aug 2010 15:10:38 +1000
Subject: [Tutor] continuous running of a method
In-Reply-To: <4C720056.3070309@gmail.com>
References: <4C720056.3070309@gmail.com>
Message-ID: 

On Mon, Aug 23, 2010 at 3:00 PM, Greg Bair  wrote:
> I have a method (I'll call it foo) that will either return None or an object
> depending on a random value generated. ?What I want to happen is that if I
> call foo(), i.e, f = foo() and it returns None, to re-call it until it
> returns something else. ?I would think this would be done with a while loop,
> but can't seem to get the details right.
>
> Any help would be greatly appreciated.

Quite simple really, and yes you are right. Use a while loop:

>>> from random import seed, random
>>> from time import time
>>> seed(time())
>>> def foo():
...     if 0.5 < random() < 0.6:
...             return True
...
>>> x = foo()
>>> while x is None:
...     x = foo()
...
>>> x
True
>>>

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"

From gregbair at gmail.com  Mon Aug 23 07:41:28 2010
From: gregbair at gmail.com (Greg Bair)
Date: Mon, 23 Aug 2010 01:41:28 -0400
Subject: [Tutor] continuous running of a method
In-Reply-To: 
References: <4C720056.3070309@gmail.com>
	
Message-ID: <4C720A08.4050607@gmail.com>

On 08/23/2010 01:10 AM, James Mills wrote:
> On Mon, Aug 23, 2010 at 3:00 PM, Greg Bair  wrote:
>    
>> I have a method (I'll call it foo) that will either return None or an object
>> depending on a random value generated.  What I want to happen is that if I
>> call foo(), i.e, f = foo() and it returns None, to re-call it until it
>> returns something else.  I would think this would be done with a while loop,
>> but can't seem to get the details right.
>>
>> Any help would be greatly appreciated.
>>      
> Quite simple really, and yes you are right. Use a while loop:
>
>    
>>>> from random import seed, random
>>>> from time import time
>>>> seed(time())
>>>> def foo():
>>>>          
> ...     if 0.5<  random()<  0.6:
> ...             return True
> ...
>    
>>>> x = foo()
>>>> while x is None:
>>>>          
> ...     x = foo()
> ...
>    
>>>> x
>>>>          
> True
>    
>>>>          
> cheers
> James
>
>    
I don't know why I didn't think of that.  Thanks.

From stefan_ml at behnel.de  Mon Aug 23 08:15:42 2010
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Mon, 23 Aug 2010 08:15:42 +0200
Subject: [Tutor] Elementtree and pretty printing in Python 2.7
In-Reply-To: 
References: <4C6E3386.9070903@googlemail.com>
	
Message-ID: 

Jerry Hill, 22.08.2010 16:51:
> Neither, as far as I know.  The XML you get is perfectly valid XML.


It's clearly well-formed, but I can't see it being valid without some kind 
of schema to validate it against.


Note that the OP has already written a follow-up but forgot to reply to the 
original mail.

Stefan


From justin.mailinglists at gmail.com  Mon Aug 23 14:42:28 2010
From: justin.mailinglists at gmail.com (Justin Ezequiel)
Date: Mon, 23 Aug 2010 20:42:28 +0800
Subject: [Tutor] OT: just venting
Message-ID: 

when some IS/IT--Management guy asks about " Eval() or compile on fly with object"
and you try to talk him out of that bad idea,
he replies, "...it's much more easier, but that's not the way i want it"

LOL. typical management.

From bgailer at gmail.com  Mon Aug 23 16:51:12 2010
From: bgailer at gmail.com (bob gailer)
Date: Mon, 23 Aug 2010 10:51:12 -0400
Subject: [Tutor] continuous running of a method
In-Reply-To: <4C720056.3070309@gmail.com>
References: <4C720056.3070309@gmail.com>
Message-ID: <4C728AE0.9090304@gmail.com>

  On 8/23/2010 1:00 AM, Greg Bair wrote:
> I have a method (I'll call it foo) that will either return None or an 
> object depending on a random value generated.  What I want to happen 
> is that if I call foo(), i.e, f = foo() and it returns None, to 
> re-call it until it returns something else.  I would think this would 
> be done with a while loop, but can't seem to get the details right.

Even though a while will work, you will have tied up the CPU until the 
loop terminates. This is never a good idea.

What is your higher level goal?

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From augdawg09 at gmail.com  Mon Aug 23 17:13:01 2010
From: augdawg09 at gmail.com (aug dawg)
Date: Mon, 23 Aug 2010 11:13:01 -0400
Subject: [Tutor] Adding all numbers in a file or list
Message-ID: 

Is there a command or module that I can use to add all the items in a list?
Alternatively, is there one I can use to add all the numbers in a file?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From sander.sweers at gmail.com  Mon Aug 23 17:21:43 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Mon, 23 Aug 2010 17:21:43 +0200
Subject: [Tutor] Adding all numbers in a file or list
In-Reply-To: 
References: 
Message-ID: 

On 23 August 2010 17:13, aug dawg  wrote:
> Is there a command or module that I can use to add all the items in a list?
> Alternatively, is there one I can use to add all the numbers in a file?

sum() is what you are looking for [1].

Greets
Sander

[1] http://docs.python.org/library/functions.html#sum

From karim.liateni at free.fr  Sun Aug 22 17:24:18 2010
From: karim.liateni at free.fr (Karim)
Date: Sun, 22 Aug 2010 17:24:18 +0200
Subject: [Tutor] Elementtree and pretty printing in Python 2.7
In-Reply-To: 
References: <4C6E3386.9070903@googlemail.com>
	
Message-ID: <4C714122.1000303@free.fr>


Hello Jerry,

Tricky solution using minidom (standard) Not tested:

import ElementTree
import minidom

def prettyPrint(element):
    txt = ElementTree.tostring(element)
    print minidom.parseString(txt).toprettyxml()


Regards
Karim

On 08/22/2010 04:51 PM, Jerry Hill wrote:
> On Fri, Aug 20, 2010 at 3:49 AM, Knacktus  wrote:
>    
>> Hi guys,
>>
>> I'm using Python 2.7 and the ElementTree standard-lib to write some xml.
>>
>> My output xml has no line breaks! So, it looks like that:
>>
>> 
>>
>> instead of something like this:
>>
>> 
>>     
>> 
>>
>> I'm aware of lxml which seems to have a pretty print option, but I would
>> prefer to use the standard-lib ElementTree which seems not to have a feature
>> like this.
>>
>> Do I miss something using the ElementTree-lib or is it bug?
>>      
> Neither, as far as I know.  The XML you get is perfectly valid XML.
> If you want to pretty print it, there's a recipe here:
> http://effbot.org/zone/element-lib.htm#prettyprint, but I don't think
> it's been included in the standard library yet.
>
>    


From sander.sweers at gmail.com  Mon Aug 23 17:33:10 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Mon, 23 Aug 2010 17:33:10 +0200
Subject: [Tutor] Adding all numbers in a file or list
In-Reply-To: 
References: 
	
	
Message-ID: 

On 23 August 2010 17:24, aug dawg  wrote:
> So it's sum(list_name) ?

Correct, but it is not limited to lists. Any itterable with
ints/floats will do, for example a tuple is also accepted.

Greets
Sander

PS: Please use reply to all so others on this list may benefit from
the questions/answers ;-)

From augdawg09 at gmail.com  Mon Aug 23 17:35:20 2010
From: augdawg09 at gmail.com (aug dawg)
Date: Mon, 23 Aug 2010 11:35:20 -0400
Subject: [Tutor] Adding all numbers in a file or list
In-Reply-To: 
References: 
	
	
	
Message-ID: 

Oh okay, sorry about that.

Thanks for the help!


On Mon, Aug 23, 2010 at 11:33 AM, Sander Sweers wrote:

> On 23 August 2010 17:24, aug dawg  wrote:
> > So it's sum(list_name) ?
>
> Correct, but it is not limited to lists. Any itterable with
> ints/floats will do, for example a tuple is also accepted.
>
> Greets
> Sander
>
> PS: Please use reply to all so others on this list may benefit from
> the questions/answers ;-)
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From matt.gregory at oregonstate.edu  Mon Aug 23 19:09:44 2010
From: matt.gregory at oregonstate.edu (Gregory, Matthew)
Date: Mon, 23 Aug 2010 10:09:44 -0700
Subject: [Tutor] design of Point class
In-Reply-To: <4C701AD9.3010209@gmail.com>
References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu>
	
	<1D673F86DDA00841A1216F04D1CE70D6426032DE61@EXCH2.nws.oregonstate.edu>
	<4C6F1F35.8040007@gmail.com> <4C701AD9.3010209@gmail.com>
Message-ID: <1D673F86DDA00841A1216F04D1CE70D6426032DEFA@EXCH2.nws.oregonstate.edu>

Bob Gailer wrote:
> class PointND(list):
>    def __init__(self, *a_list):
>      super(PointND, self).__init__(a_list)
> 
>    def getSet(ix):
>      def chklen(self):
>        if len(self) < ix + 1:
>          raise AttributeError
>      def get(self):
>        chklen(self)
>        return self[ix]
>      def set(self, value):
>        chklen(self)
>        self[ix] = value
>      return property(get, set)
> 
>    def set(self, ix):
>      return s
> 
>    x = getSet(0)
>    y = getSet(1)
>    z = getSet(2)
> 
[snip]

Bob and Hugo, thanks for enlightening me to class properties.  Obviously, I'm still on the learning curve.  Bob, I'm not seeing where the outer "def set(self, ix)" is used.  Am I missing something?

thanks, matt

From matt.gregory at oregonstate.edu  Mon Aug 23 19:55:16 2010
From: matt.gregory at oregonstate.edu (Gregory, Matthew)
Date: Mon, 23 Aug 2010 10:55:16 -0700
Subject: [Tutor] design of Point class
In-Reply-To: <201008211150.41362.steve@pearwood.info>
References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu>
	 <201008211150.41362.steve@pearwood.info>
Message-ID: <1D673F86DDA00841A1216F04D1CE70D6426032DF00@EXCH2.nws.oregonstate.edu>

Hi Steven,

Steven D'Aprano wrote:
> Every time you change the interface of inherited methods, you probably
> shouldn't.
> 
> Firstly, it probably breaks the Liskov Substitution Principle. The LSP
> says, essentially, if you subclass A to make B, you should be able to
> use a B anywhere you can use an A. (After all, instances of B are also
> instances of A.) Here's an example of what not to do:
> 
> class Vehicle:
>     def start(self, key):
>         ignition.insert(key)
>         ignition.turn()  # raises exception if out of fuel
>     def go(self, key):
>         self.start(key)
>         self.handbrake = 'off'
>         self.gear = 'drive'
>         self.accelerate()
> 
> class Truck(Vehicle):
>     # add other truck-like methods
> 
> class KeylessTruck(Truck):
>     # Some military vehicles are designed to not require keys.
>     # When on a battlefield, there's nothing worse than being
>     # unable to find the car keys!
>     def go(self):
>         self.start()
>         self.handbrake = 'off'
>         self.gear = 'drive'
>         self.accelerate()
>     def start(self):
>         ignition.turn()  # Actually a push button, but nevermind.
> 
> Can you see the problem? If the caller is expecting a Truck, and pass a
> key to the truck.go() method, they will get an exception if you give
> them a KeylessTruck instead of a Truck. This is a Bad Thing.
> 
> Secondly, changing method interfaces is not compatible with multiple
> inheritance and super(). You can probably get away with it if you stick
> to single inheritance, but it's still a bad thing to do.

Yes, this absolutely makes sense, but I'm less clear on how to solve it.  What I would think is that Vehicle shouldn't be defining start and this should be left up to a delegate within the subclasses?  Or am I showing my ignorance?

matt

matt

From bgailer at gmail.com  Mon Aug 23 20:05:19 2010
From: bgailer at gmail.com (bob gailer)
Date: Mon, 23 Aug 2010 14:05:19 -0400
Subject: [Tutor] design of Point class
In-Reply-To: <1D673F86DDA00841A1216F04D1CE70D6426032DEFA@EXCH2.nws.oregonstate.edu>
References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu>		<1D673F86DDA00841A1216F04D1CE70D6426032DE61@EXCH2.nws.oregonstate.edu>	<4C6F1F35.8040007@gmail.com>
	<4C701AD9.3010209@gmail.com>
	<1D673F86DDA00841A1216F04D1CE70D6426032DEFA@EXCH2.nws.oregonstate.edu>
Message-ID: <4C72B85F.3050300@gmail.com>

  On 8/23/2010 1:09 PM, Gregory, Matthew wrote:
> Bob Gailer wrote:
>> class PointND(list):
>>     def __init__(self, *a_list):
>>       super(PointND, self).__init__(a_list)
>>
>>     def getSet(ix):
>>       def chklen(self):
>>         if len(self)<  ix + 1:
>>           raise AttributeError
>>       def get(self):
>>         chklen(self)
>>         return self[ix]
>>       def set(self, value):
>>         chklen(self)
>>         self[ix] = value
>>       return property(get, set)
>>
>>     def set(self, ix):
>>       return s
>>
>>     x = getSet(0)
>>     y = getSet(1)
>>     z = getSet(2)
>>
> [snip]
>
> Bob and Hugo, thanks for enlightening me to class properties.  Obviously, I'm still on the learning curve.  Bob, I'm not seeing where the outer "def set(self, ix)" is used.  Am I missing something?

It should not be there! An accidental leftover.

But I notice other problems in my code which I am now attempting to fix. 
Back to you seen.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From matt.gregory at oregonstate.edu  Mon Aug 23 20:36:31 2010
From: matt.gregory at oregonstate.edu (Gregory, Matthew)
Date: Mon, 23 Aug 2010 11:36:31 -0700
Subject: [Tutor] design of Point class
In-Reply-To: <201008211124.29475.steve@pearwood.info>
References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu>
	<201008211124.29475.steve@pearwood.info>
Message-ID: <1D673F86DDA00841A1216F04D1CE70D6426032DF0A@EXCH2.nws.oregonstate.edu>

Steven D'Aprano wrote:
> It would surprise me greatly if numpy didn't already have such a class.

Yes, that is the first place I went looking, but I couldn't find such a class.  I found one project using numpy for geometry objects (geometry-simple, http://code.google.com/p/geometry-simple/), but it doesn't look to be fully fleshed out.

> Other than using numpy, probably the simplest solution is to just
> subclass tuple and give it named properties and whatever other methods
> you want. Here's a simple version:
> 
> class Point(tuple):
>     def __new__(cls, *args):
>         if len(args) == 1 and isinstance(args, tuple):
>             args = args[0]
>         for a in args:
>             try:
>                 a+0
>             except TypeError:
>                 raise TypeError('ordinate %s is not a number' % a)
>         return super(Point, cls).__new__(cls, args)
>     @property
>     def x(self):
>         return self[0]
>     @property
>     def y(self):
>         return self[1]
>     @property
>     def z(self):
>         return self[2]
>     def dist(self, other):
>         if isinstance(other, Point):
>             if len(self) == len(other):
>                 sq_diffs = sum((a-b)**2 for (a,b) in zip(self, other))
>                 return math.sqrt(sq_diffs)
>             else:
>                 raise ValueError('incompatible dimensions')
>         raise TypeError('not a Point')
>     def __repr__(self):
>         return "%s(%r)" % (self.__class__.__name__, tuple(self))
> 
> 
> class Point2D(Point):
>     def __init__(self, *args):
>         if len(self) != 2:
>             raise ValueError('need exactly two ordinates')
> 
> class Point3D(Point):
>     def __init__(self, *args):
>         if len(self) != 3:
>             raise ValueError('need exactly three ordinates')
> 
> These classes gives you:
> 
> * immutability;
> * the first three ordinates are named x, y and z;
> * any ordinate can be accessed by index with pt[3];
> * distance is only defined if the dimensions are the same;
> * nice string form;
> * input validation.

Thanks for this help.  I'm curious as to why immutability would be an advantage here (or maybe that's not what you're suggesting).  Typically, I would want to be able to do 'p.x = 10', so subclassing from a list (or numpy nd-array perhaps) would make more sense in my case?

Further, if I use setters, can I still use decorators as you've outlined or do I need to do use 'x = property(get, set)'.  These are all new language constructs that I haven't encountered yet.
  
> What it doesn't give you (yet!) is:
> 
> * distance between Points with different dimensions could easily be
>   defined just by removing the len() comparison. zip() will
>   automatically terminate at the shortest input, thus projecting the
>   higher-dimension point down to the lower-dimension point;
> * other distance methods, such as Manhattan distance;
> * a nice exception when you as for (say) pt.z from a 2-D point, instead
>   of raising IndexError;
> * point arithmetic (say, adding two points to get a third).

All good ideas, especially the different distance metrics to be defined in Point.  I'm working on implementing these.

> An alternative would be to have the named ordinates return 0 rather than
> raise an error. Something like this would work:
> 
>     @property
>     def y(self):
>         try: return self[1]
>         except IndexError: return 0

Is there an advantage to doing this?  Wouldn't this make one falsely assume that y was defined and equal to 0?

thanks, matt

From bgailer at gmail.com  Mon Aug 23 22:30:53 2010
From: bgailer at gmail.com (bob gailer)
Date: Mon, 23 Aug 2010 16:30:53 -0400
Subject: [Tutor] design of Point class
In-Reply-To: <4C72B85F.3050300@gmail.com>
References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu>		<1D673F86DDA00841A1216F04D1CE70D6426032DE61@EXCH2.nws.oregonstate.edu>	<4C6F1F35.8040007@gmail.com>
	<4C701AD9.3010209@gmail.com>
	<1D673F86DDA00841A1216F04D1CE70D6426032DEFA@EXCH2.nws.oregonstate.edu>
	<4C72B85F.3050300@gmail.com>
Message-ID: <4C72DA7D.30002@gmail.com>

  I am happier with this:

class PointND(list, object):

   def __init__(self, *a_list):
     super(PointND, self).__init__(a_list)
     self.maxIndex = len(self) - 1

   def getSet(ix, attName):
     msg = "'%s' object has no attribute '%s'" % (p.__class__.__name__, 
attName)
     def get(self):
       if self.maxIndex < ix:
         raise AttributeError, msg
       return self[ix]
     def set(self, value):
       if self.maxIndex < ix:
         raise AttributeError, msg
       self[ix] = value
     return property(get, set)

   x = getSet(0, 'x')
   y = getSet(1, 'y')
   z = getSet(2, 'z')

p = PointND(1,2,3)
assert (p.x, p.y, p.z) == (1, 2, 3)
p.x = 6; p.y = 9; p.z = 5
assert (p.x, p.y, p.z) == (6, 9, 5)

try:
   p = PointND(1,2)
   p.z = 3
except AttributeError:
   print 'Passed all tests'



-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From knotty at pearwood.info  Tue Aug 24 01:14:34 2010
From: knotty at pearwood.info (Steven)
Date: Tue, 24 Aug 2010 09:14:34 +1000
Subject: [Tutor] design of Point class
In-Reply-To: <1D673F86DDA00841A1216F04D1CE70D6426032DF0A@EXCH2.nws.oregonstate.edu>
References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu>
	<201008211124.29475.steve@pearwood.info>
	<1D673F86DDA00841A1216F04D1CE70D6426032DF0A@EXCH2.nws.oregonstate.edu>
Message-ID: <201008240914.34406.knotty@pearwood.info>

On Tue, 24 Aug 2010 04:36:31 am Gregory, Matthew wrote:

> I'm curious as to why immutability would be an
> advantage here (or maybe that's not what you're suggesting). 

Immutability is *always* an advantage for numeric types.

You can use immutable objects as keys in dicts.

You can (if you want) optimise the class so that it caches instances, 
thus saving memory.

You can be sure that invariants remain true. If an immutable instance 
has to be, say, positive, once you've checked that it is positive once 
you can be sure than no function can change it to be negative.

Look at the standard Python numeric types:

int, long, float, decimal.Decimal, fractions.Fraction 

They are all immutable. That should tell you something :)


> Typically, I would want to be able to do 'p.x = 10', so subclassing
> from a list (or numpy nd-array perhaps) would make more sense in my
> case?

Why do you want to modify points rather than create new ones as needed?

In any case, you should not subclass from list. It makes no sense to 
have pt.sort() or pt.pop() or various other list-like methods. 
Subclassing list is not the way. If you insist on mutable points, then 
something like:

class MutablePoint(object):
    def __init__(self, *ordinates):
        self._ordinates = list(ordinates)
    def __getitem__(self, i):
        return self._ordinates[i]
    def __setitem__(self, i, x):
        self._ordinates[i] = x
    

and so forth.



> Further, if I use setters, can I still use decorators as you've 
> outlined or do I need to do use 'x = property(get, set)'.  These are
> all new language constructs that I haven't encountered yet.

In Python 2.5, the only way to pass a setter and/or deleter to property 
is by using the form x = property(getter, setter, deleter). In Python 
2.6, properties gain methods that let you do this:

@property
def x(self): return self._x
@x.setter
def x(self, value): self._x = value
@x.deleter
def x(self): del self._x

Note that you MUST use the same name (x in the above example) for the 
getter, setter and deleter.

[...]
> > An alternative would be to have the named ordinates return 0 rather
> > than raise an error. Something like this would work:
> >
> >     @property
> >     def y(self):
> >         try: return self[1]
> >         except IndexError: return 0
>
> Is there an advantage to doing this?  Wouldn't this make one falsely
> assume that y was defined and equal to 0?

That's why it's an alternative.

If you decide that for your application it makes sense to treat 
coordinates on the XY plane as equivalent to coordinates in the XYZ 
space with Z=0, that's the simplest way to implement it.



-- 
Steven

From alan.gauld at btinternet.com  Tue Aug 24 01:45:36 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 24 Aug 2010 00:45:36 +0100
Subject: [Tutor] design of Point class
References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu>
	<201008211150.41362.steve@pearwood.info>
	<1D673F86DDA00841A1216F04D1CE70D6426032DF00@EXCH2.nws.oregonstate.edu>
Message-ID: 

"Gregory, Matthew"  wrote

>> class Vehicle:
>>     def start(self, key):
>>     def go(self, key):
>>
>> class Truck(Vehicle):
>>     # add other truck-like methods
>>
>> class KeylessTruck(Truck):
>>     # Some military vehicles are designed to not require keys.

Aside: Most modern high-end cars are keyless too! ;-)

>>     def go(self):
>>     def start(self):
>>
>> Can you see the problem? If the caller is expecting a Truck, and 
>> pass a
>> key to the truck.go() method, they will get an exception if you 
>> give
>> them a KeylessTruck instead of a Truck. This is a Bad Thing.

> Yes, this absolutely makes sense, but I'm less clear on how to solve 
> it.

There are several ways. Where you cannot change the original
interface - which wrongly assumed that all vehicles need keys - you
can introduce a default key parameter in which the method just ignores
the key and provides a default value(None?) if not provided.

Its messy and I'd definitely comment it to make it clear the key is
only to preserve the inherited interface but its probably the simplest 
option.

> What I would think is that Vehicle shouldn't be defining start

Defining start is probably OK (I can't think of a vehicle that doesn't
start in some way or other), but requiring a key is a mistake since
many vehicles don't use keys (think rickshaw or trolley bus etc)

> and this should be left up to a delegate within the subclasses?

I'm not sure a delegate would help here, especially if you want
to start a list of vehicles.

> Or am I showing my ignorance?

No, just uncovering the challenges of OO design. There is no
perfect solution, all models are approximations. Experience tends
to build better approximations but never perfect ones.

And sometimes breaking the LSP and working round the consequences
(try/except...) is the best - ie most pragmatic - solution. But that
should be the least favourite choice, try to maintain interfaces if 
possible.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From wallenpb at gmail.com  Tue Aug 24 05:35:02 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Mon, 23 Aug 2010 22:35:02 -0500
Subject: [Tutor] box drawing characters
In-Reply-To: 
References: 
	<4C6AA3F1.9090501@gmail.com>
	
	
	
	
	
	
Message-ID: 

On Wed, Aug 18, 2010 at 2:13 PM, Bill Allen  wrote:

>
> "Ewald Horn"  wrote in message
>> news:AANLkTinMKzyXBd0T7rLdyExHbANw1tNFZac5Z2gEEO14 at mail.gmail.com...
>>
>>  Hi Bill,
>>>
>>> have you given UniCurses a spin?
>>>
>>> See http://pyunicurses.sourceforge.net/ for more information.
>>>
>>>
>> This does look very interesting and the documentation seems to reflect a
> product that is quite complete.   I will definitely give it a try.
>
> Thanks,
> Bill
>
I did finally have a chance to give this a try.   Seems to work as it
should.   Users should read the installation instructions carefully,
particularly if installing on a Windows system as the additional PDCurses
library (pdcurses.dll) is also required.

-Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From memilanuk at gmail.com  Tue Aug 24 06:24:44 2010
From: memilanuk at gmail.com (M. Milanuk)
Date: Mon, 23 Aug 2010 21:24:44 -0700
Subject: [Tutor] box drawing characters
In-Reply-To: 
References: 	<4C6AA3F1.9090501@gmail.com>						
	
Message-ID: 

On 8/23/2010 8:35 PM, Bill Allen wrote:

> I did finally have a chance to give this a try.   Seems to work as it
> should.   Users should read the installation instructions carefully,
> particularly if installing on a Windows system as the additional
> PDCurses library (pdcurses.dll) is also required.  
> 

Bill,

This is of considerable interest to me as well.  I've downloaded the
various bits and will be tinkering with them as well as time allows.  If
you get a 'curses' application up and running on Windows any time soon,
I'd love to see it (screenshot), just as a proof-of-concept and/or
motivator ;)

Thanks,

Monte


From rwobben at hotmail.com  Tue Aug 24 10:47:46 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Tue, 24 Aug 2010 08:47:46 +0000
Subject: [Tutor] find() problem
Message-ID: 


Hello, 

 

I have this exercise :

 

Now rewrite the count_letters function so that instead of traversing the string, it repeatedly calls find (the version from Optional parameters), with the optional third parameter to locate new occurences of the letter being counted.

 

 

And I have this solution :

 

'''
def find(strng, ch, start, step=1):
index = start
while 0 <= index < len(strng):
if strng[index] == ch:
return index 
index += step
return -1

?
fruit=""
letter=""
fruit= raw_input("Enter a sort of fruit: ")
letter = raw_input("Enter the character which must be counted: ")
start=0 
aantal=0
while 0 <=start < len(fruit):
x=find (fruit,letter, start)
aantal +=1
start=x
print "De letter", letter , "komt", aantal , "maal voor in het woord", fruit

 

But it looks like it's in a indefinitive loop.

What went wrong here ?

 

I work with Python 2.7 on a Win7 machine.

 

Roelof

 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rwobben at hotmail.com  Tue Aug 24 16:23:03 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Tue, 24 Aug 2010 14:23:03 +0000
Subject: [Tutor] FW:  find() problem
In-Reply-To: 
References: ,
	,
	,
	,
	
Message-ID: 



 


From: rwobben at hotmail.com
To: oberoc at gmail.com
Subject: RE: [Tutor] find() problem
Date: Tue, 24 Aug 2010 12:25:24 +0000





 
> Date: Tue, 24 Aug 2010 08:09:54 -0400
> Subject: Re: [Tutor] find() problem
> From: oberoc at gmail.com
> To: rwobben at hotmail.com
> 
> > I will try again.
> >
> > def find(strng, ch, start, step=1):
> >     index = start
> The problem lies here, if you do a print on index, it never gets past
> the first index of the number, so
> your while loop below goes into an infinite loop.
> 
> For example:
> find('starfruit','t',0) <- First time will return 1
> find('starfruit','t',1) <- Still returns 1. Infinite loop
> 
> >     while 0 <= index < len(strng):
> >         if strng[index] == ch:
> >             return index
> >         index += step
> >     return -1
> >
> > fruit=""
> > letter=""
> > fruit= raw_input("Enter a sort of fruit: ")
> > letter = raw_input("Enter the character which must be counted: ")
> > start=0
> > aantal=0
> > while 0 <=start < len(fruit):
> >     x=find (fruit,letter, start)
> >     aantal +=1
> >     start=x
> > print "De letter", letter , "komt", aantal , "maal voor in het woord", fruit
> >
> 
> HTH,
> Tino

Hello, 
 
Your right. index get never past 1 
But in my opinion when something is found then x will be the place where the character is be found.
After that the counter is increased and start gets the value of x.
So start should change.
 
Now finding out why this is not happening.
 
But thanks for the help.
 
Roelof
 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From evert.rol at gmail.com  Tue Aug 24 17:03:07 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Tue, 24 Aug 2010 17:03:07 +0200
Subject: [Tutor] FW:  find() problem
In-Reply-To: 
References: ,
	,
	,
	,
	
	
Message-ID: <609DFFF1-6231-4D8F-A11B-C912F2C0A9A8@gmail.com>

> > > def find(strng, ch, start, step=1):
> > >     index = start
> > The problem lies here, if you do a print on index, it never gets past
> > the first index of the number, so
> > your while loop below goes into an infinite loop.
> > 
> > For example:
> > find('starfruit','t',0) <- First time will return 1
> > find('starfruit','t',1) <- Still returns 1. Infinite loop
> > 
> > >     while 0 <= index < len(strng):
> > >         if strng[index] == ch:
> > >             return index
> > >         index += step
> > >     return -1
> > >
> > > fruit=""
> > > letter=""
> > > fruit= raw_input("Enter a sort of fruit: ")
> > > letter = raw_input("Enter the character which must be counted: ")
> > > start=0
> > > aantal=0
> > > while 0 <=start < len(fruit):
> > >     x=find (fruit,letter, start)
> > >     aantal +=1
> > >     start=x
> > > print "De letter", letter , "komt", aantal , "maal voor in het woord", fruit
> > >
> > 
> > HTH,
> > Tino
> 
> Hello, 
>  
> Your right. index get never past 1 
> But in my opinion when something is found then x will be the place where the character is be found.
> After that the counter is increased and start gets the value of x.
> So start should change.
>  
> Now finding out why this is not happening.

You're including the previous found index; so it will just find the character at that same index again. You need to start the next search one index further down the word.


>  
> But thanks for the help.
>  
> Roelof
>  
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From T.Gkikopoulos at dundee.ac.uk  Tue Aug 24 16:54:19 2010
From: T.Gkikopoulos at dundee.ac.uk (Triantafyllos Gkikopoulos)
Date: Tue, 24 Aug 2010 15:54:19 +0100
Subject: [Tutor] Memory error for list creation
Message-ID: <4C73EB2B020000B300007C00@ia-gw-6.dundee.ac.uk>

Hi,
 
 I am looking for an alternative to:
 

************************************************************
Please consider the environment. Do you really need to print this email? 


 
>>> listx=[[[] for k in range(ds)] for j in range(i)]
 
as right now I am getting a Memory error on this, I tried this also on a cluster node with something like 16GB of memory and it didn't solve the problem.
 
listx is subsequently used:
 
>>> for x in something:
>>>      for y in x:
>>>                   listx[ii][y[1]].append(y[0])
>>>      ii+=1
 
 
 
 For reference values for k range from 300 -1200 and for i ~5000.
 
 
I though about using scipy/numpy array but then I wouldn't be able to have the flexibility of using append or not having to predefine the size.
 
 
 Thanks
 

The University of Dundee is a registered Scottish charity, No: SC015096
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rwobben at hotmail.com  Tue Aug 24 17:36:34 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Tue, 24 Aug 2010 15:36:34 +0000
Subject: [Tutor] FW:  find() problem
In-Reply-To: <609DFFF1-6231-4D8F-A11B-C912F2C0A9A8@gmail.com>
References: ,
	,
	,
	,
	
	,
	<609DFFF1-6231-4D8F-A11B-C912F2C0A9A8@gmail.com>
Message-ID: 



 

> Subject: Re: [Tutor] FW: find() problem
> From: evert.rol at gmail.com
> Date: Tue, 24 Aug 2010 17:03:07 +0200
> CC: tutor at python.org
> To: rwobben at hotmail.com
> 
> > > > def find(strng, ch, start, step=1):
> > > > index = start
> > > The problem lies here, if you do a print on index, it never gets past
> > > the first index of the number, so
> > > your while loop below goes into an infinite loop.
> > > 
> > > For example:
> > > find('starfruit','t',0) <- First time will return 1
> > > find('starfruit','t',1) <- Still returns 1. Infinite loop
> > > 
> > > > while 0 <= index < len(strng):
> > > > if strng[index] == ch:
> > > > return index
> > > > index += step
> > > > return -1
> > > >
> > > > fruit=""
> > > > letter=""
> > > > fruit= raw_input("Enter a sort of fruit: ")
> > > > letter = raw_input("Enter the character which must be counted: ")
> > > > start=0
> > > > aantal=0
> > > > while 0 <=start < len(fruit):
> > > > x=find (fruit,letter, start)
> > > > aantal +=1
> > > > start=x
> > > > print "De letter", letter , "komt", aantal , "maal voor in het woord", fruit
> > > >
> > > 
> > > HTH,
> > > Tino
> > 
> > Hello, 
> > 
> > Your right. index get never past 1 
> > But in my opinion when something is found then x will be the place where the character is be found.
> > After that the counter is increased and start gets the value of x.
> > So start should change.
> > 
> > Now finding out why this is not happening.
> 
> You're including the previous found index; so it will just find the character at that same index again. You need to start the next search one index further down the word.


 

Hello Evert.
 
Stupid mistake.
I change start=x to start=x+1 
But still it's not working properly.
 
I can see that on this example.
 
Fruit : banaan
letter : a
 
That a is being found at 2,4,5 which is correct but the programm don't end.
So there's another error somewhere,
 
Roelof

 

> 
> 
> > 
> > But thanks for the help.
> > 
> > Roelof
> > 
> > _______________________________________________
> > Tutor maillist - Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> 

 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From waynejwerner at gmail.com  Tue Aug 24 17:43:46 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Tue, 24 Aug 2010 10:43:46 -0500
Subject: [Tutor] Memory error for list creation
In-Reply-To: <4C73EB2B020000B300007C00@ia-gw-6.dundee.ac.uk>
References: <4C73EB2B020000B300007C00@ia-gw-6.dundee.ac.uk>
Message-ID: 

On Tue, Aug 24, 2010 at 9:54 AM, Triantafyllos Gkikopoulos <
T.Gkikopoulos at dundee.ac.uk> wrote:

>  Hi,
>
>  I am looking for an alternative to:
>
>
> ************************************************************
> Please consider the environment. Do you really need to print this email?
>
>
>
> >>> listx=[[[] for k in range(ds)] for j in range(i)]
>
> as right now I am getting a Memory error on this, I tried this also on a
> cluster node with something like 16GB of memory and it didn't solve the
> problem.
>
>

Unless you're using Python 3.x, use xrange - because here you're creating i
copies of the list 0..ds-1.

If you're trying to create a matrix this isn't the most effective way to get
it, but if you want a jagged array then using xrange should help your memory
consumption.


> listx is subsequently used:
>
> >>> for x in something:
> >>>      for y in x:
> >>>                   listx[ii][y[1]].append(y[0])
> >>>      ii+=1
>
>
>
>  For reference values for k range from 300 -1200 and for i ~5000.
>
>
> I though about using scipy/numpy array but then I wouldn't be able to have
> the flexibility of using append or not having to predefine the size.
>

If you need the ability that bad, you can convert the array to a list and
vice versa - of course those operations take time, so YMMV.

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From evert.rol at gmail.com  Tue Aug 24 17:44:22 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Tue, 24 Aug 2010 17:44:22 +0200
Subject: [Tutor] FW:  find() problem
In-Reply-To: 
References: ,
	,
	,
	,
	
	,
	<609DFFF1-6231-4D8F-A11B-C912F2C0A9A8@gmail.com>
	
Message-ID: <90F6B51A-C85A-467C-A30B-52ABBCB16921@gmail.com>

> > > > > def find(strng, ch, start, step=1):
> > > > > index = start
> > > > The problem lies here, if you do a print on index, it never gets past
> > > > the first index of the number, so
> > > > your while loop below goes into an infinite loop.
> > > > 
> > > > For example:
> > > > find('starfruit','t',0) <- First time will return 1
> > > > find('starfruit','t',1) <- Still returns 1. Infinite loop
> > > > 
> > > > > while 0 <= index < len(strng):
> > > > > if strng[index] == ch:
> > > > > return index
> > > > > index += step
> > > > > return -1

Why are you returning -1 here? 
-1 is a valid list index. 
And with your last change, it makes your main condition valid.


> > > > >
> > > > > fruit=""
> > > > > letter=""
> > > > > fruit= raw_input("Enter a sort of fruit: ")
> > > > > letter = raw_input("Enter the character which must be counted: ")
> > > > > start=0
> > > > > aantal=0
> > > > > while 0 <=start < len(fruit):
> > > > > x=find (fruit,letter, start)
> > > > > aantal +=1
> > > > > start=x
> > > > > print "De letter", letter , "komt", aantal , "maal voor in het woord", fruit
> > > > >
> > > > 
> > > > HTH,
> > > > Tino
> > > 
> > > Hello, 
> > > 
> > > Your right. index get never past 1 
> > > But in my opinion when something is found then x will be the place where the character is be found.
> > > After that the counter is increased and start gets the value of x.
> > > So start should change.
> > > 
> > > Now finding out why this is not happening.
> > 
> > You're including the previous found index; so it will just find the character at that same index again. You need to start the next search one index further down the word.
> 
>  
> Hello Evert.
>  
> Stupid mistake.
> I change start=x to start=x+1 
> But still it's not working properly.
>  
> I can see that on this example.
>  
> Fruit : banaan
> letter : a
>  
> That a is being found at 2,4,5 which is correct but the programm don't end.
> So there's another error somewhere,
>  
> Roelof
>  
> > 
> > 
> > > 
> > > But thanks for the help.
> > > 
> > > Roelof
> > > 
> > > _______________________________________________
> > > Tutor maillist - Tutor at python.org
> > > To unsubscribe or change subscription options:
> > > http://mail.python.org/mailman/listinfo/tutor
> > 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From nitin.162 at gmail.com  Tue Aug 24 18:23:10 2010
From: nitin.162 at gmail.com (Nitin Das)
Date: Tue, 24 Aug 2010 21:53:10 +0530
Subject: [Tutor] Adding all numbers in a file or list
In-Reply-To: 
References: 
	
	
	
	
Message-ID: 

alternatively you can use the lambda , reduce function for summing up all
the numbers in a list for e.g:-

lis = [1,2,3,4,5]

p = reduce(lambda x,y : x+y, lis)

p will have the value = 15.


--nitin

On Mon, Aug 23, 2010 at 9:05 PM, aug dawg  wrote:

> Oh okay, sorry about that.
>
> Thanks for the help!
>
>
>
> On Mon, Aug 23, 2010 at 11:33 AM, Sander Sweers wrote:
>
>> On 23 August 2010 17:24, aug dawg  wrote:
>> > So it's sum(list_name) ?
>>
>> Correct, but it is not limited to lists. Any itterable with
>> ints/floats will do, for example a tuple is also accepted.
>>
>> Greets
>> Sander
>>
>> PS: Please use reply to all so others on this list may benefit from
>> the questions/answers ;-)
>>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From anand.shashwat at gmail.com  Tue Aug 24 18:36:09 2010
From: anand.shashwat at gmail.com (Shashwat Anand)
Date: Tue, 24 Aug 2010 22:06:09 +0530
Subject: [Tutor] Adding all numbers in a file or list
In-Reply-To: 
References: 
	
	
	
	
	
Message-ID: 

On Tue, Aug 24, 2010 at 9:53 PM, Nitin Das  wrote:

> alternatively you can use the lambda , reduce function for summing up all
> the numbers in a list for e.g:-
>
> lis = [1,2,3,4,5]
>
> p = reduce(lambda x,y : x+y, lis)
>
> p will have the value = 15.
>

Another approach,

>>> lis = [1,2,3,4,5]
>>> reduce(operator.add, lis)
15

However use sum() for this, which is the most obvious way to do it.


>
> --nitin
>
> On Mon, Aug 23, 2010 at 9:05 PM, aug dawg  wrote:
>
>> Oh okay, sorry about that.
>>
>> Thanks for the help!
>>
>>
>>
>> On Mon, Aug 23, 2010 at 11:33 AM, Sander Sweers wrote:
>>
>>> On 23 August 2010 17:24, aug dawg  wrote:
>>> > So it's sum(list_name) ?
>>>
>>> Correct, but it is not limited to lists. Any itterable with
>>> ints/floats will do, for example a tuple is also accepted.
>>>
>>> Greets
>>> Sander
>>>
>>> PS: Please use reply to all so others on this list may benefit from
>>> the questions/answers ;-)
>>>
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
~l0nwlf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rwobben at hotmail.com  Tue Aug 24 18:32:51 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Tue, 24 Aug 2010 16:32:51 +0000
Subject: [Tutor] FW:  find() problem
In-Reply-To: <90F6B51A-C85A-467C-A30B-52ABBCB16921@gmail.com>
References: ,
	,
	,
	,
	
	,
	<609DFFF1-6231-4D8F-A11B-C912F2C0A9A8@gmail.com>
	,
	<90F6B51A-C85A-467C-A30B-52ABBCB16921@gmail.com>
Message-ID: 


Hello, 

 

I found it.

This one does the trick :

 

def find(strng, ch, start, step=1):
    index=start
    while 0 <= index < len(strng):
        if strng[index] == ch:
              return index 
        index += step
    return -2


fruit=""
letter=""
fruit= raw_input("Enter a sort of fruit: ")
letter = raw_input("Enter the character which must be counted: ")
index=1
aantal=0
while 0 <=index < len(fruit):
    x=find (fruit,letter, index)
    index=x+1
    if x<>-2 :
        aantal=aantal+1
print "De letter", letter , "komt", aantal , "maal voor in het woord", fruit

 

Roelof


 
> Subject: Re: [Tutor] FW: find() problem
> From: evert.rol at gmail.com
> Date: Tue, 24 Aug 2010 17:44:22 +0200
> CC: tutor at python.org
> To: rwobben at hotmail.com
> 
> > > > > > def find(strng, ch, start, step=1):
> > > > > > index = start
> > > > > The problem lies here, if you do a print on index, it never gets past
> > > > > the first index of the number, so
> > > > > your while loop below goes into an infinite loop.
> > > > > 
> > > > > For example:
> > > > > find('starfruit','t',0) <- First time will return 1
> > > > > find('starfruit','t',1) <- Still returns 1. Infinite loop
> > > > > 
> > > > > > while 0 <= index < len(strng):
> > > > > > if strng[index] == ch:
> > > > > > return index
> > > > > > index += step
> > > > > > return -1
> 
> Why are you returning -1 here? 
> -1 is a valid list index. 
> And with your last change, it makes your main condition valid.
> 
> 
> > > > > >
> > > > > > fruit=""
> > > > > > letter=""
> > > > > > fruit= raw_input("Enter a sort of fruit: ")
> > > > > > letter = raw_input("Enter the character which must be counted: ")
> > > > > > start=0
> > > > > > aantal=0
> > > > > > while 0 <=start < len(fruit):
> > > > > > x=find (fruit,letter, start)
> > > > > > aantal +=1
> > > > > > start=x
> > > > > > print "De letter", letter , "komt", aantal , "maal voor in het woord", fruit
> > > > > >
> > > > > 
> > > > > HTH,
> > > > > Tino
> > > > 
> > > > Hello, 
> > > > 
> > > > Your right. index get never past 1 
> > > > But in my opinion when something is found then x will be the place where the character is be found.
> > > > After that the counter is increased and start gets the value of x.
> > > > So start should change.
> > > > 
> > > > Now finding out why this is not happening.
> > > 
> > > You're including the previous found index; so it will just find the character at that same index again. You need to start the next search one index further down the word.
> > 
> > 
> > Hello Evert.
> > 
> > Stupid mistake.
> > I change start=x to start=x+1 
> > But still it's not working properly.
> > 
> > I can see that on this example.
> > 
> > Fruit : banaan
> > letter : a
> > 
> > That a is being found at 2,4,5 which is correct but the programm don't end.
> > So there's another error somewhere,
> > 
> > Roelof
> > 
> > > 
> > > 
> > > > 
> > > > But thanks for the help.
> > > > 
> > > > Roelof
> > > > 
> > > > _______________________________________________
> > > > Tutor maillist - Tutor at python.org
> > > > To unsubscribe or change subscription options:
> > > > http://mail.python.org/mailman/listinfo/tutor
> > > 
> > 
> > _______________________________________________
> > Tutor maillist - Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From evert.rol at gmail.com  Tue Aug 24 18:42:57 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Tue, 24 Aug 2010 18:42:57 +0200
Subject: [Tutor] FW:  find() problem
In-Reply-To: 
References: ,
	,
	,
	,
	
	,
	<609DFFF1-6231-4D8F-A11B-C912F2C0A9A8@gmail.com>
	,
	<90F6B51A-C85A-467C-A30B-52ABBCB16921@gmail.com>
	
Message-ID: 

> I found it.

Good.
Few generic comments nonetheless, just for the fun of it ;-).

> This one does the trick :
>  
> def find(strng, ch, start, step=1):
>     index=start
>     while 0 <= index < len(strng):
>         if strng[index] == ch:
>               return index 
>         index += step
>     return -2

You can actually use 'return index'. When you reach the end of the function, index == len(strng), which would be invalid in your main while condition, and the +1 would still keep it that way.
But read on if you want to keep the return -1 from the book.

> 
> fruit=""
> letter=""
> fruit= raw_input("Enter a sort of fruit: ")
> letter = raw_input("Enter the character which must be counted: ")
> index=1
> aantal=0
> while 0 <=index < len(fruit):
>     x=find (fruit,letter, index)

You can check for x == -1 here (if you have the old find() from the book), and then break out of the loop. Provided the book has already dealt with the break statement. If you use break, your while condition can simply be 'while True:'

>     index=x+1
>     if x<>-2 :

Don't use <>, but != instead. 
If you ever use Python 3, it doesn't work anymore: http://docs.python.org/release/3.0.1/whatsnew/3.0.html#removed-syntax


>         aantal=aantal+1
> print "De letter", letter , "komt", aantal , "maal voor in het woord", fruit
>  
> Roelof
> 
> > 
> > > > > > > def find(strng, ch, start, step=1):
> > > > > > > index = start
> > > > > > The problem lies here, if you do a print on index, it never gets past
> > > > > > the first index of the number, so
> > > > > > your while loop below goes into an infinite loop.
> > > > > > 
> > > > > > For example:
> > > > > > find('starfruit','t',0) <- First time will return 1
> > > > > > find('starfruit','t',1) <- Still returns 1. Infinite loop
> > > > > > 
> > > > > > > while 0 <= index < len(strng):
> > > > > > > if strng[index] == ch:
> > > > > > > return index
> > > > > > > index += step
> > > > > > > return -1
> > 
> > Why are you returning -1 here? 
> > -1 is a valid list index. 
> > And with your last change, it makes your main condition valid.
> > 
> > 
> > > > > > >
> > > > > > > fruit=""
> > > > > > > letter=""
> > > > > > > fruit= raw_input("Enter a sort of fruit: ")
> > > > > > > letter = raw_input("Enter the character which must be counted: ")
> > > > > > > start=0
> > > > > > > aantal=0
> > > > > > > while 0 <=start < len(fruit):
> > > > > > > x=find (fruit,letter, start)
> > > > > > > aantal +=1
> > > > > > > start=x
> > > > > > > print "De letter", letter , "komt", aantal , "maal voor in het woord", fruit
> > > > > > >
> > > > > > 
> > > > > > HTH,
> > > > > > Tino
> > > > > 
> > > > > Hello, 
> > > > > 
> > > > > Your right. index get never past 1 
> > > > > But in my opinion when something is found then x will be the place where the character is be found.
> > > > > After that the counter is increased and start gets the value of x.
> > > > > So start should change.
> > > > > 
> > > > > Now finding out why this is not happening.
> > > > 
> > > > You're including the previous found index; so it will just find the character at that same index again. You need to start the next search one index further down the word.
> > > 
> > > 
> > > Hello Evert.
> > > 
> > > Stupid mistake.
> > > I change start=x to start=x+1 
> > > But still it's not working properly.
> > > 
> > > I can see that on this example.
> > > 
> > > Fruit : banaan
> > > letter : a
> > > 
> > > That a is being found at 2,4,5 which is correct but the programm don't end.
> > > So there's another error somewhere,
> > > 
> > > Roelof
> > > 

From augdawg09 at gmail.com  Tue Aug 24 18:44:17 2010
From: augdawg09 at gmail.com (aug dawg)
Date: Tue, 24 Aug 2010 12:44:17 -0400
Subject: [Tutor] Databases in Python
Message-ID: 

The other day, I wrote a little database just to fiddle around, but when I
try to run it it says that it has an unexpected indent. From what I can
tell, it doesn't. Here's the code. I'm using SPE.

database = []
datafile = open('/home/~/the-db/data')
for line in datafile:
database.append(line)

while tf2 != True:
command = raw_input("Enter a command. >> ")

while tf != True:
if "add" in command:
adder = raw_input("What to add? >> ")
data_base.append(adder)
if "no more" in adder:
tf = True

if "read" in command:
print(database)
 if "search" in command:
searcher = raw_input("Enter term to search >> ")
if searcher in database:
# Figure this out.
 if "exit database" in command:
print "Bye!"
sys.exit()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From augdawg09 at gmail.com  Tue Aug 24 18:47:48 2010
From: augdawg09 at gmail.com (aug dawg)
Date: Tue, 24 Aug 2010 12:47:48 -0400
Subject: [Tutor] Databases in Python
In-Reply-To: 
References: 
Message-ID: 

It says that it's on line 25, on the print("Bye!").
Forgot to say that.


On Tue, Aug 24, 2010 at 12:44 PM, aug dawg  wrote:

> The other day, I wrote a little database just to fiddle around, but when I
> try to run it it says that it has an unexpected indent. From what I can
> tell, it doesn't. Here's the code. I'm using SPE.
>
> database = []
> datafile = open('/home/~/the-db/data')
> for line in datafile:
> database.append(line)
>
> while tf2 != True:
> command = raw_input("Enter a command. >> ")
>
> while tf != True:
>  if "add" in command:
> adder = raw_input("What to add? >> ")
>  data_base.append(adder)
> if "no more" in adder:
> tf = True
>
> if "read" in command:
> print(database)
>  if "search" in command:
> searcher = raw_input("Enter term to search >> ")
>  if searcher in database:
> # Figure this out.
>  if "exit database" in command:
> print "Bye!"
> sys.exit()
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From wprins at gmail.com  Tue Aug 24 19:01:43 2010
From: wprins at gmail.com (Walter Prins)
Date: Tue, 24 Aug 2010 18:01:43 +0100
Subject: [Tutor] Databases in Python
In-Reply-To: 
References: 
	
Message-ID: 

On 24 August 2010 17:47, aug dawg  wrote:

> if searcher in database:
>> # Figure this out.
>>  if "exit database" in command:
>> print "Bye!"
>> sys.exit()
>>
>
The first thing that caught my eye was the "#figure me out" line -- python
is expecting a statement there, a comment doesn't count.  You can use "pass"
for the time being.  (See
http://docs.python.org/reference/simple_stmts.html#grammar-token-pass_stmt)

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From pine508 at hotmail.com  Tue Aug 24 19:03:09 2010
From: pine508 at hotmail.com (Che M)
Date: Tue, 24 Aug 2010 13:03:09 -0400
Subject: [Tutor] Databases in Python
In-Reply-To: 
References: 
Message-ID: 


> The other day, I wrote a little database just to fiddle around, 
> but when I try to run it it says that it has an unexpected indent. 
> From what I can tell, it doesn't. Here's the code. I'm using SPE.

In the future, you should copy/paste error message you get into
your email.  This way it indicates to others the exact problem you
had.

One thing I noticed that is wrong in your code is this line:

if searcher in database:			# Figure this out.			The comment doesn't count as a line of interpretable code, so
you have nothing in this code block.  If you want to do that, use
pass, like:

if searcher in database:    pass			
    # Figure this out.			
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From marc.tompkins at gmail.com  Tue Aug 24 19:07:12 2010
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Tue, 24 Aug 2010 10:07:12 -0700
Subject: [Tutor] Databases in Python
In-Reply-To: 
References: 
	
Message-ID: 

On Tue, Aug 24, 2010 at 12:44 PM, aug dawg  wrote:

>  if searcher in database:
>> # Figure this out.
>>
>> You need some sort of actual Python statement there as a placeholder -
even just "print()".

-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From augdawg09 at gmail.com  Tue Aug 24 19:07:32 2010
From: augdawg09 at gmail.com (aug dawg)
Date: Tue, 24 Aug 2010 13:07:32 -0400
Subject: [Tutor] Databases in Python
In-Reply-To: 
References: 
	
	
Message-ID: 

Oh yeah. That was just a comment that I forgot to take out.


On Tue, Aug 24, 2010 at 1:01 PM, Walter Prins  wrote:

>
>
> On 24 August 2010 17:47, aug dawg  wrote:
>
>>  if searcher in database:
>>>  # Figure this out.
>>>  if "exit database" in command:
>>> print "Bye!"
>>> sys.exit()
>>>
>>
> The first thing that caught my eye was the "#figure me out" line -- python
> is expecting a statement there, a comment doesn't count.  You can use "pass"
> for the time being.  (See
> http://docs.python.org/reference/simple_stmts.html#grammar-token-pass_stmt
> )
>
> Walter
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From augdawg09 at gmail.com  Tue Aug 24 19:13:01 2010
From: augdawg09 at gmail.com (aug dawg)
Date: Tue, 24 Aug 2010 13:13:01 -0400
Subject: [Tutor] Databases in Python
In-Reply-To: 
References: 
	
	
Message-ID: 

It's not catching that, but I haven't gotten there with the bugs yet. One
more thing I can't figure out.

line 11
    select-db = raw_input("Which database to add to? >> ")
SyntaxError: can't assign to operator

I think it might be the >> at the end, but when I try it in the Python
interpreter, it works fine.

On Tue, Aug 24, 2010 at 1:07 PM, Marc Tompkins wrote:

> On Tue, Aug 24, 2010 at 12:44 PM, aug dawg  wrote:
>
>>  if searcher in database:
>>> # Figure this out.
>>>
>>> You need some sort of actual Python statement there as a placeholder -
> even just "print()".
>
> --
> www.fsrtechnologies.com
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From evert.rol at gmail.com  Tue Aug 24 19:18:45 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Tue, 24 Aug 2010 19:18:45 +0200
Subject: [Tutor] FW:  find() problem
In-Reply-To: 
References: ,
	,
	,
	,
	
	,
	<609DFFF1-6231-4D8F-A11B-C912F2C0A9A8@gmail.com>
	,
	<90F6B51A-C85A-467C-A30B-52ABBCB16921@gmail.com>
	,
	
	
	<9D54414F-B019-4146-BB8B-9DADBEEAA1D2@gmail.com>
	
Message-ID: <715B527A-4E82-41D3-AE5D-89D24BB7F6ED@gmail.com>

>>> I found it.
>> 
>> Good.
>> Few generic comments nonetheless, just for the fun of it ;-).
>> 
>>> This one does the trick :
>>> 
>>> def find(strng, ch, start, step=1):
>>> index=start
>>> while 0 <= index < len(strng):
>>> if strng[index] == ch:
>>> return index 
>>> index += step
>>> return -2
>> 
>> You can actually use 'return index'. When you reach the end of the function, index == len(strng), which would be invalid in your main while condition, and the +1 would still keep it that way.
>> But read on if you want to keep the return -1 from the book.
> 
> 
> Hello Evert, 
> 
> I don't get this.
> If you reach the end of the function , index==len(string) , then this loops end. 
> index does then have the value of the last found lettter. So why +1 would it keep it that way.

In your function, you keep adding step to index. If you won't find a match for a letter anymore, index reaches len(strng) and thus you break out of the while loop. Thus you continue to the return statement, and you return index (which equals len(strng) now).
Remember that len(strng) is the length of the string, but because Python's indices are zero-based, that does *not* equal the index of the last element: fruit[len(fruit)] will give an IndexError. So index does not have the value of the last found letter (actually, it never has, because it is an index, not a letter). 
In your main while loop, now, index == len(fruit), thus the condition fails. If you add one, you would get '0 <= len(fruit)+1 < len(fruit)', (index substituted with "len(fruit)"), which just as easily fails.

But if you don't get, better not use it; that generally leads to bugs.


> 
>> 
>>> 
>>> fruit=""
>>> letter=""
>>> fruit= raw_input("Enter a sort of fruit: ")
>>> letter = raw_input("Enter the character which must be counted: ")
>>> index=1
>>> aantal=0
>>> while 0 <=index < len(fruit):
>>> x=find (fruit,letter, index)
>> 
>> You can check for x == -1 here (if you have the old find() from the book), and then break out of the loop. Provided the book has already dealt with the break statement. If you use break, your while condition can simply be 'while True:'
>> 
>>> index=x+1
>>> if x<>-2 :
> 
> I don't thought about that but it is also a possibility.
> 
>> 
>> Don't use <>, but != instead. 
>> If you ever use Python 3, it doesn't work anymore: http://docs.python.org/release/3.0.1/whatsnew/3.0.html#removed-syntax
> 
> 
> Oke,  Point taken.
> 
> 




From karim.liateni at free.fr  Tue Aug 24 19:23:42 2010
From: karim.liateni at free.fr (Karim)
Date: Tue, 24 Aug 2010 19:23:42 +0200
Subject: [Tutor] Retriving previous user inputs in a gui
Message-ID: <4C74001E.8020909@free.fr>


Hello All,

I am figuring this out. I want a sort of file who store values entered 
previously in a gui.
Th e next time the user launch his gui in the same directory the gui 
load the previous
value from this file. Is there any modules in Tkinter for that? I 
suppose the file could
be in xml format or whatever? pyGTK solution is welcome too! Even if I 
prefered to use
the standard package.

Regards
Karim

From alan.gauld at btinternet.com  Tue Aug 24 19:53:41 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 24 Aug 2010 18:53:41 +0100
Subject: [Tutor] find() problem
References: 
Message-ID: 


"Roelof Wobben"  wrote

> But it looks like it's in a indefinitive loop.
>
> What went wrong here ?

When debugging this kind of thing insert a raw_input() statement
in the loop(to force a pause)  and just before it print out the key
variables. That way you can see what is happening and what is
not working the way you expect.

In this case you could print out the start, index and character 
values.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From christopher.henk at allisontransmission.com  Tue Aug 24 19:40:01 2010
From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com)
Date: Tue, 24 Aug 2010 13:40:01 -0400
Subject: [Tutor] Databases in Python
In-Reply-To: 
Message-ID: 

aug dawg wrote on 08/24/2010 01:13:01 PM:

> It's not catching that, but I haven't gotten there with the bugs yet. 
One more thing I can't figure out.
> 
> line 11
>     select-db = raw_input("Which database to add to? >> ")
> SyntaxError: can't assign to operator
> 
> I think it might be the >> at the end, but when I try it in the Python 
interpreter, it works fine.
> 
The error is triggered by your variable name.  You can't use a dash, 
Python is interpreting that as a minus sign.  You can use the underscore 
"_" instead.

more here:
http://www.pasteur.fr/formation/infobio/python/ch02s03.html
http://docs.python.org/reference/lexical_analysis.html#identifiers


Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From augdawg09 at gmail.com  Tue Aug 24 19:55:14 2010
From: augdawg09 at gmail.com (aug dawg)
Date: Tue, 24 Aug 2010 13:55:14 -0400
Subject: [Tutor] Databases in Python
In-Reply-To: 
References: 
	
Message-ID: 

Now it says that the variable adder is not defined. Does anyone know about
this?


On Tue, Aug 24, 2010 at 1:40 PM,
wrote:

>
> aug dawg wrote on 08/24/2010 01:13:01 PM:
>
>
> > It's not catching that, but I haven't gotten there with the bugs yet. One
> more thing I can't figure out.
>
> >
> > line 11
> >     select-db = raw_input("Which database to add to? >> ")
> > SyntaxError: can't assign to operator
> >
> > I think it might be the >> at the end, but when I try it in the Python
> interpreter, it works fine.
> >
> The error is triggered by your variable name.  You can't use a dash, Python
> is interpreting that as a minus sign.  You can use the underscore "_"
> instead.
>
> more here:
> http://www.pasteur.fr/formation/infobio/python/ch02s03.html
> http://docs.python.org/reference/lexical_analysis.html#identifiers
>
>
> Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From alan.gauld at btinternet.com  Tue Aug 24 19:57:25 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 24 Aug 2010 18:57:25 +0100
Subject: [Tutor] Databases in Python
References: 
	
Message-ID: 


"aug dawg"  wrote

>    select-db = raw_input("Which database to add to? >> ")
> SyntaxError: can't assign to operator
>
> I think it might be the >> at the end, but when I try it in the 
> Python
> interpreter, it works fine.

You have a minus sign in your variable name - at least thats
how Python sees it...


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From alan.gauld at btinternet.com  Tue Aug 24 20:03:20 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 24 Aug 2010 19:03:20 +0100
Subject: [Tutor] Retriving previous user inputs in a gui
References: <4C74001E.8020909@free.fr>
Message-ID: 

"Karim"  wrote

> I am figuring this out. I want a sort of file who store values 
> entered previously in a gui.

Thats easy enough - have you succeeded with this bit - check the
file with a text editor...

> Th e next time the user launch his gui in the same directory the gui 
> load the previous value from this file.

Again thats pretty easy, did you get this working - create the file
with a text editior?

> Is there any modules in Tkinter for that?

No, Tkinter is for building GUIs. Python core language includes
functions for reading and writing to files. Can you do this outside a 
GUI?

Write a program to read the users name and save it to a file.
Write a program to read the file and print the name it finds.
Write a program that says Hello  if it finds a name and asks for 
a name if it doesn't.

Now translate that to your GUI.

> suppose the file could
> be in xml format or whatever?

Yes, it could be in whatever. CSV, XML, ConfigParser or even plain 
text.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From karim.liateni at free.fr  Tue Aug 24 20:21:24 2010
From: karim.liateni at free.fr (Karim)
Date: Tue, 24 Aug 2010 20:21:24 +0200
Subject: [Tutor] Retriving previous user inputs in a gui
In-Reply-To: 
References: <4C74001E.8020909@free.fr> 
Message-ID: <4C740DA4.1030100@free.fr>


Thank you Alan for your answer.
In fact I want to do it in python format.
I want to source it (I will declare it each
input as a python variable).
I don't want to parse it. I just want to source it
like an external file in bash for example.
Is there a way to not use string evaluation. But really load it
  as python setting file inside python program.

PS: ConfigParser, hum very good , this could be of use for other part...

Karim

On 08/24/2010 08:03 PM, Alan Gauld wrote:
> "Karim"  wrote
>
>> I am figuring this out. I want a sort of file who store values 
>> entered previously in a gui.
>
> Thats easy enough - have you succeeded with this bit - check the
> file with a text editor...
>
>> Th e next time the user launch his gui in the same directory the gui 
>> load the previous value from this file.
>
> Again thats pretty easy, did you get this working - create the file
> with a text editior?
>
>> Is there any modules in Tkinter for that?
>
> No, Tkinter is for building GUIs. Python core language includes
> functions for reading and writing to files. Can you do this outside a 
> GUI?
>
> Write a program to read the users name and save it to a file.
> Write a program to read the file and print the name it finds.
> Write a program that says Hello  if it finds a name and asks for 
> a name if it doesn't.
>
> Now translate that to your GUI.
>
>> suppose the file could
>> be in xml format or whatever?
>
> Yes, it could be in whatever. CSV, XML, ConfigParser or even plain text.
>
> HTH,
>


From christopher.henk at allisontransmission.com  Tue Aug 24 20:24:22 2010
From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com)
Date: Tue, 24 Aug 2010 14:24:22 -0400
Subject: [Tutor] Databases in Python
In-Reply-To: 
Message-ID: 

aug dawg  wrote on 08/24/2010 01:55:14 PM:

> Now it says that the variable adder is not defined. Does anyone know 
about this?
> 
It is best if you send the full error message, it helps pinpoint the 
problem.
my copy of your code was:
database = []
datafile = open('/home/~/the-db/data')
for line in datafile:
database.append(line)

while tf2 != True:
command = raw_input("Enter a command. >> ")

while tf != True:
if "add" in command:
adder = raw_input("What to add? >> ")
data_base.append(adder)
if "no more" in adder:
tf = True

if "read" in command:
print(database)
if "search" in command:
searcher = raw_input("Enter term to search >> ")
if searcher in database:
# Figure this out.
if "exit database" in command:
print "Bye!"
sys.exit()

I am not sure what you typed in as your command or how your source was 
formatted (the tabs did not come through to me) so I cannot say for sure.
If "add" was not your command, adder does not get defined. 
My guess is that you typed in a different command so you skipped the 
assignment but are checking for "no more" in adder, or attempting to 
append adder.  This would trigger that error.  Did you get the "What to 
add? >>" message?

Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From karim.liateni at free.fr  Tue Aug 24 21:28:15 2010
From: karim.liateni at free.fr (Karim)
Date: Tue, 24 Aug 2010 21:28:15 +0200
Subject: [Tutor] Retriving previous user inputs in a gui
In-Reply-To: <4C740DA4.1030100@free.fr>
References: <4C74001E.8020909@free.fr> 
	<4C740DA4.1030100@free.fr>
Message-ID: <4C741D4F.6090107@free.fr>


Ok I find a solution (need to test it) that seems correct:

Suppose we have a python file mySourceFile with this setting:

EntryTextName = "myName"
EntryTextMail   = "myMail at gmail.com"

In the calling script or main python file we could define a function 
sourceConfigGui as follow:

def sourceConfigGui(mySourceFile,path_to_mysourcefile):

import mySourceFile
import sys
sys.path.append(path_to_mysourcefile)


If you have any other solution to source a external py file let me know.

Regards



On 08/24/2010 08:21 PM, Karim wrote:
>
> Thank you Alan for your answer.
> In fact I want to do it in python format.
> I want to source it (I will declare it each
> input as a python variable).
> I don't want to parse it. I just want to source it
> like an external file in bash for example.
> Is there a way to not use string evaluation. But really load it
>  as python setting file inside python program.
>
> PS: ConfigParser, hum very good , this could be of use for other part...
>
> Karim
>
> On 08/24/2010 08:03 PM, Alan Gauld wrote:
>> "Karim"  wrote
>>
>>> I am figuring this out. I want a sort of file who store values 
>>> entered previously in a gui.
>>
>> Thats easy enough - have you succeeded with this bit - check the
>> file with a text editor...
>>
>>> Th e next time the user launch his gui in the same directory the gui 
>>> load the previous value from this file.
>>
>> Again thats pretty easy, did you get this working - create the file
>> with a text editior?
>>
>>> Is there any modules in Tkinter for that?
>>
>> No, Tkinter is for building GUIs. Python core language includes
>> functions for reading and writing to files. Can you do this outside a 
>> GUI?
>>
>> Write a program to read the users name and save it to a file.
>> Write a program to read the file and print the name it finds.
>> Write a program that says Hello  if it finds a name and asks 
>> for a name if it doesn't.
>>
>> Now translate that to your GUI.
>>
>>> suppose the file could
>>> be in xml format or whatever?
>>
>> Yes, it could be in whatever. CSV, XML, ConfigParser or even plain text.
>>
>> HTH,
>>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From augdawg09 at gmail.com  Tue Aug 24 21:35:09 2010
From: augdawg09 at gmail.com (aug dawg)
Date: Tue, 24 Aug 2010 15:35:09 -0400
Subject: [Tutor] Databases in Python
In-Reply-To: 
References: 
	
Message-ID: 

Oh, stupid me forgot the error message. Well, for some odd reason it works
now, but there are still some issues. When I tried it just a few minutes
ago, it worked fine, it seemed to me.
If anyone have any tips, please let me know. Thanks everyone for the tips.

On Tue, Aug 24, 2010 at 2:24 PM,
wrote:

>
>
> aug dawg  wrote on 08/24/2010 01:55:14 PM:
>
>
> > Now it says that the variable adder is not defined. Does anyone know
> about this?
> >
> It is best if you send the full error message, it helps pinpoint the
> problem.
> my copy of your code was:
> database = []
> datafile = open('/home/~/the-db/data')
> for line in datafile:
> database.append(line)
>
> while tf2 != True:
> command = raw_input("Enter a command. >> ")
>
> while tf != True:
> if "add" in command:
> adder = raw_input("What to add? >> ")
> data_base.append(adder)
> if "no more" in adder:
> tf = True
>
> if "read" in command:
> print(database)
> if "search" in command:
> searcher = raw_input("Enter term to search >> ")
> if searcher in database:
> # Figure this out.
> if "exit database" in command:
> print "Bye!"
> sys.exit()
>
> I am not sure what you typed in as your command or how your source was
> formatted (the tabs did not come through to me) so I cannot say for sure.
> If "add" was not your command, adder does not get defined.
> My guess is that you typed in a different command so you skipped the
> assignment but are checking for "no more" in adder, or attempting to append
> adder.  This would trigger that error.  Did you get the "What to add? >>"
> message?
>
> Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From karim.liateni at free.fr  Tue Aug 24 21:38:32 2010
From: karim.liateni at free.fr (Karim)
Date: Tue, 24 Aug 2010 21:38:32 +0200
Subject: [Tutor] Retriving previous user inputs in a gui
In-Reply-To: <4C741D4F.6090107@free.fr>
References: <4C74001E.8020909@free.fr> 
	<4C740DA4.1030100@free.fr> <4C741D4F.6090107@free.fr>
Message-ID: <4C741FB8.2000701@free.fr>


Correction indents disappear (sic !) and lines are inverted (my mistake too)
  :o):

def sourceConfigGui(mySourceFile,path_to_mysourcefile):
         import sys
         sys.path.append(path_to_mysourcefile)
         import mySourceFile

Karim

On 08/24/2010 09:28 PM, Karim wrote:
>
> Ok I find a solution (need to test it) that seems correct:
>
> Suppose we have a python file mySourceFile with this setting:
>
> EntryTextName = "myName"
> EntryTextMail   = "myMail at gmail.com"
>
> In the calling script or main python file we could define a function 
> sourceConfigGui as follow:
>
> def sourceConfigGui(mySourceFile,path_to_mysourcefile):
>
> import mySourceFile
> import sys
> sys.path.append(path_to_mysourcefile)
>
>
> If you have any other solution to source a external py file let me know.
>
> Regards
>
>
>
> On 08/24/2010 08:21 PM, Karim wrote:
>>
>> Thank you Alan for your answer.
>> In fact I want to do it in python format.
>> I want to source it (I will declare it each
>> input as a python variable).
>> I don't want to parse it. I just want to source it
>> like an external file in bash for example.
>> Is there a way to not use string evaluation. But really load it
>>  as python setting file inside python program.
>>
>> PS: ConfigParser, hum very good , this could be of use for other part...
>>
>> Karim
>>
>> On 08/24/2010 08:03 PM, Alan Gauld wrote:
>>> "Karim"  wrote
>>>
>>>> I am figuring this out. I want a sort of file who store values 
>>>> entered previously in a gui.
>>>
>>> Thats easy enough - have you succeeded with this bit - check the
>>> file with a text editor...
>>>
>>>> Th e next time the user launch his gui in the same directory the 
>>>> gui load the previous value from this file.
>>>
>>> Again thats pretty easy, did you get this working - create the file
>>> with a text editior?
>>>
>>>> Is there any modules in Tkinter for that?
>>>
>>> No, Tkinter is for building GUIs. Python core language includes
>>> functions for reading and writing to files. Can you do this outside 
>>> a GUI?
>>>
>>> Write a program to read the users name and save it to a file.
>>> Write a program to read the file and print the name it finds.
>>> Write a program that says Hello  if it finds a name and asks 
>>> for a name if it doesn't.
>>>
>>> Now translate that to your GUI.
>>>
>>>> suppose the file could
>>>> be in xml format or whatever?
>>>
>>> Yes, it could be in whatever. CSV, XML, ConfigParser or even plain 
>>> text.
>>>
>>> HTH,
>>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From karim.liateni at free.fr  Tue Aug 24 22:03:18 2010
From: karim.liateni at free.fr (Karim)
Date: Tue, 24 Aug 2010 22:03:18 +0200
Subject: [Tutor] Retriving previous user inputs in a gui
In-Reply-To: <4C741FB8.2000701@free.fr>
References: <4C74001E.8020909@free.fr> 
	<4C740DA4.1030100@free.fr> <4C741D4F.6090107@free.fr>
	<4C741FB8.2000701@free.fr>
Message-ID: <4C742586.6040205@free.fr>


after tests I get the following:

 >>> import params
 >>> dir(params)
['EntryTextMail', 'EntryTextName', '__builtins__', '__doc__', 
'__file__', '__name__', '__package__']
 >>> params.EntryTextName
'myName'
 >>> params.EntryTextMail
'myMail at gmail.com'

But the file to import should have '.py' extension (.py) (if 
there is a way to avoid that
I wanted to use a 'hidden' file kind of ".config" , I can create a 
dynamical link to that
file with .py then import it and at last delete the symbolic 
link). I should do a small class
for that to reuse it.

At first I tried to access it as variables instead of using 
.variable. I learnt something here!

Regards
Karim

On 08/24/2010 09:38 PM, Karim wrote:
>
> Correction indents disappear (sic !) and lines are inverted (my 
> mistake too)
>  :o):
>
> def sourceConfigGui(mySourceFile,path_to_mysourcefile):
>         import sys
>         sys.path.append(path_to_mysourcefile)
>         import mySourceFile
>
> Karim
>
> On 08/24/2010 09:28 PM, Karim wrote:
>>
>> Ok I find a solution (need to test it) that seems correct:
>>
>> Suppose we have a python file mySourceFile with this setting:
>>
>> EntryTextName = "myName"
>> EntryTextMail   = "myMail at gmail.com"
>>
>> In the calling script or main python file we could define a function 
>> sourceConfigGui as follow:
>>
>> def sourceConfigGui(mySourceFile,path_to_mysourcefile):
>>
>> import mySourceFile
>> import sys
>> sys.path.append(path_to_mysourcefile)
>>
>>
>> If you have any other solution to source a external py file let me know.
>>
>> Regards
>>
>>
>>
>> On 08/24/2010 08:21 PM, Karim wrote:
>>>
>>> Thank you Alan for your answer.
>>> In fact I want to do it in python format.
>>> I want to source it (I will declare it each
>>> input as a python variable).
>>> I don't want to parse it. I just want to source it
>>> like an external file in bash for example.
>>> Is there a way to not use string evaluation. But really load it
>>>  as python setting file inside python program.
>>>
>>> PS: ConfigParser, hum very good , this could be of use for other 
>>> part...
>>>
>>> Karim
>>>
>>> On 08/24/2010 08:03 PM, Alan Gauld wrote:
>>>> "Karim"  wrote
>>>>
>>>>> I am figuring this out. I want a sort of file who store values 
>>>>> entered previously in a gui.
>>>>
>>>> Thats easy enough - have you succeeded with this bit - check the
>>>> file with a text editor...
>>>>
>>>>> Th e next time the user launch his gui in the same directory the 
>>>>> gui load the previous value from this file.
>>>>
>>>> Again thats pretty easy, did you get this working - create the file
>>>> with a text editior?
>>>>
>>>>> Is there any modules in Tkinter for that?
>>>>
>>>> No, Tkinter is for building GUIs. Python core language includes
>>>> functions for reading and writing to files. Can you do this outside 
>>>> a GUI?
>>>>
>>>> Write a program to read the users name and save it to a file.
>>>> Write a program to read the file and print the name it finds.
>>>> Write a program that says Hello  if it finds a name and asks 
>>>> for a name if it doesn't.
>>>>
>>>> Now translate that to your GUI.
>>>>
>>>>> suppose the file could
>>>>> be in xml format or whatever?
>>>>
>>>> Yes, it could be in whatever. CSV, XML, ConfigParser or even plain 
>>>> text.
>>>>
>>>> HTH,
>>>>
>>>
>>> _______________________________________________
>>> Tutor maillist  -  Tutor at python.org
>>> To unsubscribe or change subscription options:
>>> http://mail.python.org/mailman/listinfo/tutor
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From electroblog at gmail.com  Wed Aug 25 00:04:05 2010
From: electroblog at gmail.com (Joe Veldhuis)
Date: Tue, 24 Aug 2010 18:04:05 -0400
Subject: [Tutor] Controlling a device with ioctl's?
Message-ID: <20100824180405.2112f48e.electroblog@gmail.com>

Hello to all. I'm working on writing a tool that will control a piece of hardware using ioctl's on its device node. Specifically, I'm trying to configure and tune a DVB-S receiver on Linux.

Just for starters, I want to try opening the frontend and setting the LNB voltage. An example in C:

###
/* all the normal #include's omitted */
#include 

fd = open("/dev/dvb/adapter1/frontend0", O_RDWR)
r = ioctl (fd, FE_SET_VOLTAGE, SEC_VOLTAGE_18);
if (r == -1)
	perror ("ioctl FE_SET_VOLTAGE");
###

The relevant definitions in linux/dvb/frontend.h:

###
typedef enum fe_sec_voltage {
        SEC_VOLTAGE_13,
        SEC_VOLTAGE_18,
        SEC_VOLTAGE_OFF
} fe_sec_voltage_t;
...
#define FE_SET_VOLTAGE             _IO('o', 67)  /* fe_sec_voltage_t */
###

So, I wrote the following in Python:

###
import fcntl

fe_set_voltage = 67
sec_voltage_13 = 0
sec_voltage_18 = 1
sec_voltage_off = 2

fd = open("/dev/dvb/adapter1/frontend0", "wb")
fcntl.ioctl(fd, fe_set_voltage, sec_voltage_18)
###

This fails with "IOError: [Errno 95] Operation not supported".

Considering I'm not too good with C, and know absolutely /nothing/ about device drivers or kernel code, I'm certain I'm missing something simple and obvious. Anyone want to set me straight?

Thanks,
-Joe

From steve at pearwood.info  Wed Aug 25 00:16:05 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 25 Aug 2010 08:16:05 +1000
Subject: [Tutor] FW:  find() problem
In-Reply-To: <90F6B51A-C85A-467C-A30B-52ABBCB16921@gmail.com>
References: 
	
	<90F6B51A-C85A-467C-A30B-52ABBCB16921@gmail.com>
Message-ID: <201008250816.05345.steve@pearwood.info>

On Wed, 25 Aug 2010 01:44:22 am Evert Rol wrote:

> Why are you returning -1 here?
> -1 is a valid list index.

So? str.find() does the same thing. It guarantees to only return 0 or 
positive indexes if it finds the substring, and only returns -1 to 
indicate not found.


-- 
Steven D'Aprano

From sander.sweers at gmail.com  Wed Aug 25 00:21:12 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Wed, 25 Aug 2010 00:21:12 +0200
Subject: [Tutor] Controlling a device with ioctl's?
In-Reply-To: <20100824180405.2112f48e.electroblog@gmail.com>
References: <20100824180405.2112f48e.electroblog@gmail.com>
Message-ID: 

On 25 August 2010 00:04, Joe Veldhuis  wrote:
> Hello to all. I'm working on writing a tool that will control a piece of hardware using ioctl's on its device node. Specifically, I'm trying to configure and tune a DVB-S receiver on Linux.
>
> Just for starters, I want to try opening the frontend and setting the LNB voltage. An example in C:

Maybe you can use the python v4l2 bindings from [1] as example how to
use it for dvb. Not used it or have any experience with anything like
this but it might help..

Greets
Sander

[1] http://pypi.python.org/pypi/v4l2

From steve at pearwood.info  Wed Aug 25 00:22:26 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 25 Aug 2010 08:22:26 +1000
Subject: [Tutor] Adding all numbers in a file or list
In-Reply-To: 
References: 
	
	
Message-ID: <201008250822.26699.steve@pearwood.info>

On Wed, 25 Aug 2010 02:23:10 am Nitin Das wrote:
> alternatively you can use the lambda , reduce function for summing up
> all the numbers in a list for e.g:-
>
> lis = [1,2,3,4,5]
> p = reduce(lambda x,y : x+y, lis)
>
> p will have the value = 15.

Sure, you *can* do this, by why would you re-invent the wheel like that? 
As an exercise to teach reduce, sure, or as a demonstration of lambda, 
or if you have to support Python 2.2 or older (but that's like four 
versions out of date!). sum() is really the only sensible way to do it 
these days.

But if you insist on using reduce like that, it will probably be much 
faster to do this:

import operator
reduce(operator.add, lis)


particularly on the older versions where sum() isn't available.




-- 
Steven D'Aprano

From alan.gauld at btinternet.com  Wed Aug 25 01:57:54 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 25 Aug 2010 00:57:54 +0100
Subject: [Tutor] Retriving previous user inputs in a gui
References: <4C74001E.8020909@free.fr>
	<4C740DA4.1030100@free.fr>
	<4C741D4F.6090107@free.fr><4C741FB8.2000701@free.fr>
	<4C742586.6040205@free.fr>
Message-ID: 


"Karim"  wrote

> >>> import params
> >>> dir(params)
> ['EntryTextMail', 'EntryTextName', '__builtins__', '__doc__',

> But the file to import should have '.py' extension (.py) (if 
> there is a way to avoid that I wanted to use a 'hidden' file kind of 
> ".config" ,

You can exec a file and you can read the file into a string as a 
variable
then exec the string. BUT doing this is a huge security risk since 
anyone
can put any kind of arbitrary code in your config file and you will 
blindly
execute it. That's why config files are generally not executable code
but some kind of data format - it's much safer and very little extra 
work.

> At first I tried to access it as variables instead of using 
> .variable. I learnt something here!

Any time you import a module you need to use the module name
to access its contents - or use the from moo import * format, but
that introduces even more risk!

I strongly recommend that you think again and use a data format
config file.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From alan.gauld at btinternet.com  Wed Aug 25 02:02:01 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 25 Aug 2010 01:02:01 +0100
Subject: [Tutor] Controlling a device with ioctl's?
References: <20100824180405.2112f48e.electroblog@gmail.com>
Message-ID: 


"Joe Veldhuis"  wrote

>  control a piece of hardware using ioctl's on its device node. 

I've never tried this from Python but....

> #include 
> 
> fd = open("/dev/dvb/adapter1/frontend0", O_RDWR)

Notice the fd - that means file descriptor not file pointer.
So ioctl takes a file descriptor in C and I assume the same 
in Python.

> So, I wrote the following in Python:
> 
> 
> fd = open("/dev/dvb/adapter1/frontend0", "wb")

So I suspect this might need to be

import os
fd = os.open(.....)

But as I say I've never actually used ioctl in Python...

Alan G.



From augdawg09 at gmail.com  Wed Aug 25 02:55:34 2010
From: augdawg09 at gmail.com (aug dawg)
Date: Tue, 24 Aug 2010 20:55:34 -0400
Subject: [Tutor] Adding all numbers in a file or list
In-Reply-To: <201008250822.26699.steve@pearwood.info>
References: 
	
	
	<201008250822.26699.steve@pearwood.info>
Message-ID: 

Got it. Thanks everyone!


On Tue, Aug 24, 2010 at 6:22 PM, Steven D'Aprano wrote:

> On Wed, 25 Aug 2010 02:23:10 am Nitin Das wrote:
> > alternatively you can use the lambda , reduce function for summing up
> > all the numbers in a list for e.g:-
> >
> > lis = [1,2,3,4,5]
> > p = reduce(lambda x,y : x+y, lis)
> >
> > p will have the value = 15.
>
> Sure, you *can* do this, by why would you re-invent the wheel like that?
> As an exercise to teach reduce, sure, or as a demonstration of lambda,
> or if you have to support Python 2.2 or older (but that's like four
> versions out of date!). sum() is really the only sensible way to do it
> these days.
>
> But if you insist on using reduce like that, it will probably be much
> faster to do this:
>
> import operator
> reduce(operator.add, lis)
>
>
> particularly on the older versions where sum() isn't available.
>
>
>
>
> --
> Steven D'Aprano
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From electroblog at gmail.com  Wed Aug 25 04:59:26 2010
From: electroblog at gmail.com (Joe Veldhuis)
Date: Tue, 24 Aug 2010 22:59:26 -0400
Subject: [Tutor] Controlling a device with ioctl's?
In-Reply-To: 
References: <20100824180405.2112f48e.electroblog@gmail.com>
	
Message-ID: <20100824225926.b15391e0.electroblog@gmail.com>

A bit more work than I expected, but at least I have an idea what to do now. I'm working on writing a DVB binding based on the V4L2 binding you mentioned, currently about 30% complete - I can query the card's status! :)

Thanks for the help so far, might post again if I run into more trouble.

-Joe

On Wed, 25 Aug 2010 00:21:12 +0200
Sander Sweers  wrote:

> Maybe you can use the python v4l2 bindings from [1] as example how to
> use it for dvb. Not used it or have any experience with anything like
> this but it might help..
> 
> Greets
> Sander
> 
> [1] http://pypi.python.org/pypi/v4l2

From carter.danforth at gmail.com  Wed Aug 25 05:22:35 2010
From: carter.danforth at gmail.com (Carter Danforth)
Date: Tue, 24 Aug 2010 23:22:35 -0400
Subject: [Tutor] python: can't open file 'ex1.py' : [Errno 2] No such file
	or directory
Message-ID: 

Hi everyone,

This is my first email to group - I'm just starting to pick up Python and
I'm going through the exercises in Zed Shaw's "Learn Python the Hard Way"
ebook. Anyhow, I can't seem to be executing any files in terminal for some
reason, in this case the file ex1.py:

C:\Users\Carter Danforth\python ex1.py
python: can't open file 'ex1.py': [Errno 2] No such file or directory

ex1.py is located in "pythonpractice" on my desktop and I've updated the
modules, here's the output from sys.path:

['', 'C:\\Windows\\system32\\python27.zip', 'C:\\Users\\Carter
Danforth\\Desktop\\pythonpractice', 'C:\\Python27\\DLLs',
'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk', 'C:\\Python27',
'C:\\Python27\\lib\\site-packages']

And the environmental variable is set to have python on my path:

C:\Users\Carter Danforth>python
Python 2.7 (r27:82525, Jul  4 2010, 07:43:08) [MSC v.1500 64 bit (AMD64)] on
win
32
Type "help", "copyright", "credits" or "license" for more information.
>>>

I'm not sure why I keep getting this error message and why I'm not able to
execute any .py files. Any help would be great appreciated.

Carter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From karim.liateni at free.fr  Wed Aug 25 07:01:19 2010
From: karim.liateni at free.fr (Karim)
Date: Wed, 25 Aug 2010 07:01:19 +0200
Subject: [Tutor] Retriving previous user inputs in a gui
In-Reply-To: 
References: <4C74001E.8020909@free.fr> 
	<4C740DA4.1030100@free.fr> <4C741D4F.6090107@free.fr>
	<4C741FB8.2000701@free.fr> <4C742586.6040205@free.fr>
	
Message-ID: <4C74A39F.5080208@free.fr>


Thanks Alan for you advice!

Our environment is secured because the program is only for internal use.
We are supporting electronic designers. Nobody at work will write delete
codes inside (I hope). But, sure, I will check configParser module. I wanted
a straight forward config file because for TCL/TK GUI .config file is 
already
existing in TCL format that executing same syntax '*set myvar myvar_value*'.
I wanted to recreate this mechanism for python gui.

Thanks to point out this security issue.
Is there any equivalent to JAVACC in python (or lex yacc) to create grammary
for config or format file?

Regards
Karim

On 08/25/2010 01:57 AM, Alan Gauld wrote:
>
> "Karim"  wrote
>
>> >>> import params
>> >>> dir(params)
>> ['EntryTextMail', 'EntryTextName', '__builtins__', '__doc__',
>
>> But the file to import should have '.py' extension (.py) (if 
>> there is a way to avoid that I wanted to use a 'hidden' file kind of 
>> ".config" ,
>
> You can exec a file and you can read the file into a string as a variable
> then exec the string. BUT doing this is a huge security risk since anyone
> can put any kind of arbitrary code in your config file and you will 
> blindly
> execute it. That's why config files are generally not executable code
> but some kind of data format - it's much safer and very little extra 
> work.
>
>> At first I tried to access it as variables instead of using 
>> .variable. I learnt something here!
>
> Any time you import a module you need to use the module name
> to access its contents - or use the from moo import * format, but
> that introduces even more risk!
>
> I strongly recommend that you think again and use a data format
> config file.
>
> HTH,
>

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From karim.liateni at free.fr  Wed Aug 25 07:16:23 2010
From: karim.liateni at free.fr (Karim)
Date: Wed, 25 Aug 2010 07:16:23 +0200
Subject: [Tutor] python: can't open file 'ex1.py' : [Errno 2] No such
	file	or directory
In-Reply-To: 
References: 
Message-ID: <4C74A727.3050108@free.fr>


If it is in the sys.path you should import it: *import ex1*.
Then execute something like *ex1.main()* if you did a main().
Other python */ex.py* should world.

Regards
Karim

On 08/25/2010 05:22 AM, Carter Danforth wrote:
> Hi everyone,
>
> This is my first email to group - I'm just starting to pick up Python 
> and I'm going through the exercises in Zed Shaw's "Learn Python the 
> Hard Way" ebook. Anyhow, I can't seem to be executing any files in 
> terminal for some reason, in this case the file ex1.py:
>
> C:\Users\Carter Danforth\python ex1.py
> python: can't open file 'ex1.py': [Errno 2] No such file or directory
>
> ex1.py is located in "pythonpractice" on my desktop and I've updated 
> the modules, here's the output from sys.path:
>
> ['', 'C:\\Windows\\system32\\python27.zip', 'C:\\Users\\Carter 
> Danforth\\Desktop\\pythonpractice', 'C:\\Python27\\DLLs', 
> 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 
> 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 
> 'C:\\Python27\\lib\\site-packages']
>
> And the environmental variable is set to have python on my path:
>
> C:\Users\Carter Danforth>python
> Python 2.7 (r27:82525, Jul  4 2010, 07:43:08) [MSC v.1500 64 bit 
> (AMD64)] on win
> 32
> Type "help", "copyright", "credits" or "license" for more information.
> >>>
>
> I'm not sure why I keep getting this error message and why I'm not 
> able to execute any .py files. Any help would be great appreciated.
>
> Carter
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>    

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nitin.162 at gmail.com  Wed Aug 25 07:25:12 2010
From: nitin.162 at gmail.com (Nitin Das)
Date: Wed, 25 Aug 2010 10:55:12 +0530
Subject: [Tutor] continuous running of a method
In-Reply-To: <4C728AE0.9090304@gmail.com>
References: <4C720056.3070309@gmail.com>
	<4C728AE0.9090304@gmail.com>
Message-ID: 

The problem with this while loop is if your random value doesn't lie between
the mentioned range then ur 100% cpu would be utilized. The one thing u can
do is to sleep for some time lets say 0.5 sec after every while loop
iteration , in this case ur cpu utilization will go down.

--nitin

On Mon, Aug 23, 2010 at 8:21 PM, bob gailer  wrote:

>  On 8/23/2010 1:00 AM, Greg Bair wrote:
>
>> I have a method (I'll call it foo) that will either return None or an
>> object depending on a random value generated.  What I want to happen is that
>> if I call foo(), i.e, f = foo() and it returns None, to re-call it until it
>> returns something else.  I would think this would be done with a while loop,
>> but can't seem to get the details right.
>>
>
> Even though a while will work, you will have tied up the CPU until the loop
> terminates. This is never a good idea.
>
> What is your higher level goal?
>
>
> --
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From gregbair at gmail.com  Wed Aug 25 07:56:14 2010
From: gregbair at gmail.com (Greg Bair)
Date: Wed, 25 Aug 2010 01:56:14 -0400
Subject: [Tutor] continuous running of a method
In-Reply-To: 
References: <4C720056.3070309@gmail.com>	<4C728AE0.9090304@gmail.com>
	
Message-ID: <4C74B07E.3060803@gmail.com>

On 08/25/2010 01:25 AM, Nitin Das wrote:
> The problem with this while loop is if your random value doesn't lie 
> between the mentioned range then ur 100% cpu would be utilized. The 
> one thing u can do is to sleep for some time lets say 0.5 sec after 
> every while loop iteration , in this case ur cpu utilization will go down.
It's not that the value doesn't lie between the mentioned range.

What I'm doing is randomly fetching an item from a list of dicts 
(multi-dimensional ones from a JSON response) and accessing a value from 
it, but not every item has the key I'm looking for (can't change that).  
I suppose what I could do to not randomize every time is to iterate 
through the list and create a new list that only contains dicts that 
have that key, then get a random one from that.  I suppose that would be 
more efficient.

Any thoughts?

Greg
>
> --nitin
>
> On Mon, Aug 23, 2010 at 8:21 PM, bob gailer  > wrote:
>
>      On 8/23/2010 1:00 AM, Greg Bair wrote:
>
>         I have a method (I'll call it foo) that will either return
>         None or an object depending on a random value generated.  What
>         I want to happen is that if I call foo(), i.e, f = foo() and
>         it returns None, to re-call it until it returns something
>         else.  I would think this would be done with a while loop, but
>         can't seem to get the details right.
>
>
>     Even though a while will work, you will have tied up the CPU until
>     the loop terminates. This is never a good idea.
>
>     What is your higher level goal?
>
>


From hugo.yoshi at gmail.com  Wed Aug 25 09:12:46 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Wed, 25 Aug 2010 02:12:46 -0500
Subject: [Tutor] continuous running of a method
In-Reply-To: <4C74B07E.3060803@gmail.com>
References: <4C720056.3070309@gmail.com> <4C728AE0.9090304@gmail.com>
	
	<4C74B07E.3060803@gmail.com>
Message-ID: 

On Wed, Aug 25, 2010 at 12:56 AM, Greg Bair  wrote:
>
> It's not that the value doesn't lie between the mentioned range.
>
> What I'm doing is randomly fetching an item from a list of dicts
> (multi-dimensional ones from a JSON response) and accessing a value from it,
> but not every item has the key I'm looking for (can't change that). ?I
> suppose what I could do to not randomize every time is to iterate through
> the list and create a new list that only contains dicts that have that key,
> then get a random one from that. ?I suppose that would be more efficient.
>
> Any thoughts?
>

this sounds like a good idea. Either the filter() function or a list
comprehension can filter out the dicts you want easily.

My guess is the list comprehension is somewhat faster, but I could be
wrong. And it doesn't sound like performance is a very big deal here
anyway, so take your pick.

Hugo

From alan.gauld at btinternet.com  Wed Aug 25 09:21:31 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 25 Aug 2010 08:21:31 +0100
Subject: [Tutor] Retriving previous user inputs in a gui
References: <4C74001E.8020909@free.fr>
	<4C740DA4.1030100@free.fr>
	<4C741D4F.6090107@free.fr><4C741FB8.2000701@free.fr>
	<4C742586.6040205@free.fr>
	<4C74A39F.5080208@free.fr>
Message-ID: 


"Karim"  wrote

> Is there any equivalent to JAVACC in python (or lex yacc) to create 
> grammary
> for config or format file?

Thats kind of what ConfiogParser does - it gives you tools to 
read/write
a config file.

If you don't mind the data not being human readable you could also
use the shelve module which simulates a dictionary in a file.

There are lots of options.

Alan G.



From alan.gauld at btinternet.com  Wed Aug 25 09:30:59 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 25 Aug 2010 08:30:59 +0100
Subject: [Tutor] python: can't open file 'ex1.py' : [Errno 2] No such
	fileor directory
References: 
Message-ID: 


"Carter Danforth"  wrote

> Anyhow, I can't seem to be executing any files in terminal for some
> reason, in this case the file ex1.py:
>
> C:\Users\Carter Danforth\python ex1.py
> python: can't open file 'ex1.py': [Errno 2] No such file or 
> directory
>
> ex1.py is located in "pythonpractice" on my desktop and I've updated 
> the
> modules, here's the output from sys.path:

sys.path (and PYTHONPATH) only affect how imports work within
Python, they have no effect on Windows ability to find scripts.
To run a script you must do one of the following:

1) CD to the script folder and run Python from there as:
      > Python myscript.py

2) From anywhere execute Python as
    > python full\path\to\myscript.py

3) From anywhere execute myscript as
   > myscript.py

For 1,2 PATH must include the Python executable folder
For 3 the .py extension must be associated with the Python
executable and the folder containing myscript must be in PATH.

> I'm not sure why I keep getting this error message and why I'm not 
> able to
> execute any .py files. Any help would be great appreciated.

Windows needs to know where the file lives. You could have many
files called myscript.py in your file system. PYTHONPATH is used
only by Python and only for imports. PATH is used only for 
executables.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From fomcl at yahoo.com  Wed Aug 25 10:28:47 2010
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Wed, 25 Aug 2010 01:28:47 -0700 (PDT)
Subject: [Tutor] os.access unreliable?
Message-ID: <502129.63760.qm@web110716.mail.gq1.yahoo.com>

Hi,

Hi I'm using os.access to do a preliminary check to see if I have RW access, but 
it seems to be unreliable. In a dir for which I have only read access, os.access 
also says I have write access. This is under Windows 2000. I could of course use 
a try-except and catch the IOError, but I'd like to know why the code below 
isn;t working.

??? def isAcccessible(self):
??????? if os.access(self.path, os.R_OK) and os.access(self.path, os.W_OK):
??????????? return True
??????? else:
??????????? return False
?Cheers!!
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 mail at timgolden.me.uk  Wed Aug 25 10:53:08 2010
From: mail at timgolden.me.uk (Tim Golden)
Date: Wed, 25 Aug 2010 09:53:08 +0100
Subject: [Tutor] os.access unreliable?
In-Reply-To: <502129.63760.qm@web110716.mail.gq1.yahoo.com>
References: <502129.63760.qm@web110716.mail.gq1.yahoo.com>
Message-ID: <4C74D9F4.3030607@timgolden.me.uk>

On 25/08/2010 09:28, Albert-Jan Roskam wrote:
> Hi,
>
> Hi I'm using os.access to do a preliminary check to see if I have RW access, but
> it seems to be unreliable. In a dir for which I have only read access, os.access
> also says I have write access. This is under Windows 2000. I could of course use
> a try-except and catch the IOError, but I'd like to know why the code below
> isn;t working.
>
>      def isAcccessible(self):
>          if os.access(self.path, os.R_OK) and os.access(self.path, os.W_OK):
>              return True
>          else:
>              return False

os.access is effectively meaningless under Windows, especially
against directories. It only checks the read-only flag (which
doesn't mean anything for directories anyway).

There is a long-open issue here:

   http://bugs.python.org/issue2528

which I am half-minded to close although I could be
persuaded to pursue it if anyone were interested enough.
On the other hand, os.access checks are open to race-conditions
in any case, so you might simply be better off with a
try-except block as you suggest.

If you want more information I can explain further but unless you
want to dive into the Windows API and use AccessCheck -- which is
what that patch is doing -- then I suggest you use try-except

TJG

From rwobben at hotmail.com  Wed Aug 25 12:00:33 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Wed, 25 Aug 2010 10:00:33 +0000
Subject: [Tutor] why does this fail
Message-ID: 


Hello, 

 

I have this programm :

 

def remove_letter(letter, strng):
    """
      >>> remove_letter('a', 'apple')
      'pple'
      >>> remove_letter('a', 'banana')
      'bnn'
      >>> remove_letter('z', 'banana')
      'banana'
      >>> remove_letter('i', 'Mississippi')
      'Msssspp'
    """
    antwoord=""
    for letter in strng:
        print letter, strng
        if letter in strng:
            print "false"
        else:
            print "true"
    return antwoord

 

x=remove_letter('a', 'apple')
print x 

 

But now everything is false even a in apple.

 

What is here wrong ?

 

Roelof

 

 
  		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From steve at pearwood.info  Wed Aug 25 12:15:26 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 25 Aug 2010 20:15:26 +1000
Subject: [Tutor] os.access unreliable?
In-Reply-To: <502129.63760.qm@web110716.mail.gq1.yahoo.com>
References: <502129.63760.qm@web110716.mail.gq1.yahoo.com>
Message-ID: <201008252015.27806.steve@pearwood.info>

On Wed, 25 Aug 2010 06:28:47 pm Albert-Jan Roskam wrote:
> Hi,
>
> Hi I'm using os.access to do a preliminary check to see if I have RW
> access, but it seems to be unreliable. In a dir for which I have only
> read access, os.access also says I have write access. This is under
> Windows 2000. I could of course use a try-except and catch the
> IOError, but I'd like to know why the code below isn;t working.

As a general rule you need to use a try...except block anyway, otherwise 
your code is vulnerable to race conditions.

In a multi-tasking operating system (like just about all OSes these 
days, including Windows) there is no guarantee that just because you 
had permission to read the file now you will still have it in a 
millisecond when you try to open it. Or even that the file will still 
exist.

If you're writing a quick script for dealing with files, you can get 
away with taking the risk. But for more serious applications, there is 
no getting away from try...except.

In this case, the Fine Manual specifically warns that relying on 
os.access opens a potential security vulnerability:

http://docs.python.org/library/os.html#os.access

It also warns that os.access doesn't take into account network file 
sharing permissions.



-- 
Steven D'Aprano

From cwitts at compuscan.co.za  Wed Aug 25 12:27:39 2010
From: cwitts at compuscan.co.za (Christian Witts)
Date: Wed, 25 Aug 2010 12:27:39 +0200
Subject: [Tutor] why does this fail
In-Reply-To: 
References: 
Message-ID: <4C74F01B.7030502@compuscan.co.za>

On 25/08/2010 12:00, Roelof Wobben wrote:
> Hello,
>
> I have this programm :
>
> def remove_letter(letter, strng):
>     """
> >>> remove_letter('a', 'apple')
>       'pple'
> >>> remove_letter('a', 'banana')
>       'bnn'
> >>> remove_letter('z', 'banana')
>       'banana'
> >>> remove_letter('i', 'Mississippi')
>       'Msssspp'
>     """
>     antwoord=""
>     for letter in strng:
>         print letter, strng
>         if letter in strng:
>             print "false"
>         else:
>             print "true"
>     return antwoord
>
> x=remove_letter('a', 'apple')
> print x
>
> But now everything is false even a in apple.
>
> What is here wrong ?
>
> Roelof
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>    

You're rebinding the variable `letter`.
It is an input variable for your function but then you use it as the 
character store while iterating through your string variable `strng`.

What your control should look like would be more like

for character in strng:
     if letter == character:
         print 'false' # this should be true, it is a match just like in 
your example
     else:
         print 'true'

I'm assuming this function is just for learning purposes because there's 
a built-in string function you can use called replace and you'd use it 
as such `'apple'.replace('a', '')`.

PS: Once you've gotten it to work convert it to a list comprehension, 
they are incredibly useful and a great tool.

-- 
Kind Regards,
Christian Witts



From mail at timgolden.me.uk  Wed Aug 25 12:25:13 2010
From: mail at timgolden.me.uk (Tim Golden)
Date: Wed, 25 Aug 2010 11:25:13 +0100
Subject: [Tutor] os.access unreliable?
In-Reply-To: <201008252015.27806.steve@pearwood.info>
References: <502129.63760.qm@web110716.mail.gq1.yahoo.com>
	<201008252015.27806.steve@pearwood.info>
Message-ID: <4C74EF89.8050808@timgolden.me.uk>

On 25/08/2010 11:15, Steven D'Aprano wrote:
> It also warns that os.access doesn't take into account network file
> sharing permissions.

Heh. On Windows it doesn't take into account *any* file sharing
permissions :)

TJG

From steve at pearwood.info  Wed Aug 25 12:37:54 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 25 Aug 2010 20:37:54 +1000
Subject: [Tutor] continuous running of a method
In-Reply-To: 
References: <4C720056.3070309@gmail.com> <4C728AE0.9090304@gmail.com>
	
Message-ID: <201008252037.54541.steve@pearwood.info>

On Wed, 25 Aug 2010 03:25:12 pm Nitin Das wrote:
> The problem with this while loop is if your random value doesn't lie
> between the mentioned range then ur 100% cpu would be utilized. The
> one thing u can do is to sleep for some time lets say 0.5 sec after
> every while loop iteration , in this case ur cpu utilization will go
> down.

Pausing for half a second after each loop is WAY over-kill. Half a 
millisecond would be more appropriate, and even that is over-cautious.

Any modern multi-tasking operating system will ensure than a while loop 
doesn't kill your computer's responsiveness. A decent operating system 
will still remain responsive even at 100% CPU usage. Even Windows does 
that!

As I type this, I have about a dozen browser windows open, a music 
player playing, various text editors, a bittorrent client, and a Python 
interactive session running this:

>>> while 1:
...     pass 
...

(plus a whole heap more). Here are the top 4 entries according to top:

% CPU    Process name
96       python2.6
12       Xorg
 7       epiphany
 1       gtk-gnutella

Obviously this adds up to more that 100%. The load average is just 1.31. 
That's nothing -- a load less than 2 isn't even worth mentioning for a 
single CPU desktop machine. I don't start to worry until the load 
exceeds 3 or 4. I don't panic until it gets to 10 :)

This is perfectly normal, and nothing to be concerned about. I can 
barely notice any performance degradation despite the while loop. And 
of course Python itself remains responsive: type Ctrl-C kills it 
instantaneously.

You might need to worry this if you're writing in a low-level language 
like C, but in Python? Not unless you do something out of the ordinary, 
like setting the check interval to a ridiculously high value.

You can force Python to give even more time to threads by calling 
time.sleep(0). Other than that, you're not likely to need to care about 
this. Just write your code in the most straightforward way and leave 
the rest to Python and the OS.



-- 
Steven D'Aprano

From rwobben at hotmail.com  Wed Aug 25 12:49:05 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Wed, 25 Aug 2010 10:49:05 +0000
Subject: [Tutor] why does this fail
In-Reply-To: <4C74F01B.7030502@compuscan.co.za>
References: ,
	<4C74F01B.7030502@compuscan.co.za>
Message-ID: 



 

> Date: Wed, 25 Aug 2010 12:27:39 +0200
> From: cwitts at compuscan.co.za
> To: tutor at python.org
> Subject: Re: [Tutor] why does this fail
> 
> On 25/08/2010 12:00, Roelof Wobben wrote:
> > Hello,
> >
> > I have this programm :
> >
> > def remove_letter(letter, strng):
> > """
> > >>> remove_letter('a', 'apple')
> > 'pple'
> > >>> remove_letter('a', 'banana')
> > 'bnn'
> > >>> remove_letter('z', 'banana')
> > 'banana'
> > >>> remove_letter('i', 'Mississippi')
> > 'Msssspp'
> > """
> > antwoord=""
> > for letter in strng:
> > print letter, strng
> > if letter in strng:
> > print "false"
> > else:
> > print "true"
> > return antwoord
> >
> > x=remove_letter('a', 'apple')
> > print x
> >
> > But now everything is false even a in apple.
> >
> > What is here wrong ?
> >
> > Roelof
> >
> >
> > _______________________________________________
> > Tutor maillist - Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> > 
> 
> You're rebinding the variable `letter`.
> It is an input variable for your function but then you use it as the 
> character store while iterating through your string variable `strng`.
> 
> What your control should look like would be more like
> 
> for character in strng:
> if letter == character:
> print 'false' # this should be true, it is a match just like in 
> your example
> else:
> print 'true'
> 
> I'm assuming this function is just for learning purposes because there's 
> a built-in string function you can use called replace and you'd use it 
> as such `'apple'.replace('a', '')`.
> 
> PS: Once you've gotten it to work convert it to a list comprehension, 
> they are incredibly useful and a great tool.
> 
> -- 
> Kind Regards,
> Christian Witts
> 
> 
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


Hello Christian.
 
It's for learning purposed but I forget that de module string has built in functions.
Thank you for remainding it to me.
 
list comprehistion is q few chapters later in the book so I don't try yet.
 
Roelof
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From fomcl at yahoo.com  Wed Aug 25 17:44:02 2010
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Wed, 25 Aug 2010 08:44:02 -0700 (PDT)
Subject: [Tutor] os.access unreliable?
In-Reply-To: <4C74EF89.8050808@timgolden.me.uk>
References: <502129.63760.qm@web110716.mail.gq1.yahoo.com>
	<201008252015.27806.steve@pearwood.info>
	<4C74EF89.8050808@timgolden.me.uk>
Message-ID: <237262.89368.qm@web110711.mail.gq1.yahoo.com>

Hi Tim and Steven,

Thanks a lot for your very useful replies!
?Cheers!!
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?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 




________________________________
From: Tim Golden 
Cc: tutor at python.org
Sent: Wed, August 25, 2010 12:25:13 PM
Subject: Re: [Tutor] os.access unreliable?

On 25/08/2010 11:15, Steven D'Aprano wrote:
> It also warns that os.access doesn't take into account network file
> sharing permissions.

Heh. On Windows it doesn't take into account *any* file sharing
permissions :)

TJG
_______________________________________________
Tutor maillist? -? Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From asmosis.asterix at gmail.com  Wed Aug 25 18:56:47 2010
From: asmosis.asterix at gmail.com (Daniel)
Date: Wed, 25 Aug 2010 19:56:47 +0300
Subject: [Tutor] Function object
Message-ID: 

Hello again, seems like in my journey to learn Python I have stumbled into
another problem regarding understanding a concept- function object. As I
said, I do not understand what a function object is, what it does, and what
can I do with it? I'm currently reading Think python, but the book is not
clear for me. Python is my first programming language.
Please, can you give me some examples and if it is possible can you explain
in a more beginner orientated way? also if someone has a minute I'm
available on google chat, if it's more convenient to explain this way.



Thanks so much and I hope I didn't disturb anyone with my questions. I know
you probably get this question and others a lot. But please understand, my
goal with this email is not to make you angry or something like that, I
really like programming and what to learn it but as a beginner I find some
concepts hard to understand just by reading.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From emile at fenx.com  Wed Aug 25 19:56:27 2010
From: emile at fenx.com (Emile van Sebille)
Date: Wed, 25 Aug 2010 10:56:27 -0700
Subject: [Tutor] Function object
In-Reply-To: 
References: 
Message-ID: 

On 8/25/2010 9:56 AM Daniel said...
> Hello again, seems like in my journey to learn Python I have stumbled into
> another problem regarding understanding a concept- function object. As I
> said, I do not understand what a function object is, what it does, and what
> can I do with it? I'm currently reading Think python, but the book is not
> clear for me. Python is my first programming language.
> Please, can you give me some examples and if it is possible can you explain
> in a more beginner orientated way?

Generally speaking, everything in python is an object.  As such, objects 
have methods and attributes.  At a certain level for certain projects, 
manipulating code objects helps solve problems.

Here's a simple example.

ActivePython 2.6.1.1 (ActiveState Software Inc.) based on
Python 2.6.1 (r261:67515, Dec  5 2008, 13:58:38) [MSC v.1500 32 bit 
(Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> def test(ii): print "my name is %s" % ii.func_name
...
 >>> def test1(ii): print "my name is %s" % ii.func_name
...
 >>> def test2(ii): print "double ii is %s-%s" % (ii,ii)
...
 >>> for funcobj in (test1,test2): funcobj('spam')
...
single ii is spam
double ii is spam-spam
 >>>for funcobj in (test1,test2): test(funcobj)
...
my name is test1
my name is test2

Once defined, code is an object.  try dir(test) on the above.

HTH,

Emile


From emile at fenx.com  Wed Aug 25 20:05:23 2010
From: emile at fenx.com (Emile van Sebille)
Date: Wed, 25 Aug 2010 11:05:23 -0700
Subject: [Tutor] Function object
In-Reply-To: 
References: 
	
Message-ID: 

On 8/25/2010 10:56 AM Emile van Sebille said...
>  >>> def test1(ii): print "my name is %s" % ii.func_name
> ...

Oops -- my bad editing  s/b or once was:

def test1(ii): print "single ii is %s" % ii



From gregbair at gmail.com  Wed Aug 25 20:18:28 2010
From: gregbair at gmail.com (Greg Bair)
Date: Wed, 25 Aug 2010 14:18:28 -0400
Subject: [Tutor] why does this fail
In-Reply-To: 
References: 
Message-ID: <4C755E74.2060003@gmail.com>

On 08/25/2010 06:00 AM, Roelof Wobben wrote:
> 
> Hello, 
> 
>  
> 
> I have this programm :
> 
>  
> 
> def remove_letter(letter, strng):
>     """
>       >>> remove_letter('a', 'apple')
>       'pple'
>       >>> remove_letter('a', 'banana')
>       'bnn'
>       >>> remove_letter('z', 'banana')
>       'banana'
>       >>> remove_letter('i', 'Mississippi')
>       'Msssspp'
>     """
>     antwoord=""
>     for letter in strng:
>         print letter, strng
>         if letter in strng:
>             print "false"
>         else:
>             print "true"
>     return antwoord
> 
>  
> 
> x=remove_letter('a', 'apple')
> print x 
> 
>  
> 
> But now everything is false even a in apple.
> 
>  
> 
> What is here wrong ?
> 
I'm assuming what you really want is :

if letter in strng:
    print "true"
else:
    print "false"




From alan.gauld at btinternet.com  Wed Aug 25 20:29:49 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 25 Aug 2010 19:29:49 +0100
Subject: [Tutor] why does this fail
References: 
Message-ID: 


"Roelof Wobben"  wrote

######################
def remove_letter(letter, strng):
    antwoord=""
    for letter in strng:
        print letter, strng
        if letter in strng:
            print "false"
        else:
            print "true"
    return antwoord
######################

Several issues:

1) You never use antwoord so it alweays returns ""
2) you print false when the letter IS in the string
3) You use letter as an input parameter but then overwrite it in the 
for loop.
4) your if test would be better written as

print (letter in string)

(The parens aren't necessary but I think make it clearer that
we are printing the evaluation of an expression not just a string with
missing quotes...)

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From alan.gauld at btinternet.com  Wed Aug 25 20:32:59 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 25 Aug 2010 19:32:59 +0100
Subject: [Tutor] why does this fail
References: ,
	<4C74F01B.7030502@compuscan.co.za>
	
Message-ID: 


"Roelof Wobben"  wrote

> It's for learning purposed but I forget that de module string 
> has built in functions.Thank you for remainding it to me.

Its not the string module that Christian is referring to, 
its the methods of string objects - different things:


You can do:

import string
string.replace(aString, aChr, another)  # use string module

But its better to do

aString.replace(aChr, another)   # use string method

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From alan.gauld at btinternet.com  Wed Aug 25 20:44:05 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 25 Aug 2010 19:44:05 +0100
Subject: [Tutor] Function object
References: 
Message-ID: 


"Daniel"  wrote

> another problem regarding understanding a concept- function object. 
> As I
> said, I do not understand what a function object is, what it does, 
> and what
> can I do with it?

You are actually using them all the time.
Every function in Python is a function object.
You can execute the function by putting parenthesesc after its 
name(filled
with any required arguments)

def foo(): return None

defines a function object called foo that does nothing but return 
None.

We can rewrite that using the lambda operator which returns function
objects with no name:

foo = lambda : None

This assigns an anonymous function object to a variable foo - thus 
giving
it a name, just like any other variable.

In both cases we can now call the function with:

foo()

The advantage of treating functions as objects is that we can store 
them
and then call them later. This is the basis of event driven 
programming
and GUIs. It also allows us to easily build reconfigurable dynamic 
logic
into applications - just by changing the order in which functions are 
called.

It also allows us to create functions which return functions as their 
output,
but this is getting into deeper water, so I'll ignore that for now! 
:-)

You will find a slightly different explanation in the Functional 
Programming
topic of my tutorial

HTH
-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From nitinchandra1 at gmail.com  Wed Aug 25 21:40:33 2010
From: nitinchandra1 at gmail.com (nitin chandra)
Date: Thu, 26 Aug 2010 01:10:33 +0530
Subject: [Tutor] Need URGENT support ... PL
Message-ID: 

Hi all,

I have been getting support on this from the list, but unfortunately
now it has become URGENT that i get some solution to this problem i
need to resolve.

What i have done is create FileA.CSV whose structure is as follows :-
(no blank spaces, this is just for representation)
/home/nitin/path/To/PRl1/File1.csv , /home/nitin/path/To/PR3/File1.csv
, /home/nitin/path/To/PR2/File1.csv
/home/nitin/path/To/PRl1/File2.csv , /home/nitin/path/To/PR3/File2.csv
, /home/nitin/path/To/PR2/File2.csv
/home/nitin/path/To/PRl1/File3.csv , /home/nitin/path/To/PR3/File3.csv
, /home/nitin/path/To/PR2/File3.csv
/home/nitin/path/To/PRl1/File4.csv , /home/nitin/path/To/PR3/File4.csv
, /home/nitin/path/To/PR2/File4.csv
...
...
(96) rows

The first column is INPUT Protocol-1 File1
Second Column is INPUT Protocol-3 File1
Third Column is OUTPUT Protocol-2 File1

Each File (eg. PR1/File1 , PR3/File1 ) have approx. 600 rows of 39
column, numeric data. These data files end in a blank new line / blank
line.

Through the following code I am trying to read the TWO input files,
extract columns, Add , Divide (take mean of the values) and write to
THEIR respective OUTPUT files.

My script reads the first file and displays all the rows (print) from
PR1/File1 and then program terminates. IT does not read the Second
file (PR3/File1) and therefore i am unable to write the result out to
the OUTPUT file (PR2/File1).

Earlier I was able to create ONE file ... like the loop would run ONCE
and would not do the same process to the NEXT set of files (PR1/File2
, PR3/File2 , PR2/File2) and do the same.... till it has done
processing all the 96 set of files.

here is the code
PL ... PL .... I REALLY need this solution.

*****************************
import sys, os, fileinput


FileA = raw_input('Enter CSV file with List of Files :')
try:
   fp1 = open(FileA,'r')
   #print fp1
except IOError:
   sys.exit('Could not open File : %s' % FileA)

for rows in fp1:
    #print rows
    row11 = rows.split(",")
    #print row1
    row1 = row11[0]
    row2 = row11[1]
    row3 = row11[2]
    #print row1
    #print row2
    #print row3
    try:
       fp2 = open(row1,'r')
       #print fp2
    except IOError:
       sys.exit('Could not open File %s.' % fp2)
    try:
       fp3 = open(row2,'r')
       #print fp3
    except IOError:
       sys.exit('Could not open File %s.' % fp3)
    try:
       fp4 = open(row3,'w')
       #print fp4
    except IOError:
       sys.exit('Could not open File %s to write.' % fp4)

    row21 = fp2.readline().split(",")
    row31 = fp3.readline().split(",")
    #print row21
    row22 = row21[0]
    row23 = row21[1]
    row24 = row21[2]
    row25 = row21[3]
    row26 = row21[21]
    row27 = row21[22]
    row28 = row21[23]

    row32 = row31[1]
    row33 = row31[2]
    row34 = row31[3]
    row35 = row31[21]
    row36 = row31[22]
    row37 = row31[23]
    print "PR1", row22, row23, row24, row25, row26, row27, row28,
"PR3", row32, row33, row34, row35, row36, row37

    ## Doing the Addition is also not the problem. I am not able to put this
    ## whole process in a loop.
    ## do the calculation and write to file.
    ## and do the same thing with the next set of files. Till 96 sets

From nitinchandra1 at gmail.com  Wed Aug 25 21:49:25 2010
From: nitinchandra1 at gmail.com (nitin chandra)
Date: Thu, 26 Aug 2010 01:19:25 +0530
Subject: [Tutor] Need URGENT support ... PL
In-Reply-To: 
References: 
Message-ID: 

sorry missed; with current code IT is reading / prints ONLY first
lines for each 96 set of files are displayed. DOES NOT go the Next row
or the Next Set of Files.

PL .... PL ... give me the solution.

Thanks

Nitin

*********************************

PR1 0.000000 0.153436 0.016740 1.362566 -0.031154 1.132133 0.266704
PR3 -0.047642 0.059674 0.271700 0.047802 -0.085366 0.016262
PR1 0.005000 0.137681 0.063328 1.396118 0.015738 1.374378 0.313304 PR3
-0.008209 0.059674 0.339661 -0.046058 0.087159 0.008836
PR1 0.010000 0.200700 0.008988 1.431611 0.007935 1.478203 0.285076 PR3
-0.047827 0.075154 0.201622 -0.022574 0.087495 0.027239
PR1 0.015000 0.145697 0.016801 1.431463 -0.023277 1.651546 0.333441
PR3 -0.023871 0.082955 0.547534 0.040449 0.053501 -0.059713
PR1 0.000000 -3.404975 -0.965380 26.688482 -0.538069 7.530815
-0.076355 PR3 1.736750 0.261636 7.920164 0.579122 2.579521 -0.468668
PR1 0.005000 -3.381482 -1.012078 26.964482 -0.546172 7.566007
-0.104835 PR3 1.784014 0.315952 7.989384 0.634342 2.439866 -0.584216
PR1 0.010000 -3.358453 -1.004423 26.654238 -0.530866 7.150382
-0.085785 PR3 1.807878 0.362540 7.748612 0.595252 2.581121 -0.335703
PR1 0.015000 -3.327500 -0.880397 26.480582 -0.593364 7.323216
-0.056011 PR3 1.736750 0.347047 7.886282 0.429967 2.304293 -0.275297
PR1 0.000000 -0.004793 0.030768 0.356952 -0.036841 0.332747 -0.087458
PR3 -1.433546 -0.237249 7.929407 -0.446087 2.454336 0.326635
PR1 0.005000 -0.020455 -0.008018 0.461187 -0.036616 0.367250 -0.077974
PR3 -1.401758 -0.229472 7.722859 -0.548049 2.662068 0.290733
PR1 0.010000 -0.067348 -0.046731 0.218824 -0.036541 0.263715 -0.087470
PR3 -1.457039 -0.237212 7.618937 -0.485251 2.350271 0.318161
PR1 0.015000 -0.043669 -0.039003 0.322279 -0.052372 0.506002 -0.096786
PR3 -1.449300 -0.229472 7.687630 -0.563655 2.593573 0.233980
PR1 0.000000 1.641553 0.391073 13.009227 0.214600 1.953616 0.015595
PR3 0.146105 0.032141 0.840999 0.006657 0.178160 -0.130106
PR1 0.005000 1.681172 0.391073 13.008975 0.222178 2.196009 0.025139
PR3 0.114503 0.024401 0.946306 0.124525 -0.235777 0.057199
PR1 0.010000 1.649384 0.391061 13.042360 0.238084 2.334502 0.005910
PR3 0.082993 0.032141 0.876697 0.156186 0.283311 -0.066508
PR1 0.015000 1.673248 0.429835 12.801305 0.214450 2.231176 0.091931
PR3 0.106672 0.016600 1.049760 0.054149 -0.858067 0.058464
PR1 0.000000 -0.130893 -0.171140 0.332583 -0.030145 1.476301 -0.362464
PR3 0.051427 -0.025635 0.600788 0.118771 0.509802 -0.041242
PR1 0.005000 -0.115045 -0.171091 0.470262 -0.014539 1.685376 -0.458278
PR3 0.020196 -0.048916 0.290571 0.001202 0.129074 -0.048434
PR1 0.010000 -0.099198 -0.194348 0.297432 0.001141 1.442160 -0.391747
PR3 -0.027253 -0.025610 0.532962 -0.006900 -0.147851 -0.029492
PR1 0.015000 -0.130522 -0.186620 0.712175 0.008944 1.339193 -0.401560
PR3 0.059166 -0.010105 0.188483 0.024012 0.302548 -0.001217


On Thu, Aug 26, 2010 at 1:10 AM, nitin chandra  wrote:
> Hi all,
>
> I have been getting support on this from the list, but unfortunately
> now it has become URGENT that i get some solution to this problem i
> need to resolve.
>
> What i have done is create FileA.CSV whose structure is as follows :-
> (no blank spaces, this is just for representation)
> /home/nitin/path/To/PRl1/File1.csv , /home/nitin/path/To/PR3/File1.csv
> , /home/nitin/path/To/PR2/File1.csv
> /home/nitin/path/To/PRl1/File2.csv , /home/nitin/path/To/PR3/File2.csv
> , /home/nitin/path/To/PR2/File2.csv
> /home/nitin/path/To/PRl1/File3.csv , /home/nitin/path/To/PR3/File3.csv
> , /home/nitin/path/To/PR2/File3.csv
> /home/nitin/path/To/PRl1/File4.csv , /home/nitin/path/To/PR3/File4.csv
> , /home/nitin/path/To/PR2/File4.csv
> ...
> ...
> (96) rows
>
> The first column is INPUT Protocol-1 File1
> Second Column is INPUT Protocol-3 File1
> Third Column is OUTPUT Protocol-2 File1
>
> Each File (eg. PR1/File1 , PR3/File1 ) have approx. 600 rows of 39
> column, numeric data. These data files end in a blank new line / blank
> line.
>
> Through the following code I am trying to read the TWO input files,
> extract columns, Add , Divide (take mean of the values) and write to
> THEIR respective OUTPUT files.
>
> My script reads the first file and displays all the rows (print) from
> PR1/File1 and then program terminates. IT does not read the Second
> file (PR3/File1) and therefore i am unable to write the result out to
> the OUTPUT file (PR2/File1).
>
> Earlier I was able to create ONE file ... like the loop would run ONCE
> and would not do the same process to the NEXT set of files (PR1/File2
> , PR3/File2 , PR2/File2) and do the same.... till it has done
> processing all the 96 set of files.
>
> here is the code
> PL ... PL .... I REALLY need this solution.
>
> *****************************
> import sys, os, fileinput
>
>
> FileA = raw_input('Enter CSV file with List of Files :')
> try:
> ? fp1 = open(FileA,'r')
> ? #print fp1
> except IOError:
> ? sys.exit('Could not open File : %s' % FileA)
>
> for rows in fp1:
> ? ?#print rows
> ? ?row11 = rows.split(",")
> ? ?#print row1
> ? ?row1 = row11[0]
> ? ?row2 = row11[1]
> ? ?row3 = row11[2]
> ? ?#print row1
> ? ?#print row2
> ? ?#print row3
> ? ?try:
> ? ? ? fp2 = open(row1,'r')
> ? ? ? #print fp2
> ? ?except IOError:
> ? ? ? sys.exit('Could not open File %s.' % fp2)
> ? ?try:
> ? ? ? fp3 = open(row2,'r')
> ? ? ? #print fp3
> ? ?except IOError:
> ? ? ? sys.exit('Could not open File %s.' % fp3)
> ? ?try:
> ? ? ? fp4 = open(row3,'w')
> ? ? ? #print fp4
> ? ?except IOError:
> ? ? ? sys.exit('Could not open File %s to write.' % fp4)
>
> ? ?row21 = fp2.readline().split(",")
> ? ?row31 = fp3.readline().split(",")
> ? ?#print row21
> ? ?row22 = row21[0]
> ? ?row23 = row21[1]
> ? ?row24 = row21[2]
> ? ?row25 = row21[3]
> ? ?row26 = row21[21]
> ? ?row27 = row21[22]
> ? ?row28 = row21[23]
>
> ? ?row32 = row31[1]
> ? ?row33 = row31[2]
> ? ?row34 = row31[3]
> ? ?row35 = row31[21]
> ? ?row36 = row31[22]
> ? ?row37 = row31[23]
> ? ?print "PR1", row22, row23, row24, row25, row26, row27, row28,
> "PR3", row32, row33, row34, row35, row36, row37
>
> ? ?## Doing the Addition is also not the problem. I am not able to put this
> ? ?## whole process in a loop.
> ? ?## do the calculation and write to file.
> ? ?## and do the same thing with the next set of files. Till 96 sets
>

From steve at pearwood.info  Wed Aug 25 23:09:14 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 26 Aug 2010 07:09:14 +1000
Subject: [Tutor] why does this fail
In-Reply-To: <4C755E74.2060003@gmail.com>
References: 
	<4C755E74.2060003@gmail.com>
Message-ID: <201008260709.15789.steve@pearwood.info>

On Thu, 26 Aug 2010 04:18:28 am Greg Bair wrote:
> I'm assuming what you really want is :
>
> if letter in strng:
> ? ? print "true"
> else:
> ? ? print "false"

Oh I hope not... the above is better written as:

print letter in strng

(assuming you don't care about the difference between "True" 
and "true").



-- 
Steven D'Aprano

From steve at pearwood.info  Wed Aug 25 23:19:29 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 26 Aug 2010 07:19:29 +1000
Subject: [Tutor] Need URGENT support ... PL
In-Reply-To: 
References: 
Message-ID: <201008260719.29833.steve@pearwood.info>

On Thu, 26 Aug 2010 05:40:33 am nitin chandra wrote:
> Hi all,
>
> I have been getting support on this from the list, but unfortunately
> now it has become URGENT that i get some solution to this problem i
> need to resolve.

Is it "URGENT" enough that you would consider paid support?

Or are you asking for free support *and* immediate responsiveness as 
well? If so, why is *your* urgency important to us?


> Through the following code I am trying to read the TWO input files,
> extract columns, Add , Divide (take mean of the values) and write to
> THEIR respective OUTPUT files.
>
> My script reads the first file and displays all the rows (print) from
> PR1/File1 and then program terminates. IT does not read the Second
> file (PR3/File1) and therefore i am unable to write the result out to 
> the OUTPUT file (PR2/File1).

"Divide and conquer" is the most important programming principle. When a 
task is too complicated, break it into little pieces and solve each 
little piece alone. That's why functions exist! Instead of one great 
big script that tries to do everything, break the problem into 
functions.

You have a file that has the format:

filename1,filename3,filename2

repeated for many lines. Write a function that takes a *single* line and 
splits it into three filenames. That's easy:

def get_names(input_line):
    return input_line.strip().split(',')

Now write a function that does that to each and every line in a file:

def process_input_file(filename):
    for line in open(filename):
        f1, f3, f2 = input_line.strip().split(',')
        process(f1, f3, f2)


Now write the process function:

def process(infile1, infile2, outfile):
    """Read files infile1 and infile2, do something to their 
    content line-by-line, and write the output to outfile.
    """
    # whatever...

And then write your calculate function that operates on one row at a 
time:

def calculate(line1, line2):
    # whatever...


Just make sure it returns a string ending with a newline "\n".


And finally, put it all together:

if __name__ == '__main__':
    filename = raw_input("Enter the name of the file: ")
    process_input_file(filename.strip())


And that should be it.

If there are any problems, they will be easy to diagnose because you can 
isolate them to one small function instead of one big, confusing 
script. Do not use try...except and sys.exit to disguise where 
exceptions occur. If there is a bug or an error, you want to see the 
full traceback, not just a generic, useless error message.

I can't remember how much the company I work for charges for a monthly 
four-hour service level agreement, but we charge AUD$300 for ad-hoc 
priority service plus $150 an hour for consulting. Since I'm doing this 
in my own time, I'll do it for half that. You get the above for free 
because I'm a nice guy. (Or maybe a sucker.) If you still need "URGENT" 
support, contact me and we'll make arrangements.

Either that, or just wait until somebody feels like answering.



-- 
Steven D'Aprano

From matt.gregory at oregonstate.edu  Wed Aug 25 23:29:42 2010
From: matt.gregory at oregonstate.edu (Gregory, Matthew)
Date: Wed, 25 Aug 2010 14:29:42 -0700
Subject: [Tutor] design of Point class
In-Reply-To: <201008211124.29475.steve@pearwood.info>
References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu>
	<201008211124.29475.steve@pearwood.info>
Message-ID: <1D673F86DDA00841A1216F04D1CE70D6426032E02B@EXCH2.nws.oregonstate.edu>

Steven D'Aprano wrote:
> Other than using numpy, probably the simplest solution is to just
> subclass tuple and give it named properties and whatever other methods
> you want. Here's a simple version:
> 
> class Point(tuple):
> [snip]
>
> What it doesn't give you (yet!) is:
> 
> * distance between Points with different dimensions could easily be
>   defined just by removing the len() comparison. zip() will
>   automatically terminate at the shortest input, thus projecting the
>   higher-dimension point down to the lower-dimension point;
> * other distance methods, such as Manhattan distance;
> * a nice exception when you as for (say) pt.z from a 2-D point, instead
>   of raising IndexError;
> * point arithmetic (say, adding two points to get a third).

I hope you'll suffer me one more question on this thread.  In thinking about creating other distance methods (as you suggest), how best to create a generic enough interface, so that ANY distance metric could be used.  It seems like coding the Point class with multiple distance methods is not very flexible, especially if you wanted to iterate over those methods for any two points, e.g.

class Point(tuple):
    def euclidean_distance(self, other):
        ...
    def manhattan_distance(self, other):
        ...
    def any_other_distance(self, other):
        ...

Would this be a place for a generic get_distance with a DistanceMetric subclass as a parameter, e.g.

class DistanceMetric(object):
    def distance(self, p1, p2):
        assert 0, 'Must be defined in subclasses'

class EuclideanDistMetric(DistanceMetric):
    def distance(self, p1, p2):
        ...
        
class Point(tuple):
    def get_distance(self, other, metric):
        distance = metric.distance(self, other)
        return distance

I'm sure I don't have all my syntax correct.  Thanks for continued help.

matt

From amartin7211 at gmail.com  Wed Aug 25 23:48:11 2010
From: amartin7211 at gmail.com (Andrew Martin)
Date: Wed, 25 Aug 2010 17:48:11 -0400
Subject: [Tutor] Trouble with exercise regarding classes
Message-ID: 

I just starting programming and am trying to learn some python (ver 2.6). I
am reading Python Programming: An Introduction to Computer Science by John
Zelle. In chapter ten, the first programming exercise asks the reader to
modify code from the chapter (below) . The code I added is highlighted.
However, when I did so I got this error: "TypeError: unbound method getY()
must be called with Projectile instance as first argument (got nothing
instead) " Can someone help me out with what I am doing wrong? Please be as
straitforward as you can. I am still struggling with classes

Thanks a lot


# cball4.py
> #   Simulation of the flight of a cannon ball (or other projectile)
> #   This version uses a  separate projectile module file
>
> from projectile import Projectile
>
> def getInputs():
>     a = input("Enter the launch angle (in degrees): ")
>     v = input("Enter the initial velocity (in meters/sec): ")
>     h = input("Enter the initial height (in meters): ")
>     t = input("Enter the time interval between position calculations: ")
>     return a,v,h,t
>
> def main():
>     angle, vel, h0, time = getInputs()
>     cball = Projectile(angle, vel, h0)
>     zenith = 0.0
>     while cball.getY() >= 0:
>         cball.update(time)
>         if Projectile.getY > zenith:
>             zenith = Projectile.getY()
>     print "\nDistance traveled: %0.1f meters." % (cball.getX())
>     print "The heighest the cannon ball reached was %0.1f meters." %
> (zenith)
>
> if __name__ == "__main__": main()
>
>
>

# projectile.py
>
> """projectile.py
> Provides a simple class for modeling the flight of projectiles."""
>
> from math import pi, sin, cos
>
> class Projectile:
>
>     """Simulates the flight of simple projectiles near the earth's
>     surface, ignoring wind resistance. Tracking is done in two
>     dimensions, height (y) and distance (x)."""
>
>     def __init__(self, angle, velocity, height):
>         """Create a projectile with given launch angle, initial
>         velocity and height."""
>         self.xpos = 0.0
>         self.ypos = height
>         theta = pi * angle / 180.0
>         self.xvel = velocity * cos(theta)
>         self.yvel = velocity * sin(theta)
>
>     def update(self, time):
>         """Update the state of this projectile to move it time seconds
>         farther into its flight"""
>         self.xpos = self.xpos + time * self.xvel
>         yvel1 = self.yvel - 9.8 * time
>         self.ypos = self.ypos + time * (self.yvel + yvel1) / 2.0
>         self.yvel = yvel1
>
>     def getY(self):
>         "Returns the y position (height) of this projectile."
>         return self.ypos
>
>     def getX(self):
>         "Returns the x position (distance) of this projectile."
>         return self.xpos
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From mehgcap at gmail.com  Wed Aug 25 23:58:42 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Wed, 25 Aug 2010 17:58:42 -0400
Subject: [Tutor] args to functions in a dictionary?
Message-ID: 

Hi all,
If I wanted to have a dictionary containing functions, could I pass
args to those functions? For example:
menu={
 "option 1":f1,
 "option 2":f2
}
How would I pass args to f1 or f2 in this case? TIA.

-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From waynejwerner at gmail.com  Thu Aug 26 00:24:58 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Wed, 25 Aug 2010 17:24:58 -0500
Subject: [Tutor] args to functions in a dictionary?
In-Reply-To: 
References: 
Message-ID: 

On Wed, Aug 25, 2010 at 4:58 PM, Alex Hall  wrote:

> Hi all,
> If I wanted to have a dictionary containing functions, could I pass
> args to those functions? For example:
> menu={
>  "option 1":f1,
>  "option 2":f2
> }
> How would I pass args to f1 or f2 in this case? TIA.


You sure could, because functions are first order citizens in python,
meaning you can pass them around like any other data type.

menu['option 1']() is how you would call the functions, and you'd just put
an args/kwargs in the parenthesis.

Conceptually you can replace menu['option 1'] with f1, so anywhere you see
this:

menu['option 1'](arg1)

you can replace it with

f1(arg1)

I don't know if Python does that exact thing on the back end, but the end
result is certainly the same.

HTH,
Wayne

(p.s. Gmail's undo sending feature is terribly nice when I forget to
reply-all)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From mehgcap at gmail.com  Thu Aug 26 00:34:15 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Wed, 25 Aug 2010 18:34:15 -0400
Subject: [Tutor] args to functions in a dictionary?
In-Reply-To: 
References: 
	
Message-ID: 

On 8/25/10, Wayne Werner  wrote:
> On Wed, Aug 25, 2010 at 4:58 PM, Alex Hall  wrote:
>
>> Hi all,
>> If I wanted to have a dictionary containing functions, could I pass
>> args to those functions? For example:
>> menu={
>>  "option 1":f1,
>>  "option 2":f2
>> }
>> How would I pass args to f1 or f2 in this case? TIA.
>
>
> You sure could, because functions are first order citizens in python,
> meaning you can pass them around like any other data type.
>
> menu['option 1']() is how you would call the functions, and you'd just put
> an args/kwargs in the parenthesis.
Of course! So simple, yet somehow I did not see it. Thanks!
>
> Conceptually you can replace menu['option 1'] with f1, so anywhere you see
> this:
>
> menu['option 1'](arg1)
>
> you can replace it with
>
> f1(arg1)
>
> I don't know if Python does that exact thing on the back end, but the end
> result is certainly the same.
>
> HTH,
> Wayne
>
> (p.s. Gmail's undo sending feature is terribly nice when I forget to
> reply-all)
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From alan.gauld at btinternet.com  Thu Aug 26 01:10:03 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 26 Aug 2010 00:10:03 +0100
Subject: [Tutor] design of Point class
References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu><201008211124.29475.steve@pearwood.info>
	<1D673F86DDA00841A1216F04D1CE70D6426032E02B@EXCH2.nws.oregonstate.edu>
Message-ID: 


"Gregory, Matthew"  wrote

>.  It seems like coding the Point class with multiple distance 
>methods
> is not very flexible, especially if you wanted to iterate over those 
> methods
> for any two points

Its flexible enough provided you keep the interface to points. In 
other words
if the distance is expressed as the difference between two points that 
can
be worked out regardless of representation. The trick is to always 
keep the
interface as free of internal representation detail as possible.

However, you may not be able to provide concrete implementations of
those methods at the level of Point - which means Point turns into an
abstract class. Alternatively you may implement the methods in such
way that they call still other methods to perform data conversions
(polar-cartesian say) or generate default  values where none exist
- generating an X,Y from a list of dimensions maybe. And the Point
class implementation of those conversions may be trivial.

There are seveal ways to do this and none of them are perfect and none
of them are "right" - although a few of them might be considered 
"wrong"!.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From alan.gauld at btinternet.com  Thu Aug 26 01:24:40 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 26 Aug 2010 00:24:40 +0100
Subject: [Tutor] Trouble with exercise regarding classes
References: 
Message-ID: 


"Andrew Martin"  wrote

> However, when I did so I got this error: "TypeError: unbound method 
> getY()
> must be called with Projectile instance as first argument (got 
> nothing
> instead) "

>> def main():
>>     angle, vel, h0, time = getInputs()
>>     cball = Projectile(angle, vel, h0)

cball is a Projectile instance

>>     zenith = 0.0
>>     while cball.getY() >= 0:

So this is fine

>>         cball.update(time)


>>         if Projectile.getY > zenith:
>>             zenith = Projectile.getY()

But what are you doing here?
You are trying to compare the getY method of the class with a floating 
point number?
Then you call getY using the class rather than the instance?
I'm confused - and so is Python...


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From carter.danforth at gmail.com  Thu Aug 26 02:41:56 2010
From: carter.danforth at gmail.com (Carter Danforth)
Date: Wed, 25 Aug 2010 20:41:56 -0400
Subject: [Tutor] python: can't open file 'ex1.py' : [Errno 2] No such
	file or directory
Message-ID: 

Thanks a lot Alan and Karim, it's working -- I really appreciate it, guys.


On Wed, Aug 25, 2010 at 4:53 AM,  wrote:

> Send Tutor mailing list submissions to
>        tutor at python.org
>
> To subscribe or unsubscribe via the World Wide Web, visit
>        http://mail.python.org/mailman/listinfo/tutor
> or, via email, send a message with subject or body 'help' to
>        tutor-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: continuous running of a method (Greg Bair)
>   2. Re: continuous running of a method (Hugo Arts)
>   3. Re: Retriving previous user inputs in a gui (Alan Gauld)
>   4. Re: python: can't open file 'ex1.py' : [Errno 2] No such
>      fileor directory (Alan Gauld)
>   5. os.access unreliable? (Albert-Jan Roskam)
>   6. Re: os.access unreliable? (Tim Golden)
>
>
> ----------------------------------------------------------------------
>
> Message: 1
> Date: Wed, 25 Aug 2010 01:56:14 -0400
> From: Greg Bair 
> To: tutor at python.org
> Subject: Re: [Tutor] continuous running of a method
> Message-ID: <4C74B07E.3060803 at gmail.com>
> Content-Type: text/plain; charset=UTF-8; format=flowed
>
> On 08/25/2010 01:25 AM, Nitin Das wrote:
> > The problem with this while loop is if your random value doesn't lie
> > between the mentioned range then ur 100% cpu would be utilized. The
> > one thing u can do is to sleep for some time lets say 0.5 sec after
> > every while loop iteration , in this case ur cpu utilization will go
> down.
> It's not that the value doesn't lie between the mentioned range.
>
> What I'm doing is randomly fetching an item from a list of dicts
> (multi-dimensional ones from a JSON response) and accessing a value from
> it, but not every item has the key I'm looking for (can't change that).
> I suppose what I could do to not randomize every time is to iterate
> through the list and create a new list that only contains dicts that
> have that key, then get a random one from that.  I suppose that would be
> more efficient.
>
> Any thoughts?
>
> Greg
> >
> > --nitin
> >
> > On Mon, Aug 23, 2010 at 8:21 PM, bob gailer  > > wrote:
> >
> >      On 8/23/2010 1:00 AM, Greg Bair wrote:
> >
> >         I have a method (I'll call it foo) that will either return
> >         None or an object depending on a random value generated.  What
> >         I want to happen is that if I call foo(), i.e, f = foo() and
> >         it returns None, to re-call it until it returns something
> >         else.  I would think this would be done with a while loop, but
> >         can't seem to get the details right.
> >
> >
> >     Even though a while will work, you will have tied up the CPU until
> >     the loop terminates. This is never a good idea.
> >
> >     What is your higher level goal?
> >
> >
>
>
>
> ------------------------------
>
> Message: 2
> Date: Wed, 25 Aug 2010 02:12:46 -0500
> From: Hugo Arts 
> To: Greg Bair 
> Cc: tutor at python.org
> Subject: Re: [Tutor] continuous running of a method
> Message-ID:
>        
> Content-Type: text/plain; charset=UTF-8
>
> On Wed, Aug 25, 2010 at 12:56 AM, Greg Bair  wrote:
> >
> > It's not that the value doesn't lie between the mentioned range.
> >
> > What I'm doing is randomly fetching an item from a list of dicts
> > (multi-dimensional ones from a JSON response) and accessing a value from
> it,
> > but not every item has the key I'm looking for (can't change that). ?I
> > suppose what I could do to not randomize every time is to iterate through
> > the list and create a new list that only contains dicts that have that
> key,
> > then get a random one from that. ?I suppose that would be more efficient.
> >
> > Any thoughts?
> >
>
> this sounds like a good idea. Either the filter() function or a list
> comprehension can filter out the dicts you want easily.
>
> My guess is the list comprehension is somewhat faster, but I could be
> wrong. And it doesn't sound like performance is a very big deal here
> anyway, so take your pick.
>
> Hugo
>
>
> ------------------------------
>
> Message: 3
> Date: Wed, 25 Aug 2010 08:21:31 +0100
> From: "Alan Gauld" 
> To: tutor at python.org
> Subject: Re: [Tutor] Retriving previous user inputs in a gui
> Message-ID: 
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>        reply-type=original
>
>
> "Karim"  wrote
>
> > Is there any equivalent to JAVACC in python (or lex yacc) to create
> > grammary
> > for config or format file?
>
> Thats kind of what ConfiogParser does - it gives you tools to
> read/write
> a config file.
>
> If you don't mind the data not being human readable you could also
> use the shelve module which simulates a dictionary in a file.
>
> There are lots of options.
>
> Alan G.
>
>
>
>
> ------------------------------
>
> Message: 4
> Date: Wed, 25 Aug 2010 08:30:59 +0100
> From: "Alan Gauld" 
> To: tutor at python.org
> Subject: Re: [Tutor] python: can't open file 'ex1.py' : [Errno 2] No
>        such    fileor directory
> Message-ID: 
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
>        reply-type=original
>
>
> "Carter Danforth"  wrote
>
> > Anyhow, I can't seem to be executing any files in terminal for some
> > reason, in this case the file ex1.py:
> >
> > C:\Users\Carter Danforth\python ex1.py
> > python: can't open file 'ex1.py': [Errno 2] No such file or
> > directory
> >
> > ex1.py is located in "pythonpractice" on my desktop and I've updated
> > the
> > modules, here's the output from sys.path:
>
> sys.path (and PYTHONPATH) only affect how imports work within
> Python, they have no effect on Windows ability to find scripts.
> To run a script you must do one of the following:
>
> 1) CD to the script folder and run Python from there as:
>      > Python myscript.py
>
> 2) From anywhere execute Python as
>    > python full\path\to\myscript.py
>
> 3) From anywhere execute myscript as
>   > myscript.py
>
> For 1,2 PATH must include the Python executable folder
> For 3 the .py extension must be associated with the Python
> executable and the folder containing myscript must be in PATH.
>
> > I'm not sure why I keep getting this error message and why I'm not
> > able to
> > execute any .py files. Any help would be great appreciated.
>
> Windows needs to know where the file lives. You could have many
> files called myscript.py in your file system. PYTHONPATH is used
> only by Python and only for imports. PATH is used only for
> executables.
>
> HTH,
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
>
>
> ------------------------------
>
> Message: 5
> Date: Wed, 25 Aug 2010 01:28:47 -0700 (PDT)
> From: Albert-Jan Roskam 
> To: Python Mailing List 
> Subject: [Tutor] os.access unreliable?
> Message-ID: <502129.63760.qm at web110716.mail.gq1.yahoo.com>
> Content-Type: text/plain; charset="iso-8859-1"
>
> Hi,
>
> Hi I'm using os.access to do a preliminary check to see if I have RW
> access, but
> it seems to be unreliable. In a dir for which I have only read access,
> os.access
> also says I have write access. This is under Windows 2000. I could of
> course use
> a try-except and catch the IOError, but I'd like to know why the code below
> isn;t working.
>
> ??? def isAcccessible(self):
> ??????? if os.access(self.path, os.R_OK) and os.access(self.path, os.W_OK):
> ??????????? return True
> ??????? else:
> ??????????? return False
> ?Cheers!!
> 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: <
> http://mail.python.org/pipermail/tutor/attachments/20100825/3a660844/attachment-0001.html
> >
>
> ------------------------------
>
> Message: 6
> Date: Wed, 25 Aug 2010 09:53:08 +0100
> From: Tim Golden 
> Cc: Python Mailing List 
> Subject: Re: [Tutor] os.access unreliable?
> Message-ID: <4C74D9F4.3030607 at timgolden.me.uk>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> On 25/08/2010 09:28, Albert-Jan Roskam wrote:
> > Hi,
> >
> > Hi I'm using os.access to do a preliminary check to see if I have RW
> access, but
> > it seems to be unreliable. In a dir for which I have only read access,
> os.access
> > also says I have write access. This is under Windows 2000. I could of
> course use
> > a try-except and catch the IOError, but I'd like to know why the code
> below
> > isn;t working.
> >
> >      def isAcccessible(self):
> >          if os.access(self.path, os.R_OK) and os.access(self.path,
> os.W_OK):
> >              return True
> >          else:
> >              return False
>
> os.access is effectively meaningless under Windows, especially
> against directories. It only checks the read-only flag (which
> doesn't mean anything for directories anyway).
>
> There is a long-open issue here:
>
>   http://bugs.python.org/issue2528
>
> which I am half-minded to close although I could be
> persuaded to pursue it if anyone were interested enough.
> On the other hand, os.access checks are open to race-conditions
> in any case, so you might simply be better off with a
> try-except block as you suggest.
>
> If you want more information I can explain further but unless you
> want to dive into the Windows API and use AccessCheck -- which is
> what that patch is doing -- then I suggest you use try-except
>
> TJG
>
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 78, Issue 116
> **************************************
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From denisg640 at gmail.com  Thu Aug 26 03:00:29 2010
From: denisg640 at gmail.com (Denis Gomes)
Date: Wed, 25 Aug 2010 21:00:29 -0400
Subject: [Tutor] Function object
In-Reply-To: 
References: 
	
Message-ID: 

Daniel,

     Considering that Python is your first programming language, let's start
from the absolute beginning.  Before you think about what a function object
is, try to understand what a function is.  A function is a series of
python commands put together under a common heading or name in order to
achieve a specific task.  A function can receive parameters from the main
program, perform some operations using the parameters and return value(s) to
the main program.  In the following example, add is a function and it, like
all other functions is defined using the def statement:

def add(x,y):
     sum=x+y    # python commands here
     return sum

The x and y are parameters or arguments that you pass to the function
add.  x and y can be anything depending on what you want your function to
do.  In our particular example x and y will be numbers (assuming, integers)
because the add function will take the parameters, adds them together and
temporarily save the result in a variable called sum.  The return statement
will then take the result of the addition and send it back to the main
program.  When this happens the sum variable you created inside the function
will go out of scope (i.e. you will not be able to refer to it any more).
To use the function above say you have the following snippet in a file
called foo.py:

------------------------foo.py--------------------
def add(x,y):
     sum=x+y
     return sum

if __name__=="__main__":    # Execution of code starts here when you type
">>> python foo.py".  Python knows you defined add above.  Think of this as
the main program.
     result=add(1,1)    # You are calling add and storing the value returned
into a variable called result
     print result    # Assuming you are using Python2.X
----------------------------------------------------

Type
>>> python foo.py

Run it and see what happens.  You should get the answer 2.  From the main
program, you are calling the function add and storing the value that it
returns into a variable called result.  Then you are printing that value to
screen.

Once you get to learning about classes you will get a better understanding
of why a function in python is an object but I think you should try to get
the mechanics down first.

Experiment! Good luck.

Denis




On Wed, Aug 25, 2010 at 2:44 PM, Alan Gauld wrote:

>
> "Daniel"  wrote
>
>
> another problem regarding understanding a concept- function object. As I
>> said, I do not understand what a function object is, what it does, and
>> what
>> can I do with it?
>>
>
> You are actually using them all the time.
> Every function in Python is a function object.
> You can execute the function by putting parenthesesc after its name(filled
> with any required arguments)
>
> def foo(): return None
>
> defines a function object called foo that does nothing but return None.
>
> We can rewrite that using the lambda operator which returns function
> objects with no name:
>
> foo = lambda : None
>
> This assigns an anonymous function object to a variable foo - thus giving
> it a name, just like any other variable.
>
> In both cases we can now call the function with:
>
> foo()
>
> The advantage of treating functions as objects is that we can store them
> and then call them later. This is the basis of event driven programming
> and GUIs. It also allows us to easily build reconfigurable dynamic logic
> into applications - just by changing the order in which functions are
> called.
>
> It also allows us to create functions which return functions as their
> output,
> but this is getting into deeper water, so I'll ignore that for now! :-)
>
> You will find a slightly different explanation in the Functional
> Programming
> topic of my tutorial
>
>
> HTH
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> _______________________________________________
>   Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From amartin7211 at gmail.com  Thu Aug 26 03:56:54 2010
From: amartin7211 at gmail.com (Andrew Martin)
Date: Wed, 25 Aug 2010 21:56:54 -0400
Subject: [Tutor] Trouble with exercise regarding classes
In-Reply-To: 
References: 
	
Message-ID: 

All I want to do is add a line that displays that maximum height the
cannonball reaches. I created a variable zenith to store the highest y
value. I then wanted to compare the current y value of the cannonball to
zenith while the cannonballs y value is greater than zero. If the
cannonballs current y value is greater than zenith, I want to have the
current value replace zenith. Finally, once the cannonball has reaches y =
0, I wanted the program to write out the value for zenith.

I want to compare zenith, a floating point number, with the current y value?
I thought the current y value could be retrieved by Projectile.getY. And how
do I call the getY using the instance?



On Wed, Aug 25, 2010 at 7:24 PM, Alan Gauld wrote:

>
> "Andrew Martin"  wrote
>
>
>  However, when I did so I got this error: "TypeError: unbound method getY()
>> must be called with Projectile instance as first argument (got nothing
>> instead) "
>>
>
>  def main():
>>>    angle, vel, h0, time = getInputs()
>>>    cball = Projectile(angle, vel, h0)
>>>
>>
> cball is a Projectile instance
>
>
>     zenith = 0.0
>>>    while cball.getY() >= 0:
>>>
>>
> So this is fine
>
>
>         cball.update(time)
>>>
>>
>
>         if Projectile.getY > zenith:
>>>            zenith = Projectile.getY()
>>>
>>
> But what are you doing here?
> You are trying to compare the getY method of the class with a floating
> point number?
> Then you call getY using the class rather than the instance?
> I'm confused - and so is Python...
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From amonroe at columbus.rr.com  Thu Aug 26 04:27:03 2010
From: amonroe at columbus.rr.com (R. Alan Monroe)
Date: Wed, 25 Aug 2010 22:27:03 -0400
Subject: [Tutor] continuous running of a method
In-Reply-To: <201008252037.54541.steve@pearwood.info>
References: <4C720056.3070309@gmail.com> <4C728AE0.9090304@gmail.com>
	
	<201008252037.54541.steve@pearwood.info>
Message-ID: <130420949513.20100825222703@columbus.rr.com>

> Any modern multi-tasking operating system will ensure than a while loop
> doesn't kill your computer's responsiveness. A decent operating system 
> will still remain responsive even at 100% CPU usage. Even Windows does 
> that!

Opinions vary. If you try this on a laptop, the end user will be quite
annoyed to see their battery drop to zero, their cooling fans go into
overdrive, and to receive first degree burns on their hands and/or
lap.

Busywaiting my cpu makes your program an instant candidate for
immediate deletion. Maybe that's just me :)

Alan


From mehgcap at gmail.com  Thu Aug 26 04:51:32 2010
From: mehgcap at gmail.com (Alex Hall)
Date: Wed, 25 Aug 2010 22:51:32 -0400
Subject: [Tutor] Trouble with exercise regarding classes
In-Reply-To: 
References: 
	
	
Message-ID: 

On 8/25/10, Andrew Martin  wrote:
> All I want to do is add a line that displays that maximum height the
> cannonball reaches. I created a variable zenith to store the highest y
> value. I then wanted to compare the current y value of the cannonball to
> zenith while the cannonballs y value is greater than zero. If the
> cannonballs current y value is greater than zenith, I want to have the
> current value replace zenith. Finally, once the cannonball has reaches y =
> 0, I wanted the program to write out the value for zenith.
>
> I want to compare zenith, a floating point number, with the current y value?
> I thought the current y value could be retrieved by Projectile.getY. And how
It can, but you need parentheses after the function call.
> do I call the getY using the instance?
I think the problem may be where you say
ball.getY
instead of
ball.getY()
When you hear "instance", do not panic. An instance is just a variable
of type class. For example, "ball" is an instance of the Projectile
class. As an example, if I had a "pet" class, I might make a "dog"
variable of type pet:
dog=Pet()
After I have my dog set up, since it is an instance of the Pet class,
it has all the methods available in the Pet class. I might say
dog.speak()
which would just look at my Pet class for a "speak" method, and call
it. In the same way, you have a "ball" variable which is  a
Projectile, so you have all the methods and variables from the
Projectile class available in the "ball" variable. Note that, if a
variable is of type class, it is also called an object, so I could
have as easily called the "ball" a Projectile object.
>
>
>
> On Wed, Aug 25, 2010 at 7:24 PM, Alan Gauld
> wrote:
>
>>
>> "Andrew Martin"  wrote
>>
>>
>>  However, when I did so I got this error: "TypeError: unbound method
>> getY()
>>> must be called with Projectile instance as first argument (got nothing
>>> instead) "
>>>
>>
>>  def main():
>>>>    angle, vel, h0, time = getInputs()
>>>>    cball = Projectile(angle, vel, h0)
>>>>
>>>
>> cball is a Projectile instance
>>
>>
>>     zenith = 0.0
>>>>    while cball.getY() >= 0:
>>>>
>>>
>> So this is fine
>>
>>
>>         cball.update(time)
>>>>
>>>
>>
>>         if Projectile.getY > zenith:
>>>>            zenith = Projectile.getY()
>>>>
>>>
>> But what are you doing here?
>> You are trying to compare the getY method of the class with a floating
>> point number?
>> Then you call getY using the class rather than the instance?
>> I'm confused - and so is Python...
>>
>>
>> --
>> Alan Gauld
>> Author of the Learn to Program web site
>> http://www.alan-g.me.uk/
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap

From nitin.162 at gmail.com  Thu Aug 26 04:57:08 2010
From: nitin.162 at gmail.com (Nitin Das)
Date: Thu, 26 Aug 2010 08:27:08 +0530
Subject: [Tutor] Trouble with exercise regarding classes
In-Reply-To: 
References: 
	
	
Message-ID: 

There are 2 ways to get the ypos value one is cball.ypos and another is
call.getY() both will give u the current ypos.

--nitin

On Thu, Aug 26, 2010 at 7:26 AM, Andrew Martin wrote:

> All I want to do is add a line that displays that maximum height the
> cannonball reaches. I created a variable zenith to store the highest y
> value. I then wanted to compare the current y value of the cannonball to
> zenith while the cannonballs y value is greater than zero. If the
> cannonballs current y value is greater than zenith, I want to have the
> current value replace zenith. Finally, once the cannonball has reaches y =
> 0, I wanted the program to write out the value for zenith.
>
> I want to compare zenith, a floating point number, with the current y
> value? I thought the current y value could be retrieved by Projectile.getY.
> And how do I call the getY using the instance?
>
>
>
>
> On Wed, Aug 25, 2010 at 7:24 PM, Alan Gauld wrote:
>
>>
>> "Andrew Martin"  wrote
>>
>>
>>  However, when I did so I got this error: "TypeError: unbound method
>>> getY()
>>> must be called with Projectile instance as first argument (got nothing
>>> instead) "
>>>
>>
>>  def main():
>>>>    angle, vel, h0, time = getInputs()
>>>>    cball = Projectile(angle, vel, h0)
>>>>
>>>
>> cball is a Projectile instance
>>
>>
>>     zenith = 0.0
>>>>    while cball.getY() >= 0:
>>>>
>>>
>> So this is fine
>>
>>
>>         cball.update(time)
>>>>
>>>
>>
>>         if Projectile.getY > zenith:
>>>>            zenith = Projectile.getY()
>>>>
>>>
>> But what are you doing here?
>> You are trying to compare the getY method of the class with a floating
>> point number?
>> Then you call getY using the class rather than the instance?
>> I'm confused - and so is Python...
>>
>>
>> --
>> Alan Gauld
>> Author of the Learn to Program web site
>> http://www.alan-g.me.uk/
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From denisg640 at gmail.com  Thu Aug 26 05:09:39 2010
From: denisg640 at gmail.com (Denis Gomes)
Date: Wed, 25 Aug 2010 23:09:39 -0400
Subject: [Tutor] Trouble with exercise regarding classes
In-Reply-To: 
References: 
	
	
Message-ID: 

Andrew,

     For starters you have some errors in the way you are trying to access
methods from within a class instances.  For example in your code in line 7
and 8,

def main():
    angle, vel, h0, time = getInputs()
    cball = Projectile(angle, vel, h0)
    zenith = 0.0
    while cball.getY() >= 0:
        cball.update(time)
        if Projectile.getY > zenith:          # This should be -- if
cball.getY()>zenith:
            zenith = Projectile.getY()       # This should be -- zenith =
cball.getY()
    print "\nDistance traveled: %0.1f meters." % (cball.getX())
    print "The heighest the cannon ball reached was %0.1f meters." %
(zenith)

You access the method of an instance using the instance name that you
created on line 3, not the class name.

Secondly, you have to change the time variable so that the value of
cball.getY() changes or else nothing will happen.  Assuming that the time
you are entering is a delta_t value, you can create another variable say
actual_time which starts at 0 and add delta_t to it at the end of the while
loop each time through.

actual_time=actual_time+delta_t

This will update your Y position because you will be calling
cball.update(actual_time).  You will converge to a solution.

Good luck,

Denis



On Wed, Aug 25, 2010 at 9:56 PM, Andrew Martin wrote:

> All I want to do is add a line that displays that maximum height the
> cannonball reaches. I created a variable zenith to store the highest y
> value. I then wanted to compare the current y value of the cannonball to
> zenith while the cannonballs y value is greater than zero. If the
> cannonballs current y value is greater than zenith, I want to have the
> current value replace zenith. Finally, once the cannonball has reaches y =
> 0, I wanted the program to write out the value for zenith.
>
> I want to compare zenith, a floating point number, with the current y
> value? I thought the current y value could be retrieved by Projectile.getY.
> And how do I call the getY using the instance?
>
>
>
>
> On Wed, Aug 25, 2010 at 7:24 PM, Alan Gauld wrote:
>
>>
>> "Andrew Martin"  wrote
>>
>>
>>  However, when I did so I got this error: "TypeError: unbound method
>>> getY()
>>> must be called with Projectile instance as first argument (got nothing
>>> instead) "
>>>
>>
>>  def main():
>>>>    angle, vel, h0, time = getInputs()
>>>>    cball = Projectile(angle, vel, h0)
>>>>
>>>
>> cball is a Projectile instance
>>
>>
>>     zenith = 0.0
>>>>    while cball.getY() >= 0:
>>>>
>>>
>> So this is fine
>>
>>
>>         cball.update(time)
>>>>
>>>
>>
>>         if Projectile.getY > zenith:
>>>>            zenith = Projectile.getY()
>>>>
>>>
>> But what are you doing here?
>> You are trying to compare the getY method of the class with a floating
>> point number?
>> Then you call getY using the class rather than the instance?
>> I'm confused - and so is Python...
>>
>>
>> --
>> Alan Gauld
>> Author of the Learn to Program web site
>> http://www.alan-g.me.uk/
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rwobben at hotmail.com  Thu Aug 26 08:22:43 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Thu, 26 Aug 2010 06:22:43 +0000
Subject: [Tutor] why does this fail
In-Reply-To: <427851.46740.qm@web86706.mail.ird.yahoo.com>
References: , ,
	<4C74F01B.7030502@compuscan.co.za>,
	,
	
	,
	<427851.46740.qm@web86706.mail.ird.yahoo.com>
Message-ID: 


Hello Alan,

 

Oops, then I have a problem.

Im following this book : http://openbookproject.net/thinkcs/python/english2e/ which is the first link  in the beginners tutorial page.

And it's talking about the string modules.

 

Roelof


 


Date: Wed, 25 Aug 2010 15:49:14 -0700
From: alan.gauld at btinternet.com
Subject: Re: [Tutor] why does this fail
To: rwobben at hotmail.com





Thats OK, I only replied because what you said could genuinely have been 
a mistake because some old tutorials still refer to the string module amnd 
its functions. Because other begineers may read the post too it was 
important to make the distinction.

Regards,

 Alan Gauld
Author of the Learn To Program website
http://www.alan-g.me.uk/






From: Roelof Wobben 
To: alan.gauld at btinternet.com
Sent: Wednesday, 25 August, 2010 19:38:03
Subject: RE: [Tutor] why does this fail



Oke,
 
That's what I ment.
Apolize for the bad English. 
It's not the language I often use.
 
Roelof

 
> To: tutor at python.org
> From: alan.gauld at btinternet.com
> Date: Wed, 25 Aug 2010 19:32:59 +0100
> Subject: Re: [Tutor] why does this fail
> 
> 
> "Roelof Wobben"  wrote
> 
> > It's for learning purposed but I forget that de module string 
> > has built in functions.Thank you for remainding it to me.
> 
> Its not the string module that Christian is referring to, 
> its the methods of string objects - different things:
> 
> 
> You can do:
> 
> import string
> string.replace(aString, aChr, another) # use string module
> 
> But its better to do
> 
> aString.replace(aChr, another) # use string method
> 
> HTH,
> 
> 
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> 
> 
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rwobben at hotmail.com  Thu Aug 26 08:25:34 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Thu, 26 Aug 2010 06:25:34 +0000
Subject: [Tutor] (no subject)
Message-ID: 


Hello, 

 

I have this exercise :

 

Try each of the following formatted string operations in a Python shell and record the results:

?%s %d %f? % (5, 5, 5)
?%-.2f? % 3
?%-10.2f%-10.2f? % (7, 1.0/2)
print ? $%5.2fn $%5.2fn $%5.2f? % (3, 4.5, 11.2)
 

But if I try in a python 2.7 IDLE enviroment I get this :

 

>>> %s %d %f % (5, 5, 5)
SyntaxError: invalid syntax
>>> print ?%s %d %f? % (5, 5, 5)
SyntaxError: invalid syntax

 

Roelof

 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From karim.liateni at free.fr  Thu Aug 26 08:43:29 2010
From: karim.liateni at free.fr (Karim)
Date: Thu, 26 Aug 2010 08:43:29 +0200
Subject: [Tutor] What Design Pattern for Document class (NOT URGENT)
Message-ID: <4C760D11.5090302@free.fr>


Hello All,

I want to  build some classes by optimizing their design.
But I want to keep quite 'simples'. I have a XML  document
which represents let's say some rules (id, description, value).

My first idea is to create an *docrules* class which holds my document.
This class will use 2 other instances from 2 respectives classes
reader and writer. The main method of  reader is get().
The main method of writer is write(). To resume I have:
                   
------------------------------                                  
-----------------------
                   -     docrules         
-----------------------------------      reader     -
                   
------------------------------                                  
-----------------------
                   -       filename       
-                                  -       file         -
                   - 
----------------------------                                  
-----------------------
                   -                            
-                                  -       get()       -
                   -                            
-------                            -----------------------
                   ------------------------------     -
                                                      -
                                                      
-                             ------------------------
                                                      
-------------------------------    writer        -
                                                                                    ------------------------
                                                                                    -      file           -
                                                                                    ------------------------
                                                                                    -      write()     -
                                                                                    ------------------------

The *docrules* will do the parsing (*xml.etree* very effective)
and create the reader and the writer instance.
I want to create 2 others classes (or more) more specific which have
more the knowledge about the XML documents structures.
*SpecificRuleReader*, *SpecificRuleWriter* which are deriving resp.
from Reader and Writer which hold resp. *getSpecificRules*() (use of 
get('/tag1/tag2/tag3/specificTagRules') and a* writeSpecificRules*():

-----------------------------                      
---------------------------------
       reader                                             writer
-----------------------------                      
---------------------------------
             ^                                                   ^
              |                                                    |
-------------------------------                    
-----------------------------------
*SpecificRuleReader* *SpecificRulesWriter*
-------------------------------                    
-----------------------------------
*getSpecificRules*() *writeSpecificRules()*
--------------------------------                   
--------------------------------------

My purpose is to separate as far as possible XML representation from
core classes. I will have certainly more SpecificrulesReader/Writer
classes becauses the document is huge and several discipline rules
will be adressed. I don't want necessarily have 2 big classes which
know everything about XML document because I will have too many
methods.

So, for if anybody has this kind of experience or any design pattern idea,
I will be enchant?.

Regards
Karim

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From vbuell at gmail.com  Thu Aug 26 08:56:47 2010
From: vbuell at gmail.com (Volodymyr Buell)
Date: Thu, 26 Aug 2010 09:56:47 +0300
Subject: [Tutor] (no subject)
In-Reply-To: 
References: 
Message-ID: 

Hi Roelof,
The problem is in quotation marks. Please use plain double instead of
curly quotes. (That's a common issue when you copy-paste the code from
pdf/doc)

On Thu, Aug 26, 2010 at 9:25 AM, Roelof Wobben  wrote:
> Hello,
>
> I have this exercise :
>
>
> Try each of the following formatted string operations in a Python shell and
> record the results:
>
> ?%s %d %f? % (5, 5, 5)
> ?%-.2f? % 3
> ?%-10.2f%-10.2f? % (7, 1.0/2)
> print ? $%5.2fn $%5.2fn $%5.2f? % (3, 4.5, 11.2)
>
>
> But if I try in a python 2.7 IDLE enviroment I get this :
>
>>>> %s %d %f % (5, 5, 5)
> SyntaxError: invalid syntax
>>>> print ?%s %d %f? % (5, 5, 5)
> SyntaxError: invalid syntax
>
> Roelof
>
>
> _______________________________________________
> Tutor maillist ?- ?Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>

-- 
Thanks,
Volodymyr

From alan.gauld at btinternet.com  Thu Aug 26 10:22:20 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 26 Aug 2010 09:22:20 +0100
Subject: [Tutor] why does this fail
References: , ,
	<4C74F01B.7030502@compuscan.co.za>,
	,
	,
	<427851.46740.qm@web86706.mail.ird.yahoo.com>
	
Message-ID: 

"Roelof Wobben"  wrote

> then I have a problem.
>
> Im following this book : 
> http://openbookproject.net/thinkcs/python/english2e/
> which is the first link  in the beginners tutorial page.
>
> And it's talking about the string modules.

So it is which is quite bizarre since it is using Python 2.5!

The string module is deprecated and in Python v3 has had most of the
functions removed. Do not use ther string module functions, use the 
string
methods instead. It is usually a simple translation from

string.function(aString, other args...)

to

aString.method(otherargs...)

You can check the documentation for the string methods using

>>> help(str)

I don't want to put you off the tutorial because it is quite a good 
tutor,
but I never noticed it was still promoting the use of the string 
module
before - very odd!

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From alan.gauld at btinternet.com  Thu Aug 26 10:32:55 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 26 Aug 2010 09:32:55 +0100
Subject: [Tutor] Trouble with exercise regarding classes
References: 
	
Message-ID: 


"Andrew Martin"  wrote

> I want to compare zenith, a floating point number, with the current 
> y value?
> I thought the current y value could be retrieved by Projectile.getY.

Projectile.getY is a reference to the getY method of the Projectile 
class.
(See the separate thread on function objects for more on this topic)

You want to execute the method so you need parens on the end.

But, you also want to execute it for the cball instance.
You have already done this earlier in your code, here:

>>>>    while cball.getY() >= 0:

So you just need to make the if test compatible with that:


>>         if Projectile.getY > zenith:

becomes

            if cball.getY() > zenith:

And similarly for the assignment

>>>>            zenith = Projectile.getY()
becomes
                    zenith = cball.getY()


As an aside you can do this using Projectile, but its bad practice:

Projectile.getY(cball)

This explicitly provides the self argument instead of Python doing
it for you when you use the instance. We can use this technique when
calling inherited methods inside a class method definition. Anywhere
else its best to use the instance to call a method.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From fomcl at yahoo.com  Thu Aug 26 11:46:38 2010
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Thu, 26 Aug 2010 02:46:38 -0700 (PDT)
Subject: [Tutor] wx to convert Group 4 Tifs to Gifs
Message-ID: <183499.75004.qm@web110701.mail.gq1.yahoo.com>

Hi,

I have a small application, written in Tkinter. It is supposed to display a tif 
image, among other things. The problem is, PIL won't?decode group 4 Tifs (G4 
TIF).
The tifs that I have are about 125kb and contain two pages per file. They're 
scanned, monochrome files. I need the second page of the tif, more specifically 
the lower half 

of the second page. I will have 5000-6000 tifs eventually, to manual conversion 
is not an option.

While googling around, I found many other people who faced the same problem. 
Since I cannot download executables here, I decided to use wx.
Ideally, I'd like an object that can be handled with Tkinter.PhotoImage, but I'm 
also very happy with a simple program that converts from G4 tif to Gif.
I have zero knowledge from wx. Therefroe, I'd really appreciate some pointers as 
to how to make the program below work.

import wx, os
def tif2gif(infile):
? """ This does *not* work """
? SECONDPAGE = 1
? outfile = os.path.splitext(infile[0] + ".gif")
? image?? = wx.Image(name = infile, type = wx.BITMAP_TYPE_TIF, index = 
SECONDPAGE) 

? bitmap? = wx.BitmapFromImage(self.image)
? bitmap.SaveFile(outfile", wx.BITMAP_TYPE_GIF)
tif2gif(infile? = "d:/temp/somefile.tif")
?
Thank you very much in advance!
?
Cheers!!
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 cwitts at compuscan.co.za  Thu Aug 26 12:13:34 2010
From: cwitts at compuscan.co.za (Christian Witts)
Date: Thu, 26 Aug 2010 12:13:34 +0200
Subject: [Tutor] wx to convert Group 4 Tifs to Gifs
In-Reply-To: <183499.75004.qm@web110701.mail.gq1.yahoo.com>
References: <183499.75004.qm@web110701.mail.gq1.yahoo.com>
Message-ID: <4C763E4E.9000400@compuscan.co.za>

On 26/08/2010 11:46, Albert-Jan Roskam wrote:
> Hi,
> I have a small application, written in Tkinter. It is supposed to 
> display a tif image, among other things. The problem is, PIL 
> won't decode group 4 Tifs (G4 TIF).
> The tifs that I have are about 125kb and contain two pages per file. 
> They're scanned, monochrome files. I need the second page of the tif, 
> more specifically the lower half
> of the second page. I will have 5000-6000 tifs eventually, to manual 
> conversion is not an option.
> While googling around, I found many other people who faced the same 
> problem. Since I cannot download executables here, I decided to use wx.
> Ideally, I'd like an object that can be handled with 
> Tkinter.PhotoImage, but I'm also very happy with a simple program that 
> converts from G4 tif to Gif.
> I have zero knowledge from wx. Therefroe, I'd really appreciate some 
> pointers as to how to make the program below work.
> import wx, os
> def tif2gif(infile):
>   """ This does *not* work """
>   SECONDPAGE = 1
>   outfile = os.path.splitext(infile[0] + ".gif")
>   image   = wx.Image(name = infile, type = wx.BITMAP_TYPE_TIF, index = 
> SECONDPAGE)
>   bitmap  = wx.BitmapFromImage(self.image)
>   bitmap.SaveFile(outfile", wx.BITMAP_TYPE_GIF)
> tif2gif(infile  = "d:/temp/somefile.tif")
>
> Thank you very much in advance!
>
> Cheers!!
> 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?
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>    

Any chance you run Linux ?  If so you can do it with convert like

for fn in ./*.tif; do convert $fn $fn.jpg; done
for fn in ./*-1.jpg; do convert $fn $fn.gif; done

The reason for the 2 step conversion is tif -> gif seems to only give 
you access to the first page.

-- 
Kind Regards,
Christian Witts



From steve at pearwood.info  Thu Aug 26 14:05:59 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 26 Aug 2010 22:05:59 +1000
Subject: [Tutor] continuous running of a method
In-Reply-To: <130420949513.20100825222703@columbus.rr.com>
References: <4C720056.3070309@gmail.com>
	<201008252037.54541.steve@pearwood.info>
	<130420949513.20100825222703@columbus.rr.com>
Message-ID: <201008262206.00309.steve@pearwood.info>

On Thu, 26 Aug 2010 12:27:03 pm R. Alan Monroe wrote:
> > Any modern multi-tasking operating system will ensure than a while
> > loop doesn't kill your computer's responsiveness. A decent
> > operating system will still remain responsive even at 100% CPU
> > usage. Even Windows does that!
>
> Opinions vary. If you try this on a laptop, the end user will be
> quite annoyed to see their battery drop to zero, their cooling fans
> go into overdrive, and to receive first degree burns on their hands
> and/or lap.

Hmmm. Well, there is that. But the OS will remain responsive while 
you're looking for the burn cream for your lap!


> Busywaiting my cpu makes your program an instant candidate for
> immediate deletion. Maybe that's just me :)

Ah, I take it you've deleted the Flash plugin then? Or maybe it's just 
the Linux version that periodically goes nuts.



-- 
Steven D'Aprano

From steve at pearwood.info  Thu Aug 26 16:44:29 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 27 Aug 2010 00:44:29 +1000
Subject: [Tutor] design of Point class
In-Reply-To: <1D673F86DDA00841A1216F04D1CE70D6426032E02B@EXCH2.nws.oregonstate.edu>
References: <1D673F86DDA00841A1216F04D1CE70D6426032DE54@EXCH2.nws.oregonstate.edu>
	<201008211124.29475.steve@pearwood.info>
	<1D673F86DDA00841A1216F04D1CE70D6426032E02B@EXCH2.nws.oregonstate.edu>
Message-ID: <201008270044.29694.steve@pearwood.info>

On Thu, 26 Aug 2010 07:29:42 am Gregory, Matthew wrote:

> I hope you'll suffer me one more question on this thread.  In
> thinking about creating other distance methods (as you suggest), how
> best to create a generic enough interface, so that ANY distance
> metric could be used.  It seems like coding the Point class with
> multiple distance methods is not very flexible, especially if you
> wanted to iterate over those methods for any two points, e.g.
>
> class Point(tuple):
>     def euclidean_distance(self, other):
>         ...
>     def manhattan_distance(self, other):
>         ...
>     def any_other_distance(self, other):
>         ...
>
> Would this be a place for a generic get_distance with a
> DistanceMetric subclass as a parameter, e.g.
>
> class DistanceMetric(object):
>     def distance(self, p1, p2):
>         assert 0, 'Must be defined in subclasses'
>
> class EuclideanDistMetric(DistanceMetric):
>     def distance(self, p1, p2):
>         ...
>
> class Point(tuple):
>     def get_distance(self, other, metric):
>         distance = metric.distance(self, other)
>         return distance


That could work, but it seems like a terribly heavyweight solution for a 
lightweight problem to me.

It doesn't save you any work -- you still have to code the distance 
method, but instead of creating a single method, you have to create an 
entire class. So it's more work.

I believe the simplest solution is to use the bound methods as first 
class functions:

pt = Point(23, 42)
# choose a distance 
if today == "Tuesday":
    dist = pt.manhattan_distance
else:
    dist = pt.euclidean_distance
for other in list_of_other_points:
    print(dist(other))



-- 
Steven D'Aprano

From rwobben at hotmail.com  Thu Aug 26 17:41:25 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Thu, 26 Aug 2010 15:41:25 +0000
Subject: [Tutor] question about lists and doctest
Message-ID: 


hello, 

 

I have this programm 

 

#  Add your doctests here:
"""
  >>> a_list[3]
  42
  >>> a_list[6]
  'Ni!'
  >>> len(a_list)
  8
"""
a_list = ['test', 'test','test',42,'test','test','Ni!','test']
print a_list[3]
print a_list[6]
print len(a_list)

if __name__ == '__main__':
    import doctest
    doctest.testmod()

 

If I change lets say 42 to 16 then the doctest fails with 

 

Expecting 

 

42 

 

Got 

 

16.

 

 

How does doctest now which values are right or not ?

 

Roelof

 

 

 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nitin.162 at gmail.com  Thu Aug 26 18:40:08 2010
From: nitin.162 at gmail.com (Nitin Das)
Date: Thu, 26 Aug 2010 22:10:08 +0530
Subject: [Tutor] question about lists and doctest
In-Reply-To: 
References: 
Message-ID: 

The doctest module searches for pieces of text that look like interactive
Python sessions, and then executes those sessions to verify that they work
exactly as shown.
Here ur a_list[3] in docstring is 42 then doctest expects it to be 42 for
success. Since u changed 42 to 16 then it is not = 42 as per the
a_list[3]=42 in docstring hence it raises error.

--nitin

On Thu, Aug 26, 2010 at 9:11 PM, Roelof Wobben  wrote:

>  hello,
>
> I have this programm
>
> #  Add your doctests here:
> """
>   >>> a_list[3]
>   42
>   >>> a_list[6]
>   'Ni!'
>   >>> len(a_list)
>   8
> """
> a_list = ['test', 'test','test',42,'test','test','Ni!','test']
> print a_list[3]
> print a_list[6]
> print len(a_list)
> if __name__ == '__main__':
>     import doctest
>     doctest.testmod()
>
> If I change lets say 42 to 16 then the doctest fails with
>
> Expecting
>
> 42
>
> Got
>
> 16.
>
>
> How does doctest now which values are right or not ?
>
> Roelof
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From davidheiserca at gmail.com  Thu Aug 26 18:54:27 2010
From: davidheiserca at gmail.com (davidheiserca at gmail.com)
Date: Thu, 26 Aug 2010 09:54:27 -0700
Subject: [Tutor] SSH session problems with network devices
Message-ID: <1D45067A27EE4D98B497585063D18BF0@dheiser>


I have Python code that opens a telnet session with a network device and performs a multitude of tasks. Now, I am trying to establish and maintain an SSH connection as an alternative to telent. My research has found that the SSH implementation some network device manufacturers use is not consistent and the problems I'm having are common. I'm hoping to find someone who has found a solution.

I am using Paramiko, but I am not limited to that. I am also exploring Appgate "MindTerm" http://www.appgate.com/index/products/mindterm/.

My Paramiko code works correctly when connecting with a Linux system. But when I connect with a router, the connection is dropped immediately after a command is exectued, so it isn't possible to send a sequence of interrelated commands. 

For example, I want to change the screen paging value so that complete results from the next command will stream back without stopping for "--MORE--". Or I need to change the user level and enter a password followed by a series of commands.

I have reviewed relevant postings from on the Paramiko list, but there are no clear solutions.

http://www.lag.net/pipermail/paramiko/2010-June/001322.html
http://www.lag.net/pipermail/paramiko/2010-June/001320.html
http://www.lag.net/pipermail/paramiko/2010-March/001284.html

I have tried three methods, unsuccessfully, for establishing and maintaining an SSH connection. My test code is at http://pastebin.ca/1918235. I would appreciate any help. I'm open to a non-Paramiko solution, but it has to plug-and-play with the Python utility code I already have. And I hope to keep it simple.

Thank you,
David Heiser
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rwobben at hotmail.com  Thu Aug 26 21:02:38 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Thu, 26 Aug 2010 19:02:38 +0000
Subject: [Tutor] exercise problem
Message-ID: 


Hello, 
 
I have this exercise:
 
Lists can be used to represent mathematical vectors. In this exercise and several that follow you will write functions to perform standard operations on vectors. Create a file named vectors.py and write Python code to make the doctests for each function pass.
Write a function add_vectors(u, v) that takes two lists of numbers of the same length, and returns a new list containing the sums of the corresponding elements of each.


def add_vectors(u, v):
    """
      >>> add_vectors([1, 0], [1, 1])
      [2, 1]
      >>> add_vectors([1, 2], [1, 4])
      [2, 6]
      >>> add_vectors([1, 2, 1], [1, 4, 3])
      [2, 6, 4]
      >>> add_vectors([11, 0, -4, 5], [2, -4, 17, 0])
      [13, -4, 13, 5]
    """

add_vectors should pass the doctests above

 

I think that u is the name of the new list and v is the number which represent the number which must be eveluated.

 

Is this right or do I mis understood the exercise ?

 

Roelof

 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From emile at fenx.com  Thu Aug 26 22:21:22 2010
From: emile at fenx.com (Emile van Sebille)
Date: Thu, 26 Aug 2010 13:21:22 -0700
Subject: [Tutor] exercise problem
In-Reply-To: 
References: 
Message-ID: 

On 8/26/2010 12:02 PM Roelof Wobben said...
>
> Hello,
>
> I have this exercise:
>
> Lists can be used to represent mathematical vectors. In this exercise and several that follow you will write functions to perform standard operations on vectors. Create a file named vectors.py and write Python code to make the doctests for each function pass.
> Write a function add_vectors(u, v) that takes two lists of numbers of the same length, and returns a new list containing the sums of the corresponding elements of each.
>
>
> def add_vectors(u, v):
>      """
>        >>>  add_vectors([1, 0], [1, 1])
>        [2, 1]
>        >>>  add_vectors([1, 2], [1, 4])
>        [2, 6]
>        >>>  add_vectors([1, 2, 1], [1, 4, 3])
>        [2, 6, 4]
>        >>>  add_vectors([11, 0, -4, 5], [2, -4, 17, 0])
>        [13, -4, 13, 5]
>      """
>
> add_vectors should pass the doctests above
>
>
>
> I think that u is the name of the new list and v is the number which represent the number which must be eveluated.

No.  u,v are the parameters names for the two lists of numbers of the 
same length.  So in the example add_vectors([1, 0], [1, 1]), u will take 
on the value [1, 0] and v the value [1, 1].

HTH,

Emile


>
>
>
> Is this right or do I mis understood the exercise ?
>
>
>
> Roelof
>
>
>   		 	   		
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



From prologic at shortcircuit.net.au  Fri Aug 27 00:28:31 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Fri, 27 Aug 2010 08:28:31 +1000
Subject: [Tutor] SSH session problems with network devices
In-Reply-To: <1D45067A27EE4D98B497585063D18BF0@dheiser>
References: <1D45067A27EE4D98B497585063D18BF0@dheiser>
Message-ID: 

On Fri, Aug 27, 2010 at 2:54 AM,   wrote:
> My Paramiko?code?works correctly when connecting with a Linux system. But
> when I connect with a router, the connection is dropped immediately after a
> command is exectued, so it isn't possible to send a sequence of interrelated
> commands.

What Router is this ? What OS does it run ?

I may have some experience with this as I often ssh into various
networking devices including Linux servers and systems, etc...

cheers
James


-- 
-- James Mills
--
-- "Problems are solved by method"

From prologic at shortcircuit.net.au  Fri Aug 27 00:47:58 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Fri, 27 Aug 2010 08:47:58 +1000
Subject: [Tutor] SSH session problems with network devices
In-Reply-To: <6CC953C65A4043068FF51B9B0E0B69EA@dheiser>
References: <1D45067A27EE4D98B497585063D18BF0@dheiser>
	
	<6CC953C65A4043068FF51B9B0E0B69EA@dheiser>
Message-ID: 

On Fri, Aug 27, 2010 at 8:42 AM,   wrote:
>
> I'm running tests on - Cisco IOS Software, s72033_rp Software
> (s72033_rp-ADVIPSERVICESK9_WAN-M), Version 12.2
>
> It's running SSHv2.0
>
> My solution should be portable to other vendor/models.

Can you "normally" ssh into your Cisco routers and be presented
with a shell of some kind ?

cheers
James

PS: Please post to the list.

-- 
-- James Mills
--
-- "Problems are solved by method"

From alan.gauld at btinternet.com  Fri Aug 27 00:54:19 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 26 Aug 2010 23:54:19 +0100
Subject: [Tutor] exercise problem
References: 
Message-ID: 

"Roelof Wobben"  wrote

> Write a function add_vectors(u, v) that takes two lists of numbers

> I think that u is the name of the new list and v is the number which
> represent the number which must be eveluated.

No. It sounds like you don't really understand the basic concepts
behind functions yet. Try reading the Modules and Functions topic
in my tutorial. See if that clarifies things for you. Getting these 
basic
concepts right at the beginning is very important, don't try to rush 
it.

If confused by one tutorial reading an alternative explanation can
often help - at least it does for me! :-)

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From steve at pearwood.info  Fri Aug 27 01:39:41 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 27 Aug 2010 09:39:41 +1000
Subject: [Tutor] SSH session problems with network devices
In-Reply-To: <1D45067A27EE4D98B497585063D18BF0@dheiser>
References: <1D45067A27EE4D98B497585063D18BF0@dheiser>
Message-ID: <201008270939.42529.steve@pearwood.info>

On Fri, 27 Aug 2010 02:54:27 am davidheiserca at gmail.com wrote:
> I have Python code that opens a telnet session with a network device
> and performs a multitude of tasks. Now, I am trying to establish and
> maintain an SSH connection as an alternative to telent. My research
> has found that the SSH implementation some network device
> manufacturers use is not consistent and the problems I'm having are
> common. I'm hoping to find someone who has found a solution.

Hi David,

you may be better off on a more senior discussion list than this. It's 
not really a beginners question, and you may benefit from having a lit 
more eyes on your question :)

Have you tried python-list at python.org or its newsgroup mirror 
comp.lang.python ?

http://mail.python.org/mailman/listinfo/python-list



-- 
Steven D'Aprano

From prologic at shortcircuit.net.au  Fri Aug 27 01:40:30 2010
From: prologic at shortcircuit.net.au (James Mills)
Date: Fri, 27 Aug 2010 09:40:30 +1000
Subject: [Tutor] SSH session problems with network devices
In-Reply-To: 
References: <1D45067A27EE4D98B497585063D18BF0@dheiser>
	
	<6CC953C65A4043068FF51B9B0E0B69EA@dheiser>
	
	
Message-ID: 

On Fri, Aug 27, 2010 at 9:13 AM,   wrote:
>
> Yes. No problem. The point is that I have Python programs that normally
> access these devices by telnet to complex tasks. I have to find a way to use
> SSH to replace the telnet in my code.

I actually have no experience with Cisco devices, but the question
that remains to be seen really is; "Why are your Cisco devices
terminating the SSH connection after the first command ?"

This actually might be a terminal or some kind of configuration issue
(if you can normally ssh into your Cisco devices and get a
prompt/terminal). Ssh'ing and executing remote commands might be
interpreted differently by the Cisco ssh/shell/etc.

It might be worth your while looking into this as it'll have nothing
at all to do with Python or Paramiko..

cheers
James

-- 
-- James Mills
--
-- "Problems are solved by method"

From wallenpb at gmail.com  Fri Aug 27 02:15:31 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Thu, 26 Aug 2010 19:15:31 -0500
Subject: [Tutor] question about import statement
Message-ID: 

I was experimenting with Tk today, just trying it out.   I found this
example of a very simple "hello world" button click program.  This is it.

from tkinter import *
from tkinter import ttk
root = Tk()
button = ttk.Button(root, text="Hello World").grid()
root.mainloop()

What I don't understand is why it is necessary to run that import statement
twice.  Shouldn't import * bring everything in from tkinter?


Just wondering,

Bill Allen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From wallenpb at gmail.com  Fri Aug 27 03:56:16 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Thu, 26 Aug 2010 20:56:16 -0500
Subject: [Tutor] question about import statement
In-Reply-To: <4C770A7F.7090504@aim.com>
References: 
	<4C770A7F.7090504@aim.com>
Message-ID: 

On Thu, Aug 26, 2010 at 7:44 PM, Corey Richardson  wrote:

> Why don't you try it out without the "from tkinter import ttk" statement,
> and see if it works?
>
> Bill Allen wrote:
>
>> I was experimenting with Tk today, just trying it out.   I found this
>> example of a very simple "hello world" button click program.  This is it.
>>
>> from tkinter import *
>> from tkinter import ttk
>>
>> root = Tk()
>> button = ttk.Button(root, text="Hello World").grid()
>> root.mainloop()
>> What I don't understand is why it is necessary to run that import
>> statement twice.  Shouldn't import * bring everything in from tkinter?
>>
>>
>> Just wondering,
>>
>> Bill Allen
>>
>> ------------------------------------------------------------------------
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From wallenpb at gmail.com  Fri Aug 27 04:16:36 2010
From: wallenpb at gmail.com (Bill Allen)
Date: Thu, 26 Aug 2010 21:16:36 -0500
Subject: [Tutor] question about import statement
In-Reply-To: 
References: 
	<4C770A7F.7090504@aim.com>
	
Message-ID: 

>
> On Thu, Aug 26, 2010 at 7:44 PM, Corey Richardson  wrote:
>
>> Why don't you try it out without the "from tkinter import ttk" statement,
>> and see if it works?
>>
>> Bill Allen wrote:
>>
>>> I was experimenting with Tk today, just trying it out.   I found this
>>> example of a very simple "hello world" button click program.  This is it.
>>>
>>> from tkinter import *
>>> from tkinter import ttk
>>>
>>> root = Tk()
>>> button = ttk.Button(root, text="Hello World").grid()
>>> root.mainloop()
>>> What I don't understand is why it is necessary to run that import
>>> statement twice.  Shouldn't import * bring everything in from tkinter?
>>>
>>>
Oops, sorry about the previous empty post.

I did try that and of course it gave an error because it was necessary.  I
just did not know why.   However, I later found an explanation on the web.
Here it is:

*from tkinter import *
from tkinter import ttk

These two lines tell Python that our program needs two modules. The first,
"tkinter", is the standard binding to Tk, which when loaded also causes the
existing Tk library on your system to be loaded. The second, "ttk", is
Python's binding to the newer "themed widgets" that were added to Tk in 8.5.
*


-Bill
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From hugo.yoshi at gmail.com  Fri Aug 27 04:29:06 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Thu, 26 Aug 2010 21:29:06 -0500
Subject: [Tutor] question about import statement
In-Reply-To: 
References: 
	<4C770A7F.7090504@aim.com>
	
	
Message-ID: 

On Thu, Aug 26, 2010 at 9:16 PM, Bill Allen  wrote:
>
> I did try that and of course it gave an error because it was necessary.? I
> just did not know why.?? However, I later found an explanation on the web.
> Here it is:
>
> from tkinter import *
> from tkinter import ttk
>
> These two lines tell Python that our program needs two modules. The first,
> "tkinter", is the standard binding to Tk, which when loaded also causes the
> existing Tk library on your system to be loaded. The second, "ttk", is
> Python's binding to the newer "themed widgets" that were added to Tk in 8.5.
>

yeah, "from package import *" doesn't actually import every name from
a module. For example, by default, names starting with an underscore
are not imported. Alternatively, if you have a variable named __all__
in your module, and it's a list of names, only those names in the list
actually get imported when you do a "from x import *"

Hugo

From gregbair at gmail.com  Fri Aug 27 06:18:10 2010
From: gregbair at gmail.com (Greg Bair)
Date: Fri, 27 Aug 2010 00:18:10 -0400
Subject: [Tutor] question about import statement
In-Reply-To: 
References: 	<4C770A7F.7090504@aim.com>		
	
Message-ID: <4C773C82.8070902@gmail.com>

On 08/26/2010 10:29 PM, Hugo Arts wrote:
> On Thu, Aug 26, 2010 at 9:16 PM, Bill Allen  wrote:
>>
>> I did try that and of course it gave an error because it was necessary.  I
>> just did not know why.   However, I later found an explanation on the web.
>> Here it is:
>>
>> from tkinter import *
>> from tkinter import ttk
>>
>> These two lines tell Python that our program needs two modules. The first,
>> "tkinter", is the standard binding to Tk, which when loaded also causes the
>> existing Tk library on your system to be loaded. The second, "ttk", is
>> Python's binding to the newer "themed widgets" that were added to Tk in 8.5.
>>
> 
> yeah, "from package import *" doesn't actually import every name from
> a module. For example, by default, names starting with an underscore
> are not imported. Alternatively, if you have a variable named __all__
> in your module, and it's a list of names, only those names in the list
> actually get imported when you do a "from x import *"
> 
> Hugo
Why would the person who wrote this package choose to do it this way,
though?  If it was something that people would use and not just an
internal name, why hide it this way?

Greg

From hugo.yoshi at gmail.com  Fri Aug 27 07:05:55 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Fri, 27 Aug 2010 00:05:55 -0500
Subject: [Tutor] question about import statement
In-Reply-To: <4C773C82.8070902@gmail.com>
References: 
	<4C770A7F.7090504@aim.com>
	
	
	
	<4C773C82.8070902@gmail.com>
Message-ID: 

On Thu, Aug 26, 2010 at 11:18 PM, Greg Bair  wrote:
> On 08/26/2010 10:29 PM, Hugo Arts wrote:
>> On Thu, Aug 26, 2010 at 9:16 PM, Bill Allen  wrote:
>>>
>>> I did try that and of course it gave an error because it was necessary. ?I
>>> just did not know why. ? However, I later found an explanation on the web.
>>> Here it is:
>>>
>>> from tkinter import *
>>> from tkinter import ttk
>>>
>>> These two lines tell Python that our program needs two modules. The first,
>>> "tkinter", is the standard binding to Tk, which when loaded also causes the
>>> existing Tk library on your system to be loaded. The second, "ttk", is
>>> Python's binding to the newer "themed widgets" that were added to Tk in 8.5.
>>>
>>
>> yeah, "from package import *" doesn't actually import every name from
>> a module. For example, by default, names starting with an underscore
>> are not imported. Alternatively, if you have a variable named __all__
>> in your module, and it's a list of names, only those names in the list
>> actually get imported when you do a "from x import *"
>>
>> Hugo
> Why would the person who wrote this package choose to do it this way,
> though? ?If it was something that people would use and not just an
> internal name, why hide it this way?
>

http://docs.python.org/tutorial/modules.html#importing-from-a-package

It's a practical thing, mostly for packages. When you import * from a
package 'x', how does python know all the modules present in the
package? You would hope that it somehow goes into the filesystem and
figures out all the files inside the 'x' directory, but this could
take a long time and have unwanted side-effects. So, you have to
specify the __all__ variable inside your __init__.py file, and that
way import * will know what to do. Alternatively, you can just import
all the modules inside __init__.py, since any names that are inside
__init__.py will also be loaded.

Hugo

From steve at pearwood.info  Fri Aug 27 08:42:28 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 27 Aug 2010 16:42:28 +1000
Subject: [Tutor] question about import statement
In-Reply-To: <4C773C82.8070902@gmail.com>
References: 
	
	<4C773C82.8070902@gmail.com>
Message-ID: <201008271642.29781.steve@pearwood.info>

On Fri, 27 Aug 2010 02:18:10 pm Greg Bair wrote:
> > yeah, "from package import *" doesn't actually import every name
> > from a module. For example, by default, names starting with an
> > underscore are not imported. Alternatively, if you have a variable
> > named __all__ in your module, and it's a list of names, only those
> > names in the list actually get imported when you do a "from x
> > import *"
> >
> > Hugo
>
> Why would the person who wrote this package choose to do it this way,
> though? ?If it was something that people would use and not just an
> internal name, why hide it this way?

I can't speak for the tkinter package, but in my own packages I like to 
distinguish between three broad categories of functions (and classes):

* public functions that are part of the main functionality of the 
package;

* public functions that are associated with the package, but not 
directly part of the package functionality (e.g. helper functions, 
support functions, unittests, experimental code that is provided but 
not supported, utilities, decorators, etc.);

* private functions that I reserve the right to change or remove without 
notice.

Only the first goes into __all__. Only the third start with an 
underscore.



-- 
Steven D'Aprano

From alan.gauld at btinternet.com  Fri Aug 27 09:43:08 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 27 Aug 2010 08:43:08 +0100
Subject: [Tutor] question about import statement
References: <4C770A7F.7090504@aim.com>
	
Message-ID: 


"Bill Allen"  wrote

> *from tkinter import *
> from tkinter import ttk
>
> These two lines tell Python that our program needs two modules. The 
> first,
> "tkinter", is the standard binding to Tk, which when loaded also 
> causes the
> existing Tk library on your system to be loaded. The second, "ttk", 
> is
> Python's binding to the newer "themed widgets" that were added to Tk 
> in 8.5.

Yes, they are both modules so must both be imported. You could also 
do:

import tkinter as tk
import tkinter.ttk as ttk

which is the style I tend to use for my own code.

HTH,

Alan G 



From __peter__ at web.de  Fri Aug 27 09:45:39 2010
From: __peter__ at web.de (Peter Otten)
Date: Fri, 27 Aug 2010 09:45:39 +0200
Subject: [Tutor] question about import statement
References: 
	<4C770A7F.7090504@aim.com>
	
	
	
	<4C773C82.8070902@gmail.com>
Message-ID: 

Greg Bair wrote:

> On 08/26/2010 10:29 PM, Hugo Arts wrote:
>> On Thu, Aug 26, 2010 at 9:16 PM, Bill Allen  wrote:
>>>
>>> I did try that and of course it gave an error because it was necessary. 
>>> I
>>> just did not know why.   However, I later found an explanation on the
>>> web. Here it is:
>>>
>>> from tkinter import *
>>> from tkinter import ttk
>>>
>>> These two lines tell Python that our program needs two modules. The
>>> first, "tkinter", is the standard binding to Tk, which when loaded also
>>> causes the existing Tk library on your system to be loaded. The second,
>>> "ttk", is Python's binding to the newer "themed widgets" that were added
>>> to Tk in 8.5.
>>>
>> 
>> yeah, "from package import *" doesn't actually import every name from
>> a module. For example, by default, names starting with an underscore
>> are not imported. Alternatively, if you have a variable named __all__
>> in your module, and it's a list of names, only those names in the list
>> actually get imported when you do a "from x import *"
>> 
>> Hugo
> Why would the person who wrote this package choose to do it this way,
> though?  If it was something that people would use and not just an
> internal name, why hide it this way?

There are many programs out there that don't use ttk. For those it would be 
a waste of time and memory if the tkinter.ttk module were imported 
automatically. If you modify your example to

from tkinter import *
root = Tk()
button = Button(root, text="Hello World").grid()
root.mainloop()

it will still work (but maybe look a little different). If the ttk import 
were automatic the above script might not work on machines that don't have 
"themed widgets" even though it doesn't use them. 

In general it is good practice that modules introduce as few dependencies as 
possible.

Peter


From rwobben at hotmail.com  Fri Aug 27 12:23:06 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Fri, 27 Aug 2010 10:23:06 +0000
Subject: [Tutor] exercise problem
In-Reply-To: 
References: ,
	,
	
Message-ID: 



 


From: rwobben at hotmail.com
To: alan.gauld at btinternet.com
Subject: RE: [Tutor] exercise problem
Date: Fri, 27 Aug 2010 07:04:39 +0000





 
> To: tutor at python.org
> From: alan.gauld at btinternet.com
> Date: Thu, 26 Aug 2010 23:54:19 +0100
> Subject: Re: [Tutor] exercise problem
> 
> "Roelof Wobben"  wrote
> 
> > Write a function add_vectors(u, v) that takes two lists of numbers
> 
> > I think that u is the name of the new list and v is the number which
> > represent the number which must be eveluated.
> 
> No. It sounds like you don't really understand the basic concepts
> behind functions yet. Try reading the Modules and Functions topic
> in my tutorial. See if that clarifies things for you. Getting these 
> basic
> concepts right at the beginning is very important, don't try to rush 
> it.
> 
> If confused by one tutorial reading an alternative explanation can
> often help - at least it does for me! :-)
> 
> -- 
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> 
> 
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

Hello, 
 
I read your page and I think I understand the basic concepts.
What I don't see is what s and v represent.
 
My new idea is that u is the number which must be calculated and v is the vector which containts the outcome or u is the outcome of the first numbers and v the outcome of the second numbers.
 
Roelof
 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From fal at libero.it  Fri Aug 27 15:55:19 2010
From: fal at libero.it (Francesco Loffredo)
Date: Fri, 27 Aug 2010 15:55:19 +0200
Subject: [Tutor] exercise problem
In-Reply-To: 
References: ,
	,
	
	
Message-ID: <4C77C3C7.5090809@libero.it>

On 27/08/2010 12.23, Roelof Wobben wrote:
> ------------------------------------------------------------------------
> From: rwobben at hotmail.com
> To: alan.gauld at btinternet.com
> Subject: RE: [Tutor] exercise problem
> Date: Fri, 27 Aug 2010 07:04:39 +0000
>
>  > To: tutor at python.org
>  > From: alan.gauld at btinternet.com
>  > Date: Thu, 26 Aug 2010 23:54:19 +0100
>  > Subject: Re: [Tutor] exercise problem
>  >
>  > "Roelof Wobben"  wrote
>  >
>  > > Write a function add_vectors(u, v) that takes two lists of numbers
>  >
>  > > I think that u is the name of the new list and v is the number which
>  > > represent the number which must be eveluated.
>  >
>  > No. It sounds like you don't really understand the basic concepts
>  > behind functions yet. it does for me! :-)
>  > ...
>  > --
>  > Alan Gauld
>  > Author of the Learn to Program web site
>  > http://www.alan-g.me.uk/
>
> Hello,
>
> I read your page and I think I understand the basic concepts.
> What I don't see is what s and v represent.
>
> My new idea is that u is the number which must be calculated and v is
> the vector which containts the outcome or u is the outcome of the first
> numbers and v the outcome of the second numbers.
>
> Roelof
Ok, let's take a deep breath and start from the beginning:

First: a vector is a (usually small) ordered set of numbers that are 
taken together to represent some mathematical entity or physical 
quantity. For example, (3,1,7) can mean the position of an object in 
space, relative to a Cartesian 3-dimensional axis system.

Second: the sum of two vectors is defined as a new vector, whose 
coordinates (the elements of the vectors) are each the sum of the same 
coordinates of the two given vectors:
v1 = (a, b, c)
v2 = (x, y, z)
v1 + v2 = (a+x, b+y, c+z)

That said, Alan tried to point you to the very important concept that:
Third: a function usually produces a result in itself, using the values 
given as arguments (those inside the parentheses, in your case u and v).
And that result is usually assigned to a variable, or used directly, by 
the funcion call itself:
new_vector = add_vectors(u, v)
or
print add_vectors(u, v)

The function you want to write should sum two of these vectors, that can 
be represented in Python as tuples (or as lists, as your exercise told you):
first_vector = (3, 1, 7)
second_vector = (7, -1, 13)
result = add_vectors(first_vector, second_vector)
print result
(10, 0, 20)

So, if you are asked to write a function that "takes two lists of 
numbers", I thought that those two lists were vectors, called u and v, 
and that the result of the sum, the "new vector", would be the result 
produced by the function.

Hope this made it clearer
Francesco
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.851 / Database dei virus: 271.1.1/3096 -  Data di rilascio: 08/26/10 20:34:00

From steve at pearwood.info  Fri Aug 27 16:15:15 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 28 Aug 2010 00:15:15 +1000
Subject: [Tutor] exercise problem
In-Reply-To: 
References: 
	
	
Message-ID: <201008280015.16028.steve@pearwood.info>

On Fri, 27 Aug 2010 08:23:06 pm Roelof Wobben wrote:
> > > Write a function add_vectors(u, v) that takes two lists of
> > > numbers
[...]
> My new idea is that u is the number which must be calculated and v is
> the vector which containts the outcome or u is the outcome of the
> first numbers and v the outcome of the second numbers. 

If you had a function called "add_numbers(x, y)", you would say that x 
and y are the numbers which are to be added. If you have a function 
called "add_vectors(u, v)", then u and v are the vectors to be added. 
Perhaps this example will help:


u = [1, 10, 100]
v = [2, 11, 111]
add_vectors(u, v)
=> [3, 21, 211]




-- 
Steven D'Aprano

From rwobben at hotmail.com  Fri Aug 27 16:38:23 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Fri, 27 Aug 2010 14:38:23 +0000
Subject: [Tutor] exercise problem
In-Reply-To: <201008280015.16028.steve@pearwood.info>
References: ,
	,
	,
	<201008280015.16028.steve@pearwood.info>
Message-ID: 


Oke, 

 

That's also the point Alan is making.

I try now to make  the function and puttting it on this maillist if it's ready.

 

Maybe I can learn more about efficient progamming or better way to do this.

 

Roelof


 
> From: steve at pearwood.info
> To: tutor at python.org
> Date: Sat, 28 Aug 2010 00:15:15 +1000
> Subject: Re: [Tutor] exercise problem
> 
> On Fri, 27 Aug 2010 08:23:06 pm Roelof Wobben wrote:
> > > > Write a function add_vectors(u, v) that takes two lists of
> > > > numbers
> [...]
> > My new idea is that u is the number which must be calculated and v is
> > the vector which containts the outcome or u is the outcome of the
> > first numbers and v the outcome of the second numbers. 
> 
> If you had a function called "add_numbers(x, y)", you would say that x 
> and y are the numbers which are to be added. If you have a function 
> called "add_vectors(u, v)", then u and v are the vectors to be added. 
> Perhaps this example will help:
> 
> 
> u = [1, 10, 100]
> v = [2, 11, 111]
> add_vectors(u, v)
> => [3, 21, 211]
> 
> 
> 
> 
> -- 
> Steven D'Aprano
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rwobben at hotmail.com  Fri Aug 27 17:05:43 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Fri, 27 Aug 2010 15:05:43 +0000
Subject: [Tutor] exercise problem
In-Reply-To: 
References: ,
	,
	,
	<201008280015.16028.steve@pearwood.info>,
	
Message-ID: 


Hello, 

 

My first try :

 

def add_vectors(u, v):
    """
      >>> add_vectors([1, 0], [1, 1])
      [2, 1]
      >>> add_vectors([1, 2], [1, 4])
      [2, 6]
      >>> add_vectors([1, 2, 1], [1, 4, 3])
      [2, 6, 4]
      >>> add_vectors([11, 0, -4, 5], [2, -4, 17, 0])
      [13, -4, 13, 5]
    """
    teller=1
    getal1=0
    getal2=0 
    while teller < len(u):
        getal1 = getal1 + u[teller,0] + v[teller,0]
        getal2 = getal2 + v[teller,1] + v[teller,1]
        teller=teller+1
    return uitkomst2[getal1, getal2]

uitkomst= []
vector= [[1,0], [1,1]]
v=vector[0]
u=vector[1]
uitkomst = add_vectors[u,v]

 

But now I get this error message :

 

Traceback (most recent call last):
File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 27, in 
uitkomst = add_vectors[u,v]
TypeError: 'function' object is not subscriptable
 
So it seems that I can't use vectors as a variable in a function.
 
Roelof
 
 
 

 


 


From: rwobben at hotmail.com
To: tutor at python.org
Subject: RE: [Tutor] exercise problem
Date: Fri, 27 Aug 2010 14:38:23 +0000




Oke, 
 
That's also the point Alan is making.
I try now to make  the function and puttting it on this maillist if it's ready.
 
Maybe I can learn more about efficient progamming or better way to do this.
 
Roelof

 
> From: steve at pearwood.info
> To: tutor at python.org
> Date: Sat, 28 Aug 2010 00:15:15 +1000
> Subject: Re: [Tutor] exercise problem
> 
> On Fri, 27 Aug 2010 08:23:06 pm Roelof Wobben wrote:
> > > > Write a function add_vectors(u, v) that takes two lists of
> > > > numbers
> [...]
> > My new idea is that u is the number which must be calculated and v is
> > the vector which containts the outcome or u is the outcome of the
> > first numbers and v the outcome of the second numbers. 
> 
> If you had a function called "add_numbers(x, y)", you would say that x 
> and y are the numbers which are to be added. If you have a function 
> called "add_vectors(u, v)", then u and v are the vectors to be added. 
> Perhaps this example will help:
> 
> 
> u = [1, 10, 100]
> v = [2, 11, 111]
> add_vectors(u, v)
> => [3, 21, 211]
> 
> 
> 
> 
> -- 
> Steven D'Aprano
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From wprins at gmail.com  Fri Aug 27 17:20:27 2010
From: wprins at gmail.com (Walter Prins)
Date: Fri, 27 Aug 2010 16:20:27 +0100
Subject: [Tutor] exercise problem
In-Reply-To: 
References: 
	
	
	<201008280015.16028.steve@pearwood.info>
	
	
Message-ID: 

Hi Roelof,

See below

On 27 August 2010 16:05, Roelof Wobben  wrote:

>
> uitkomst = add_vectors[u,v]
>
> But now I get this error message :
>
>
> Traceback (most recent call last):
> *File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 27, in
> *
>
> uitkomst = add_vectors[u,v]
>
> TypeError: 'function' object is not subscriptable
>
>
>
> So it seems that I can't use vectors as a variable in a function.
>
Carefully compare the syntax for calling your function (as in the doctest)
to what you've written above.  See the difference?  (Hint: check the type of
parentheses...)

The error message is giving you a hint -- a subscriptable item is something
like a list or array.  They use square brackets.  Function calls always use
(round) parentheses.  To python, it looks like you're trying to subcript the
function object "add_vectors", which obviously isn't possible.  Hence the
message.

Regards,

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From wprins at gmail.com  Fri Aug 27 17:20:27 2010
From: wprins at gmail.com (Walter Prins)
Date: Fri, 27 Aug 2010 16:20:27 +0100
Subject: [Tutor] exercise problem
In-Reply-To: 
References: 
	
	
	<201008280015.16028.steve@pearwood.info>
	
	
Message-ID: 

Hi Roelof,

See below

On 27 August 2010 16:05, Roelof Wobben  wrote:

>
> uitkomst = add_vectors[u,v]
>
> But now I get this error message :
>
>
> Traceback (most recent call last):
> *File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 27, in
> *
>
> uitkomst = add_vectors[u,v]
>
> TypeError: 'function' object is not subscriptable
>
>
>
> So it seems that I can't use vectors as a variable in a function.
>
Carefully compare the syntax for calling your function (as in the doctest)
to what you've written above.  See the difference?  (Hint: check the type of
parentheses...)

The error message is giving you a hint -- a subscriptable item is something
like a list or array.  They use square brackets.  Function calls always use
(round) parentheses.  To python, it looks like you're trying to subcript the
function object "add_vectors", which obviously isn't possible.  Hence the
message.

Regards,

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rwobben at hotmail.com  Fri Aug 27 17:33:46 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Fri, 27 Aug 2010 15:33:46 +0000
Subject: [Tutor]  exercise problem
In-Reply-To: 
References: ,
	,
	,
	<201008280015.16028.steve@pearwood.info>,
	,
	,
	,
	
Message-ID: 



 Hello,
 
Thanks for pointing this out.
 
I change it to this :
 
def add_vectors(u, v):
    """
      >>> add_vectors([1, 0], [1, 1])
      [2, 1]
      >>> add_vectors([1, 2], [1, 4])
      [2, 6]
      >>> add_vectors([1, 2, 1], [1, 4, 3])
      [2, 6, 4]
      >>> add_vectors([11, 0, -4, 5], [2, -4, 17, 0])
      [13, -4, 13, 5]
    """
    teller=1
    getal1=0
    getal2=0 
    while teller < len(u):
        getal1 = getal1 + u[teller,0] + v[teller,0]
        getal2 = getal2 + v[teller,1] + v[teller,1]
        teller=teller+1
        uitkomst2 = [getal1, getal2]
    return uitkomst2
 
uitkomst= []
vector= [[1,0], [1,1]]
v=vector[0]
u=vector[1]
print u, v
uitkomst = add_vectors(u,v)
print uitkomst          
 
But now Im getting this message :
 


Traceback (most recent call last):
File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 28, in 
uitkomst = add_vectors(u,v)
File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 17, in add_vectors
getal1 = getal1 + u[teller,0] + v[teller,0]TypeError: list indices must be integers, not tuple
 
Roelof
 

 


Date: Fri, 27 Aug 2010 16:20:27 +0100
Subject: Re: [Tutor] exercise problem
From: wprins at gmail.com
To: rwobben at hotmail.com
CC: tutor at python.org

Hi Roelof,

See below


On 27 August 2010 16:05, Roelof Wobben  wrote:



uitkomst = add_vectors[u,v]
 
But now I get this error message :
 

Traceback (most recent call last):File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 27, in  
uitkomst = add_vectors[u,v]
TypeError: 'function' object is not subscriptable
 
So it seems that I can't use vectors as a variable in a function.
Carefully compare the syntax for calling your function (as in the doctest) to what you've written above.  See the difference?  (Hint: check the type of parentheses...)

The error message is giving you a hint -- a subscriptable item is something like a list or array.  They use square brackets.  Function calls always use (round) parentheses.  To python, it looks like you're trying to subcript the function object "add_vectors", which obviously isn't possible.  Hence the message.

Regards,

Walter 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From bgailer at gmail.com  Fri Aug 27 18:00:23 2010
From: bgailer at gmail.com (bob gailer)
Date: Fri, 27 Aug 2010 12:00:23 -0400
Subject: [Tutor] exercise problem
In-Reply-To: 
References: ,
	,
	,
	<201008280015.16028.steve@pearwood.info>,
	,
	,
	,
	
	
Message-ID: <4C77E117.4070605@gmail.com>

  I have been reading your posts and responses. I find myself frustrated 
with your lack of understanding of Python fundamentals and the time and 
energy others are putting in that seems to help only a little.

I recommend you take a very basic tutorial, and be sure you understand 
the basic concepts before tackling what seems too hard for you.

Also I encourage you to take each error message and look up the topic. 
In this case

getal1 = getal1 + u[teller,0] + v[teller,0]
TypeError: list indices must be integers, not tuple

What does this error tell you?

What is a tuple? What is an integer? Where is there a tuple in this 
expression? What are you trying to do?

Look up list indexing and see if you can solve it yourself, then return 
with any questions that arise from this effort.

The more you do for yourself the faster and better you will learn and we 
will be more encouraged to help.

How does this sound to you? Will you give it a try?

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From rwobben at hotmail.com  Fri Aug 27 18:18:01 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Fri, 27 Aug 2010 16:18:01 +0000
Subject: [Tutor] exercise problem
In-Reply-To: <4C77E117.4070605@gmail.com>
References: ,
	,
	,
	<201008280015.16028.steve@pearwood.info>,
	,
	,
	,
	
	,
	<4C77E117.4070605@gmail.com>
Message-ID: 



 

> Date: Fri, 27 Aug 2010 12:00:23 -0400
> From: bgailer at gmail.com
> To: rwobben at hotmail.com
> CC: tutor at python.org
> Subject: Re: [Tutor] exercise problem
> 
> I have been reading your posts and responses. I find myself frustrated 
> with your lack of understanding of Python fundamentals and the time and 
> energy others are putting in that seems to help only a little.
> 
> I recommend you take a very basic tutorial, and be sure you understand 
> the basic concepts before tackling what seems too hard for you

 

 

I follow this basic tutorial : http://openbookproject.net/thinkcs/python/english2e/ch09.html

 


> 
> Also I encourage you to take each error message and look up the topic. 
> In this case
> 
> getal1 = getal1 + u[teller,0] + v[teller,0]
> TypeError: list indices must be integers, not tuple
> 
> What does this error tell you?

 

That the list index must be a integer.


> 
> What is a tuple? What is an integer? Where is there a tuple in this 
> expression? What are you trying to do?


What a tuple is i can't tell you. it's in the next chapter.

A integer is a number.

What Im trying to do is that I want all the first numbers of the vectors are added and all the second numbers.

 

So if I have this vector [1.0] [1,1]

I try to add 1 and 1 and after that I try to add 0 and 1 

and put the answer in a new vector.

 

 

> 
> Look up list indexing and see if you can solve it yourself, then return 
> with any questions that arise from this effort.
> 
> The more you do for yourself the faster and better you will learn and we 
> will be more encouraged to help.
> 
> How does this sound to you? Will you give it a try?


Of course I will give it a try. 

 

> 
> -- 
> Bob Gailer
> 919-636-4239
> Chapel Hill NC
> 

 

Roelof


 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From fomcl at yahoo.com  Fri Aug 27 18:25:12 2010
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Fri, 27 Aug 2010 09:25:12 -0700 (PDT)
Subject: [Tutor] more on wx and tiff
Message-ID: <733084.22051.qm@web110713.mail.gq1.yahoo.com>

Hi again,

Some more questions about tiff conversion. 

First, thanks for your previous replies. I cannot use IrfanView any time soon, 
nor will my boss switch to Linux. 


So I'm trying to do the conversion from tiff to png using the wx package (gif 
would also be fine, but that won't work due to copyright issues -- I pulled 
about half of my hairs out before I found that out ;-). I have to access the 
second page of the tiff file, then write it to a png file. The code below (see 
also http://codepad.org/CV9xZXgi) works for one file only. Two questions:

1--- the program gives a 'tiff library warning', which is related to multipage 
tiff files (http://libtiff.maptools.org/man/TIFFReadDirectory.3tiff.html), but 
it generates the same warning with a single page tiff. The warning is given in a 
little menu (annoying!). How can I prevent or suppress this warning? This is the 
complete warning log:
17:49:54: tiff module: TIFFReadDirectory
17:49:54: TIFF library warning.
17:49:54: tiff module: TIFFReadDirectory
17:49:54: TIFF library warning.
17:49:54: tiff module: TIFFReadDirectory
17:49:54: TIFF library warning.

2--- the program is not closed properly (despite of the destroy() call). What 
should I do to correct this?

As always, thanks in advance for your replies.

Best wishes,
Albert-Jan


import wx, Image
import os, glob

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        self.tifLoc = tifLoc
        self.debug = True
        wx.Frame.__init__(self, parent, id, title, size = (600, 800))
        SECONDPAGE = 1
        self.image = wx.Image(name = self.tifLoc, type = wx.BITMAP_TYPE_TIF, 
index = SECONDPAGE)
        if self.debug:
            h, w = self.image.GetSize()
            print "Reading file '%s' of %s x %s pixels" % (self.tifLoc, h, w )
        self.bitmap = wx.BitmapFromImage(self.image)
        wx.EVT_PAINT(self, self.OnPaint)
        self.Centre()

    def OnPaint(self, event):
        dc = wx.PaintDC(self)
        dc.DrawBitmap(self.bitmap, 0, 0)        
        self.saveIt()

    def saveIt(self):
        pngLoc = os.path.splitext(self.tifLoc)[0] + ".png"
        self.bitmap.SaveFile(pngLoc, wx.BITMAP_TYPE_PNG)

class MyApp(wx.App):

    def OnInit(self):
        frame = MyFrame(None, -1, 'My file')
        frame.Show(False) # do not show pic
        self.SetTopWindow(frame)
        if frame.debug:
            print "... Conversion done!"
        return True

path = "d:/temp"
for f in glob.glob(os.path.join(path, "*.tif")):
    tifLoc = f
    app = MyApp(0)
    app.MainLoop()
    app.Destroy()

 Cheers!!
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 waynejwerner at gmail.com  Fri Aug 27 18:44:04 2010
From: waynejwerner at gmail.com (Wayne Werner)
Date: Fri, 27 Aug 2010 11:44:04 -0500
Subject: [Tutor] more on wx and tiff
In-Reply-To: <733084.22051.qm@web110713.mail.gq1.yahoo.com>
References: <733084.22051.qm@web110713.mail.gq1.yahoo.com>
Message-ID: 

On Fri, Aug 27, 2010 at 11:25 AM, Albert-Jan Roskam  wrote:

> Hi again,
>
> Some more questions about tiff conversion.
>
> First, thanks for your previous replies. I cannot use IrfanView any time
> soon, nor will my boss switch to Linux.
>

Have you tried using the PIL?
http://www.pythonware.com/products/pil/

import Image
i = Image.open("file.tiff")
i.save(open('file.png', 'w'), filetype='png')

I don't know if that was previously suggested, but it should work on any
platform with PIL installed.

HTH,
Wayne
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From fal at libero.it  Fri Aug 27 18:44:28 2010
From: fal at libero.it (Francesco Loffredo)
Date: Fri, 27 Aug 2010 18:44:28 +0200
Subject: [Tutor] exercise problem
In-Reply-To: 
References: ,
	,
	,
	<201008280015.16028.steve@pearwood.info>,
	
	
Message-ID: <4C77EB6C.4010909@libero.it>

On 27/08/2010 17.05, Roelof Wobben wrote:
> Hello,
>
> My first try :
>
> def add_vectors(u, v):
> """
>  >>> add_vectors([1, 0], [1, 1])
> [2, 1]
>  >>> add_vectors([1, 2], [1, 4])
> [2, 6]
>  >>> add_vectors([1, 2, 1], [1, 4, 3])
> [2, 6, 4]
>  >>> add_vectors([11, 0, -4, 5], [2, -4, 17, 0])
> [13, -4, 13, 5]
> """
> teller=1
> getal1=0
> getal2=0
> while teller < len(u):

Up to this point, it's a good start.

Let's address the last problem first:
 > uitkomst = add_vectors[u,v]
 >
 > But now I get this error message :
 >
 > uitkomst = add_vectors[u,v]
 >
 > TypeError: 'function' object is not subscriptable
 >
 > So it seems that I can't use vectors as a variable in a function.

No, it just seems that you used brackets [] instead of parentheses () in 
the function call. When you call a function, you must follow its name 
with parentheses, even when the function doesn't need arguments.
So this line should read:
uitkomst = add_vectors(u, v)
or, if you really (really?) think the two vectors should be enclosed in 
a bigger list:
uitkomst = add_vectors([u, v]).
This is just one of the problems, I'll address the rest when you'll find 
them. Just some hints:

> getal1 = getal1 + u[teller,0] + v[teller,0] ???
> getal2 = getal2 + v[teller,1] + v[teller,1] ???
 > teller=teller+1

Ok, while I was writing, Walter told you about parentheses, so I'll 
address your next question:
>
> But now Im getting this message :
>
>
> Traceback (most recent call last):
>
> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 28, in 
>
> uitkomst = add_vectors(u,v)
>
> File "C:\Users\wobben\workspace\oefeningen\src\test.py", line 17, in add_vectors
>
> getal1 = getal1 + u[teller,0] + v[teller,0]
> TypeError: list indices must be integers, not tuple

When you call add_vectors, you give it u and v as arguments, and they 
are two lists, as per your requirements:
v = vector[0]  makes  v equal to the list [1, 0], and
u = vector[1]  makes  u equal to the list [1, 1].
Inside add_vectors, you want to sum the coordinates of the two vectors, 
so you should refer to each of them with their position in the list.
Just as you did with the list called vector, you should use a single 
integer to address an element also in the u and v lists inside 
add_vectors. If you use a couple of numbers separated by a comma, as you 
did, Python reads them as a tuple, and it complains. So the 2 lines that 
sum the vectors should become a single one:

getal1 = getal1 + u[teller] + v[teller]

Then you don't even need to accumulate the sum in the variable getal1, 
because you are building a list and you can store each sum in a 
different position of the new list... remember the append method of the 
lists? So that line should read:

getal1 = u[teller] + v[teller]

and getal1 should be appended to a list... uitkomst2, perhaps?

>
> Roelof

Francesco


> return uitkomst2[getal1, getal2] ???
> uitkomst= []
> vector= [[1,0], [1,1]]
> v=vector[0]
> u=vector[1]
> uitkomst = add_vectors[u,v]
>
> But now I get this error message :
>
> uitkomst = add_vectors[u,v]
>
> TypeError: 'function' object is not subscriptable
>
> So it seems that I can't use vectors as a variable in a function.
>
> Roelof
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.851 / Database dei virus: 271.1.1/3096 -  Data di rilascio: 08/26/10 20:34:00

From sander.sweers at gmail.com  Fri Aug 27 18:51:19 2010
From: sander.sweers at gmail.com (Sander Sweers)
Date: Fri, 27 Aug 2010 18:51:19 +0200
Subject: [Tutor] more on wx and tiff
In-Reply-To: <733084.22051.qm@web110713.mail.gq1.yahoo.com>
References: <733084.22051.qm@web110713.mail.gq1.yahoo.com>
Message-ID: 

On 27 August 2010 18:25, Albert-Jan Roskam  wrote:
> First, thanks for your previous replies. I cannot use IrfanView any time
> soon, nor will my boss switch to Linux.

Why not use graphicsmagick [1] which also provides a windows binary
[2]. You can execute it with the subprocess [3] module?

Greets
Sander

[1] http://www.graphicsmagick.org/convert.html
[2] ftp://ftp.graphicsmagick.org/pub/GraphicsMagick/1.3/windows/README.txt
[3] http://docs.python.org/library/subprocess.html

From christopher.henk at allisontransmission.com  Fri Aug 27 19:04:57 2010
From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com)
Date: Fri, 27 Aug 2010 13:04:57 -0400
Subject: [Tutor] exercise problem
In-Reply-To: 
Message-ID: 

Roelof Wobben wrote on 08/27/2010 12:18:01 PM:

> 
> 
> > Date: Fri, 27 Aug 2010 12:00:23 -0400
> > From: bgailer at gmail.com
> > To: rwobben at hotmail.com
> > CC: tutor at python.org
> > Subject: Re: [Tutor] exercise problem
> > 
> > I have been reading your posts and responses. I find myself frustrated 

> > with your lack of understanding of Python fundamentals and the time 
and 
> > energy others are putting in that seems to help only a little.
> > 
> > I recommend you take a very basic tutorial, and be sure you understand 

> > the basic concepts before tackling what seems too hard for you
> 
> 
> I follow this basic tutorial : 
http://openbookproject.net/thinkcs/python/english2e/ch09.html
> 
> 
> > 
> > Also I encourage you to take each error message and look up the topic. 

> > In this case
> > 
> > getal1 = getal1 + u[teller,0] + v[teller,0]
> > TypeError: list indices must be integers, not tuple
> > 
> > What does this error tell you?
> 
> That the list index must be a integer.
> 
> > 
> > What is a tuple? What is an integer? Where is there a tuple in this 
> > expression? What are you trying to do?
> 
> What a tuple is i can't tell you. it's in the next chapter.
> A integer is a number.
> What Im trying to do is that I want all the first numbers of the vectors 
are added and all the second numbers.
> 
> So if I have this vector [1.0] [1,1]

You seem still confused on how your parameters to your function are 
working or the assignment in general.  You do not have a vector [[1,0] 
[1,1]] being passed into your function.  You are passing in two lists 
(vectors).  The first one 'u' is [1,0] , the second 'v' is [1,1] 
part of your code below:
vector= [[1,0], [1,1]]
v=vector[0]
u=vector[1]
print u, v
uitkomst = add_vectors(u,v)

if you just print u it will show [0,1]
if you just print v it will print [1,1]

thus your code:
getal1 = getal1 + u[teller,0] + v[teller,0]
getal2 = getal2 + v[teller,1] + v[teller,1]

is not doing what you thought it would.  (the syntax is wrong also).  I am 
guessing you are trying to index a 2D matrix with this.  Section 9.18 
would show you how to do that in python.  However there is no 2D matrix in 
your function, there are 2 vectors u and v.
 
So to add the vectors you loop over the index numbers (see 9.13) in your 
tutorial. in this loop add the value referenced by the index in each list 
to each other (section 9.2), and assign it to your new list at the same 
index value (9.8).  The one thing that would catch you on the assignment 
part, is that the list you are assigning to must have an element at that 
index (I didn't see the append function mentioned in your tutorial yet). 
Therefore you must initialize the list to which you are assigning to make 
sure it is the same length as the vectors you are adding (9.12 gives a 
method for this). 
 
Hopefully that will get you a bit closer to your answer.  I would suggest 
spending time in this section and make sure you understand what each line 
is doing, since these concepts are fundamentals in python programming. 
Use the interactive session in python to quickly see what each command 
does.  Python is great in that it will give you instant feedback.

Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rwobben at hotmail.com  Fri Aug 27 19:56:35 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Fri, 27 Aug 2010 17:56:35 +0000
Subject: [Tutor] exercise problem
In-Reply-To: <229747.38101.qm@web86706.mail.ird.yahoo.com>
References: ,
	
	,
	<412444.33192.qm@web86702.mail.ird.yahoo.com>
	,
	<229747.38101.qm@web86706.mail.ird.yahoo.com>
Message-ID: 


Hello, 

 

Now I have this :

 

def add_vectors(u, v):
    """
      >>> add_vectors([1, 0], [1, 1])
      [2, 1]
      >>> add_vectors([1, 2], [1, 4])
      [2, 6]
      >>> add_vectors([1, 2, 1], [1, 4, 3])
      [2, 6, 4]
      >>> add_vectors([11, 0, -4, 5], [2, -4, 17, 0])
      [13, -4, 13, 5]
    """
    teller=0
    getal1=0
    getal2=0 
    while teller < len(u):
        getal1 = u[teller] + v[teller]
        teller=teller+1
    return uitkomst2
             
uitkomst= []
uitkomst2=[]
vector= [1, 2, 1], [1, 4, 3]
v=vector[0]
u=vector[1]
uitkomst = add_vectors(u,v)
print uitkomst         


The only problem I have is to build up uitkomst2.

 

on every loop getal1 has the value of the outcome.

 

So I thought this would work

 

uitkomst2 [teller] = getal1 

 

But then i get a out of range.

 

Roelof
 


Date: Fri, 27 Aug 2010 10:19:30 -0700
From: alan.gauld at btinternet.com
Subject: Re: [Tutor] exercise problem
To: rwobben at hotmail.com










>u v, result
 
first example.
 
u : [1.0]  v: [1,1] result [2.1] 
 


OK, Great, you got that.



first split  u en v in only numbers.



No, you should leave them as lists.





Then add u[0] en v[0] and u[1] and v[1] 
put the outcome in the new  vector.

Almost except you don't know how many elements there will be so 
you need a loop to process all the elements.








outcome= [outcome u, outcome[u]
return outcome.


This confused me, the output should be:

[ u[0]+v[0], u[1]+v[1], u[2]+v[2], ...., [u[n]+v[n] ]

And in case you are wondering, a vector is used in math to, 
for example, represent a point in space. A 2 dimensional 
point has an X,Y coordinate so we can create a 2 element 
vector: [x,y]

We can add, subtract and multiply vectors. Vectors can also 
be used to represent other physical measures, for example 
AC electric current has a magnitude and phase angle at any 
point in time. These two values can be combined as a vector.
We can use bigger vectors to represent, for example the 
set of inputs to a parallel port printer, so we would have a 
list of 8 binary values. Once again we can express mathematically 
the processing of this vector as a function and by applying the 
function to the vector deermine the expected output for any given input. 
That could be, for example, an ASCII character for the printer example...
They are very important in science and engineering.

The tutorial you are following does expect the reader to be quite 
math literate - it is part of a university comp sci course after all. If
you do not have a strong math background you may find some of 
the others more readable. For example mine( :-) ) does not assume 
any knowledge of math beyond basic high school level - really basic 
geometry and arithmetic.

Alan G.



 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From fomcl at yahoo.com  Fri Aug 27 20:00:16 2010
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Fri, 27 Aug 2010 11:00:16 -0700 (PDT)
Subject: [Tutor] more on wx and tiff
In-Reply-To: 
References: <733084.22051.qm@web110713.mail.gq1.yahoo.com>
	
Message-ID: <11704.1631.qm@web110705.mail.gq1.yahoo.com>

Hi Wayne,

Yep, I considered using PIL, but that package won't read so-called Group 4 Tiffs 
[1]. They're two-page, black-and-white scanned forms. I need part of the second 
form (i.e., the backside of a certificate). The page contains some hand-written 
info which needs to be presented in a simple data entry program, which I made 
using Tkinter.

The forms are confidential so they may not leave the company network. And the IT 
droids are somewhat paranoid so it's very time-consuming to get some new 
executable 'inside' the company network. Beeeh, formalities... :-(

 
[1] http://www.digitalpreservation.gov/formats/fdd/fdd000024.shtml

Cheers!!
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?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~




________________________________
From: Wayne Werner 
To: Albert-Jan Roskam 
Cc: Python Mailing List 
Sent: Fri, August 27, 2010 6:44:04 PM
Subject: Re: [Tutor] more on wx and tiff


On Fri, Aug 27, 2010 at 11:25 AM, Albert-Jan Roskam  wrote:

Hi again,
>
>Some more questions about tiff conversion. 
>
>First, thanks for your previous replies. I cannot use IrfanView any time soon, 
>nor will my boss switch to Linux. 
>
>

Have you tried using the PIL?
http://www.pythonware.com/products/pil/

import Image
i = Image.open("file.tiff")
i.save(open('file.png', 'w'), filetype='png')

I don't know if that was previously suggested, but it should work on any 
platform with PIL installed. 

HTH,
Wayne


      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From davea at ieee.org  Fri Aug 27 20:27:34 2010
From: davea at ieee.org (Dave Angel)
Date: Fri, 27 Aug 2010 14:27:34 -0400
Subject: [Tutor] exercise problem
In-Reply-To: 
References: ,
		,
	<412444.33192.qm@web86702.mail.ird.yahoo.com>	,
	<229747.38101.qm@web86706.mail.ird.yahoo.com>
	
Message-ID: <4C780396.1090906@ieee.org>

(Don't top-post, it loses all the context)

Roelof Wobben wrote:
> Hello, 
>
>  
>
> Now I have this :
>
>  
>
> def add_vectors(u, v):
>     """
>       >>> add_vectors([1, 0], [1, 1])
>       [2, 1]
>       >>> add_vectors([1, 2], [1, 4])
>       [2, 6]
>       >>> add_vectors([1, 2, 1], [1, 4, 3])
>       [2, 6, 4]
>       >>> add_vectors([11, 0, -4, 5], [2, -4, 17, 0])
>       [13, -4, 13, 5]
>     """
>     teller=0
>     getal1=0
>     getal2=0 
>     while teller < len(u):
>         getal1 = u[teller] + v[teller]
>         teller=teller+1
>     return uitkomst2
>              
> uitkomst= []
> uitkomst2=[]
> vector= [1, 2, 1], [1, 4, 3]
> v=vector[0]
> u=vector[1]
> uitkomst = add_vectors(u,v)
> print uitkomst         
>
>
> The only problem I have is to build up uitkomst2.
> on every loop getal1 has the value of the outcome.
> So I thought this would work
>
> uitkomst2 [teller] = getal1 
>
> But then i get a out of range.
>
>   
Where did you put that statement?  Was it indented like getal1= and 
teller= ?  I doubt it.  If you don't use the value till the loop is 
over, then the subscript will be wrong, and so will the value.

The other problem is you're confusing the variables inside the function 
with the ones declared outside.  While you're learning, you should use 
different names for the two sets of variables.  So create a new variable 
inside the function, called something like result.  Give it an initial 
value, a list of the desired size.  Then assign to one of its elements 
each time through the loop.  And don't forget to change the return 
statement to return that variable instead of the confused-named one.

DaveA


From rwobben at hotmail.com  Fri Aug 27 20:35:21 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Fri, 27 Aug 2010 18:35:21 +0000
Subject: [Tutor] exercise problem
In-Reply-To: <4C780396.1090906@ieee.org>
References: ,
	
	,
	<412444.33192.qm@web86702.mail.ird.yahoo.com>
	,
	<229747.38101.qm@web86706.mail.ird.yahoo.com>
	,
	<4C780396.1090906@ieee.org>
Message-ID: 



 

> Date: Fri, 27 Aug 2010 14:27:34 -0400
> From: davea at ieee.org
> To: rwobben at hotmail.com
> CC: alan.gauld at btinternet.com; tutor at python.org
> Subject: Re: [Tutor] exercise problem
> 
> (Don't top-post, it loses all the context)
> 
> Roelof Wobben wrote:
> > Hello, 
> >
> > 
> >
> > Now I have this :
> >
> > 
> >
> > def add_vectors(u, v):
> > """
> > >>> add_vectors([1, 0], [1, 1])
> > [2, 1]
> > >>> add_vectors([1, 2], [1, 4])
> > [2, 6]
> > >>> add_vectors([1, 2, 1], [1, 4, 3])
> > [2, 6, 4]
> > >>> add_vectors([11, 0, -4, 5], [2, -4, 17, 0])
> > [13, -4, 13, 5]
> > """
> > teller=0
> > getal1=0
> > getal2=0 
> > while teller < len(u):
> > getal1 = u[teller] + v[teller]
> > teller=teller+1
> > return uitkomst2
> > 
> > uitkomst= []
> > uitkomst2=[]
> > vector= [1, 2, 1], [1, 4, 3]
> > v=vector[0]
> > u=vector[1]
> > uitkomst = add_vectors(u,v)
> > print uitkomst 
> >
> >
> > The only problem I have is to build up uitkomst2.
> > on every loop getal1 has the value of the outcome.
> > So I thought this would work
> >
> > uitkomst2 [teller] = getal1 
> >
> > But then i get a out of range.
> >
> > 
> Where did you put that statement? Was it indented like getal1= and 
> teller= ? I doubt it. If you don't use the value till the loop is 
> over, then the subscript will be wrong, and so will the value.
> 
> The other problem is you're confusing the variables inside the function 
> with the ones declared outside. While you're learning, you should use 
> different names for the two sets of variables. So create a new variable 
> inside the function, called something like result. Give it an initial 
> value, a list of the desired size. Then assign to one of its elements 
> each time through the loop. And don't forget to change the return 
> statement to return that variable instead of the confused-named one.
> 
> DaveA
> 


Hello, 

 

I put in right after getal1 = 

I have tried another solution nl. 

 

Put every outcome in a string.

Then convert the string into a list like this :

 

def add_vectors(u, v):
    """
      >>> add_vectors([1, 0], [1, 1])
      [2, 1]
      >>> add_vectors([1, 2], [1, 4])
      [2, 6]
      >>> add_vectors([1, 2, 1], [1, 4, 3])
      [2, 6, 4]
      >>> add_vectors([11, 0, -4, 5], [2, -4, 17, 0])
      [13, -4, 13, 5]
    """
    teller=0
    getal1=0
    uitkomst=""
    while teller < len(u):
        getal1 = u[teller] + v[teller]
        uitkomst = uitkomst + str(getal1) 
        teller=teller+1
    uitkomst2 = list(uitkomst)
    return uitkomst2
             
uitkomst= []
uitkomst2=[]
vector= [1, 2, 1], [1, 4, 3]
v=vector[0]
u=vector[1]
uitkomst = add_vectors(u,v)
print uitkomst     

 

But then I get a list of string instead of integers.

 

You say I have to make a vector and put all the values into it.

That can work only you have to know how big the vector must be.

Or work with a lot of if then.

 

Roelof

 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From fal at libero.it  Fri Aug 27 20:54:56 2010
From: fal at libero.it (Francesco Loffredo)
Date: Fri, 27 Aug 2010 20:54:56 +0200
Subject: [Tutor] exercise problem
In-Reply-To: 
References: ,
		,
	<412444.33192.qm@web86702.mail.ird.yahoo.com>	,
	<229747.38101.qm@web86706.mail.ird.yahoo.com>
	
Message-ID: <4C780A00.2070200@libero.it>

We are close to the solution, keep trying!

On 27/08/2010 19.56, Roelof Wobben wrote:
> Hello,
>
> Now I have this :
>
> def add_vectors(u, v):
> """
>  >>> add_vectors([1, 0], [1, 1])
> [2, 1]
>  >>> add_vectors([1, 2], [1, 4])
> [2, 6]
>  >>> add_vectors([1, 2, 1], [1, 4, 3])
> [2, 6, 4]
>  >>> add_vectors([11, 0, -4, 5], [2, -4, 17, 0])
> [13, -4, 13, 5]
> """
> teller=0
> getal1=0
> getal2=0
> while teller < len(u):
> getal1 = u[teller] + v[teller]
> teller=teller+1
> return uitkomst2
>
> uitkomst= []
> uitkomst2=[]
> vector= [1, 2, 1], [1, 4, 3]
> v=vector[0]
> u=vector[1]
> uitkomst = add_vectors(u,v)
> print uitkomst
>
> The only problem I have is to build up uitkomst2.
There is no need to initialize uitkomst, because it will be created by 
the line
 > uitkomst = add_vectors(u,v)
but you should create the list uitkomst2 INSIDE the add_vectors 
function. uitkomst2 is an internal storage for...
> on every loop getal1 has the value of the outcome.
... that's it, for the different values that you put in getal1.
There is no more need for getal2, too.
So you could put the line
 > uitkomst2=[]
in the place where you should delete
 > getal2=0
that is just before the while loop.
And finally, in the loop, just before
 > teller=teller+1
you need to insert the line that you haven't yet read about, but that 
you really need: (ta-dah!)

uitkomst2.append(getal1)

As you will (YOU WILL, WON'T YOU?) read in Alan's tutorial, and also in 
the one you're reading, this line extends the uitkomst2 list by adding a 
new element to its 'tail': the number getal1.
So, if you follow the flow of your function, you can see it happening:

-------------- BEGINNING -----------------------
vector= [1, 2, 1], [1, 4, 3]  # maybe Python can forgive you, but
                               # I would write [[1, 2, 1], [1, 4, 3]]
                               # or ([1, 2, 1], [1, 4, 3]) ...
v=vector[0]  # now v = [1, 2, 1]
u=vector[1]  # now u = [1, 4, 3]
uitkomst = add_vectors(u,v)  # add_vectors is called to provide a value
     teller=0
     getal1=0
     uitkomst2 = []
     while teller < len(u):  # teller= 0, len(u) = 3, OK
         getal1 = u[teller] + v[teller]  # getal1 = u[0]+v[0] = 1+1 = 2
         uitkomst2.append(getal1)  # uitkomst2 is now [2]
         teller=teller+1
     while teller < len(u):  # teller= 1, len(u) = 3, OK
         getal1 = u[teller] + v[teller]  # getal1 = u[1]+v[1] = 2+4 = 6
         uitkomst2.append(getal1)  # uitkomst2 is now [2, 6]
         teller=teller+1
     while teller < len(u):  # teller= 2, len(u) = 3, OK
         getal1 = u[teller] + v[teller]  # getal1 = u[2]+v[2] = 1+3 = 4
         uitkomst2.append(getal1)  # uitkomst2 is now [2, 6, 4]
         teller=teller+1
     while teller < len(u):  # teller= 3, len(u) = 3, STOP!
     return uitkomst2  # and finally the list uitkomst2 becomes the value
                       # that the add_vectors function will provide.
uitkomst = add_vectors(u,v)  # now uitkomst becomes [2, 6, 4]
print uitkomst  # and lived happily ever after.


> So I thought this would work
>
> uitkomst2 [teller] = getal1
>
> But then i get a out of range.
sure, because you tried to access an element in an empty list.

>
> Roelof
Hope you got it, and keep trying!
Francesco
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.851 / Database dei virus: 271.1.1/3096 -  Data di rilascio: 08/26/10 20:34:00

From davea at ieee.org  Fri Aug 27 21:32:59 2010
From: davea at ieee.org (Dave Angel)
Date: Fri, 27 Aug 2010 15:32:59 -0400
Subject: [Tutor] exercise problem
In-Reply-To: 
References: ,
		,
	<412444.33192.qm@web86702.mail.ird.yahoo.com>	,
	<229747.38101.qm@web86706.mail.ird.yahoo.com>	,
	<4C780396.1090906@ieee.org>
	
Message-ID: <4C7812EB.8060301@ieee.org>



Roelof Wobben wrote:
>> Date: Fri, 27 Aug 2010 14:27:34 -0400
>> From: davea at ieee.org
>> To: rwobben at hotmail.com
>> CC: alan.gauld at btinternet.com; tutor at python.org
>> Subject: Re: [Tutor] exercise problem
>>
>> 
>> The other problem is you're confusing the variables inside the function 
>> with the ones declared outside. While you're learning, you should use 
>> different names for the two sets of variables. So create a new variable 
>> inside the function, called something like result. Give it an initial 
>> value, a list of the desired size. Then assign to one of its elements 
>> each time through the loop. And don't forget to change the return 
>> statement to return that variable instead of the confused-named one.
>>
>> DaveA
>>
>>     
>
>
> Hello, 
>
>  
>
> I put in right after getal1 = 
>
> I have tried another solution nl. 
>
>  
>
> Put every outcome in a string.
>
> Then convert the string into a list like this :
>
>  
>
> def add_vectors(u, v):
>     """
>       >>> add_vectors([1, 0], [1, 1])
>       [2, 1]
>       >>> add_vectors([1, 2], [1, 4])
>       [2, 6]
>       >>> add_vectors([1, 2, 1], [1, 4, 3])
>       [2, 6, 4]
>       >>> add_vectors([11, 0, -4, 5], [2, -4, 17, 0])
>       [13, -4, 13, 5]
>     """
>     teller=0
>     getal1=0
>     uitkomst=""
>     while teller < len(u):
>         getal1 = u[teller] + v[teller]
>         uitkomst = uitkomst + str(getal1) 
>         teller=teller+1
>     uitkomst2 = list(uitkomst)
>     return uitkomst2
>              
> uitkomst= []
> uitkomst2=[]
> vector= [1, 2, 1], [1, 4, 3]
> v=vector[0]
> u=vector[1]
> uitkomst = add_vectors(u,v)
> print uitkomst     
>
>  
>
> But then I get a list of string instead of integers.
>
>   
You're close.  Now that you've initialized the result variable to [], 
you can use + just as you're doing.  Just take out the str() function in 
that line.  You've still got duplicate names there between that function 
and the outer level code.

There's also no need to convert uitkomst to a list, since it already is.


DaveA


From alan.gauld at btinternet.com  Sat Aug 28 00:56:24 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 27 Aug 2010 23:56:24 +0100
Subject: [Tutor] exercise problem
References: ,
		,
	<412444.33192.qm@web86702.mail.ird.yahoo.com>	,
	<229747.38101.qm@web86706.mail.ird.yahoo.com>	,
	<4C780396.1090906@ieee.org>
	<4C7812EB.8060301@ieee.org>
Message-ID: 


"Dave Angel"  wrote

>>     while teller < len(u):
>>         getal1 = u[teller] + v[teller]
>>         uitkomst = uitkomst + str(getal1)
>> But then I get a list of string instead of integers.
>>
>>
> You're close.  Now that you've initialized the result variable to 
> [], you can use + just as you're doing.  Just take out the str() 
> function in that line.  You've still got duplicate names there 
> between that function and the outer level code.

You will need to make the new result a list too for + to work, like 
so:

         uitkomst = uitkomst + [getal1]

Or you can just append() the answer to uitkomst

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From kevinosky at gmail.com  Sat Aug 28 03:42:52 2010
From: kevinosky at gmail.com (kevin hayes)
Date: Fri, 27 Aug 2010 18:42:52 -0700
Subject: [Tutor] help, complete beginner please!
Message-ID: 

Hi all! I'm trying to write a basic text adventure game to start learning
python (just for fun). I've gone through the first four chapters of a "learn
python game programming book" and I'm having trouble with the exercise on
writing a text adventure.  I've been piecing together what is in the book
with some examples I found online. My goal with this question is not to
necessarily make the code I've written work, but to gain a fundamental
understanding of the concepts.
        Can someone show me how to organize a text-based game with these
things kept in mind:  1)Each room will be a function 2)Direction(N,S,E,W)
3)"Look at" 4)Pick Up 5)Quit 6)Accumulated Gold Coins 7) Find all the Gold
8)Win/Lose
         I'm looking for the simplest version of this as possible, because
I'm having trouble with the concepts. I'm only showing my code to give you
an idea where I'm at. However, I would really like someone to lay out a
little code structure for me.

I'm using Python 2.6.5 on a Mac Version 10.4.11 and don't consider myself
computer literate, so bear with my ignorance please.
        Also, don't feel like you have to correct my code...please just
create your own example of code structure to get me on the right track.

Here is the start of my game:

"""FirstGame.py
First try at creating a text-based adventure game.  Trying to learn the
basics
of creating functions and using if and loops.
kevin: 8/27/10"""

keepGoing = True
while keepGoing == True:

    global gold
    gold = 0

    def RoomOne():
        print "You find yourself in a large room. Above you is a massive
crystal"
        print "chandelier. In front of you is round stone fountain, spewing
water"
        print "from it's center. On the walls hang green satin drapery.  The
ceiling"
        print "is comprised of three ornate arches. There is an arch in
front of you"
        print "and to your right and left. A staircase leads up from under
the arch"
        print "in front of you. Under the arches to your left and right are
large wooden"
        print "doors, each with an iron handle. Enter 'Help' for a full list
of commands."
    RoomOne()
    Command = raw_input("Please enter a command. ")
    Command = Command.upper()
    if Command == "N":
        RoomFour()
    elif Command == "S":
        print "You ditched the creepy castle and headed for the road."
        keepGoing == False
    elif Command == "E":
        RoomTwo()
    elif Command == "HELP":
        print "List of Commands: 'Help',then enter for this list."
        print                   "'N', then enter = Door to the North."
        print                   "'S', then enter = Door to the South."
        print                   "'E', then enter = Door to the East."
        print                   "'W', then enter = Door to the West."
        print                   "'Look at', then 'objects name', then enter
= Looks at an object."
        print                   "'Pick Up', then 'objects name', then enter
= Picks up an object."
        print                   "'Q', then enter = Quit Game."

    elif Command == "W":
        RoomSix()
    elif Command == "LOOK AT FOUNTAIN":
        print "There appears to be 4 gold coins in it."
    elif Command == "PICK UP 4 GOLD COINS":
        gold = gold + 4
        print "Current Gold = ", gold
    elif Command == "Q":
        keepGoing = False

    else:
        print "That doesn't work."

    def RoomTwo():
        print "Current Gold = ", gold
        print "In the middle of the room is a large Gargoyle with fiery red
eyes."
        print "He's holding a cup. In the southeast corner of the room you
see a broom"
        print "with dust and cob-webs on it. Next to the broom is a dead
rat."
        print "To the north is another door. In front of the door is an
overturned basket."

    promptTwo = raw_input("What are you going to do? ")
    promptTwo = promptTwo.upper()

    if promptTwo == "N":
        RoomThree()
    elif promptTwo == "S":
        print "There is no door there."
    elif promptTwo == "W":
        RoomOne()
    elif promptTwo == "E":
        print "There is only a wall there."
    elif promptTwo == "Q":
        keepGoing = False
    elif promptTwo == "PICK UP BASKET":
        print "You pick up the basket, revealing 2 gold pieces."
        RoomTwo()
    elif promptTwo == "PICK UP 2 GOLD COINS":
        gold = gold + 2
        print "Current Gold = ", gold
        RoomTwo()
    elif promptTwo == "LOOK AT GARGOYLE":
        print "Looking at the Gargoyle you notice he's really mean, and
really still."
        RoomTwo()
    elif promptTwo == "LOOK AT BROOM":
        print "Looking at the broom, you notice it's unnecessarity dirty."
    elif promptTwo == "PICK UP BROOM":
        print " You pick up the broom. But you don't notice anything
special, so you"
        print "set it back down where it was."
    elif promptTwo == "LOOK AT CUP":
        print "You look at the cup, and find nothing of interest."
    elif promptTwo == "LOOK AT DEAD RAT":
        print "You look at the dead rat and find it utterly disgusting."
    elif promptTwo == "HELP":
        print "List of Commands: 'Help',then enter for this list."
        print                   "'N', then enter = Door to the North."
        print                   "'S', then enter = Door to the South."
        print                   "'E', then enter = Door to the East."
        print                   "'W', then enter = Door to the West."
        print                   "'Look at', then 'objects name', then enter
= Looks at an object."
        print                   "'Pick Up', then 'objects name', then enter
= Picks up an object."
        print                   "'Q', then enter = Quit Game."
    else:
        print "That didn't work."


    def RoomThree():
        print "Current Gold = ", gold
        print "To the north is a giant replica of a wooley mamoth.  His
tusks are made"
        print "of gold. To the east is a painting of Mother Theresa.  Under
the painting"
        print "is a baby's crib. The only doors you see are to the south and
west."

    promptThree = raw_input("What would you like to do? ")
    promptThree = promptThree.upper()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From augdawg09 at gmail.com  Sat Aug 28 04:34:19 2010
From: augdawg09 at gmail.com (aug dawg)
Date: Fri, 27 Aug 2010 22:34:19 -0400
Subject: [Tutor] help, complete beginner please!
In-Reply-To: 
References: 
Message-ID: 

Now, I'm no pro at programming in Python, but here's what I recommend you
do. I would have a class at the beginning to define all of the rooms, and
then have the rest of the code below that. Then, it makes it easier to
follow. In addition, I would also have a function that stores the name of
the room in a variable which can then call the "Look around" type function.
I would also have a variable that has the number of all of the gold and then
another one that has the amount of gold that the player has. I would place
the entire program in a loop so that every time the loop runs and checks if
the player has found all of the gold, and if the player has, it acts
accordingly. For example:

class rooms:
     (code for the various rooms goes here)

if all_gold != player_gold:
     do this
     (program goes here)
else:
     do this

    Regarding the compass part (N, S, E, W) I would also do a bunch of if's
for each possible answer, and then an if on top of those. For example:

if value != None:
     if value == whatever_value:
          do this
     if value == other_value:
          do other thing

If you need extra help, just let me know.

On Fri, Aug 27, 2010 at 9:42 PM, kevin hayes  wrote:

> Hi all! I'm trying to write a basic text adventure game to start learning
> python (just for fun). I've gone through the first four chapters of a "learn
> python game programming book" and I'm having trouble with the exercise on
> writing a text adventure.  I've been piecing together what is in the book
> with some examples I found online. My goal with this question is not to
> necessarily make the code I've written work, but to gain a fundamental
> understanding of the concepts.
>         Can someone show me how to organize a text-based game with these
> things kept in mind:  1)Each room will be a function 2)Direction(N,S,E,W)
> 3)"Look at" 4)Pick Up 5)Quit 6)Accumulated Gold Coins 7) Find all the Gold
> 8)Win/Lose
>          I'm looking for the simplest version of this as possible, because
> I'm having trouble with the concepts. I'm only showing my code to give you
> an idea where I'm at. However, I would really like someone to lay out a
> little code structure for me.
>
> I'm using Python 2.6.5 on a Mac Version 10.4.11 and don't consider myself
> computer literate, so bear with my ignorance please.
>         Also, don't feel like you have to correct my code...please just
> create your own example of code structure to get me on the right track.
>
> Here is the start of my game:
>
> """FirstGame.py
> First try at creating a text-based adventure game.  Trying to learn the
> basics
> of creating functions and using if and loops.
> kevin: 8/27/10"""
>
> keepGoing = True
> while keepGoing == True:
>
>     global gold
>     gold = 0
>
>     def RoomOne():
>         print "You find yourself in a large room. Above you is a massive
> crystal"
>         print "chandelier. In front of you is round stone fountain, spewing
> water"
>         print "from it's center. On the walls hang green satin drapery.
>  The ceiling"
>         print "is comprised of three ornate arches. There is an arch in
> front of you"
>         print "and to your right and left. A staircase leads up from under
> the arch"
>         print "in front of you. Under the arches to your left and right are
> large wooden"
>         print "doors, each with an iron handle. Enter 'Help' for a full
> list of commands."
>     RoomOne()
>     Command = raw_input("Please enter a command. ")
>     Command = Command.upper()
>     if Command == "N":
>         RoomFour()
>     elif Command == "S":
>         print "You ditched the creepy castle and headed for the road."
>         keepGoing == False
>     elif Command == "E":
>         RoomTwo()
>     elif Command == "HELP":
>         print "List of Commands: 'Help',then enter for this list."
>         print                   "'N', then enter = Door to the North."
>         print                   "'S', then enter = Door to the South."
>         print                   "'E', then enter = Door to the East."
>         print                   "'W', then enter = Door to the West."
>         print                   "'Look at', then 'objects name', then enter
> = Looks at an object."
>         print                   "'Pick Up', then 'objects name', then enter
> = Picks up an object."
>         print                   "'Q', then enter = Quit Game."
>
>     elif Command == "W":
>         RoomSix()
>     elif Command == "LOOK AT FOUNTAIN":
>         print "There appears to be 4 gold coins in it."
>     elif Command == "PICK UP 4 GOLD COINS":
>         gold = gold + 4
>         print "Current Gold = ", gold
>     elif Command == "Q":
>         keepGoing = False
>
>     else:
>         print "That doesn't work."
>
>     def RoomTwo():
>         print "Current Gold = ", gold
>         print "In the middle of the room is a large Gargoyle with fiery red
> eyes."
>         print "He's holding a cup. In the southeast corner of the room you
> see a broom"
>         print "with dust and cob-webs on it. Next to the broom is a dead
> rat."
>         print "To the north is another door. In front of the door is an
> overturned basket."
>
>     promptTwo = raw_input("What are you going to do? ")
>     promptTwo = promptTwo.upper()
>
>     if promptTwo == "N":
>         RoomThree()
>     elif promptTwo == "S":
>         print "There is no door there."
>     elif promptTwo == "W":
>         RoomOne()
>     elif promptTwo == "E":
>         print "There is only a wall there."
>     elif promptTwo == "Q":
>         keepGoing = False
>     elif promptTwo == "PICK UP BASKET":
>         print "You pick up the basket, revealing 2 gold pieces."
>         RoomTwo()
>     elif promptTwo == "PICK UP 2 GOLD COINS":
>         gold = gold + 2
>         print "Current Gold = ", gold
>         RoomTwo()
>     elif promptTwo == "LOOK AT GARGOYLE":
>         print "Looking at the Gargoyle you notice he's really mean, and
> really still."
>         RoomTwo()
>     elif promptTwo == "LOOK AT BROOM":
>         print "Looking at the broom, you notice it's unnecessarity dirty."
>     elif promptTwo == "PICK UP BROOM":
>         print " You pick up the broom. But you don't notice anything
> special, so you"
>         print "set it back down where it was."
>     elif promptTwo == "LOOK AT CUP":
>         print "You look at the cup, and find nothing of interest."
>     elif promptTwo == "LOOK AT DEAD RAT":
>         print "You look at the dead rat and find it utterly disgusting."
>     elif promptTwo == "HELP":
>         print "List of Commands: 'Help',then enter for this list."
>         print                   "'N', then enter = Door to the North."
>         print                   "'S', then enter = Door to the South."
>         print                   "'E', then enter = Door to the East."
>         print                   "'W', then enter = Door to the West."
>         print                   "'Look at', then 'objects name', then enter
> = Looks at an object."
>         print                   "'Pick Up', then 'objects name', then enter
> = Picks up an object."
>         print                   "'Q', then enter = Quit Game."
>     else:
>         print "That didn't work."
>
>
>     def RoomThree():
>         print "Current Gold = ", gold
>         print "To the north is a giant replica of a wooley mamoth.  His
> tusks are made"
>         print "of gold. To the east is a painting of Mother Theresa.  Under
> the painting"
>         print "is a baby's crib. The only doors you see are to the south
> and west."
>
>     promptThree = raw_input("What would you like to do? ")
>     promptThree = promptThree.upper()
>
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From bgailer at gmail.com  Sat Aug 28 07:16:04 2010
From: bgailer at gmail.com (bob gailer)
Date: Sat, 28 Aug 2010 01:16:04 -0400
Subject: [Tutor] help, complete beginner please!
In-Reply-To: 
References: 
Message-ID: <4C789B94.7040002@gmail.com>

  On 8/27/2010 9:42 PM, kevin hayes wrote:
> Hi all! I'm trying to write a basic text adventure game to start 
> learning python (just for fun). I've gone through the first four 
> chapters of a "learn python game programming book" and I'm having 
> trouble with the exercise on writing a text adventure.  I've been 
> piecing together what is in the book with some examples I found 
> online. My goal with this question is not to necessarily make the code 
> I've written work, but to gain a fundamental understanding of the 
> concepts.
>         Can someone show me how to organize a text-based game with 
> these things kept in mind:  1)Each room will be a function 
> 2)Direction(N,S,E,W) 3)"Look at" 4)Pick Up 5)Quit 6)Accumulated Gold 
> Coins 7) Find all the Gold 8)Win/Lose

aug dawg recommended classes, with which I agree, but that may be 
premature for you.

1) define the functions once, outside the while loop.

2) there is no need for global gold. global only makes sense inside a def.

3) do not reset gold to 0 at the start of each loop cycle. Do that 
before the loop.

4) write a help function to handle the help text rather than repeating 
the text multiple times.

5) use initial lower case for function and variable names. This is a 
convention that makes
      it easier to read each other's code as well as your own code.

6) check the spelling of wooley mamoth

7) while keepGoing == True: can be simplified to while keepGoing:

8) write a function to get a command. Have it do the uppercasing and 
checking for / processing of common commands such as HELP,

9) have the functions return text rather than printing it. Use triple 
quoted text. e.g.:

def Room1():
   description = """You find yourself in a large room. Above you is a 
massive crystal
chandelier. In front of you is round stone fountain, spewing water."""

Then in the loop:
   print Room1().

This separates data from logic and paves the way to convert things to 
classes & dictionaries.


>         I'm looking for the simplest version of this as possible, 
> because I'm having trouble with the concepts. I'm only showing my code 
> to give you an idea where I'm at. However, I would really like someone 
> to lay out a little code structure for me.
>
> I'm using Python 2.6.5 on a Mac Version 10.4.11 and don't consider 
> myself computer literate, so bear with my ignorance please.
>         Also, don't feel like you have to correct my code...please 
> just create your own example of code structure to get me on the right 
> track.
>
> Here is the start of my game:
>
> """FirstGame.py
> First try at creating a text-based adventure game.  Trying to learn 
> the basics
> of creating functions and using if and loops.
> kevin: 8/27/10"""
>
> keepGoing = True
> while keepGoing == True:
>
>     global gold
>     gold = 0
>
>     def RoomOne():
>         print "You find yourself in a large room. Above you is a 
> massive crystal"
>         print "chandelier. In front of you is round stone fountain, 
> spewing water"
>         print "from it's center. On the walls hang green satin 
> drapery.  The ceiling"
>         print "is comprised of three ornate arches. There is an arch 
> in front of you"
>         print "and to your right and left. A staircase leads up from 
> under the arch"
>         print "in front of you. Under the arches to your left and 
> right are large wooden"
>         print "doors, each with an iron handle. Enter 'Help' for a 
> full list of commands."
>     RoomOne()
>     Command = raw_input("Please enter a command. ")
>     Command = Command.upper()
>     if Command == "N":
>         RoomFour()
>     elif Command == "S":
>         print "You ditched the creepy castle and headed for the road."
>         keepGoing == False
>     elif Command == "E":
>         RoomTwo()
>     elif Command == "HELP":
>         print "List of Commands: 'Help',then enter for this list."
>         print                   "'N', then enter = Door to the North."
>         print                   "'S', then enter = Door to the South."
>         print                   "'E', then enter = Door to the East."
>         print                   "'W', then enter = Door to the West."
>         print                   "'Look at', then 'objects name', then 
> enter = Looks at an object."
>         print                   "'Pick Up', then 'objects name', then 
> enter = Picks up an object."
>         print                   "'Q', then enter = Quit Game."
>
>     elif Command == "W":
>         RoomSix()
>     elif Command == "LOOK AT FOUNTAIN":
>         print "There appears to be 4 gold coins in it."
>     elif Command == "PICK UP 4 GOLD COINS":
>         gold = gold + 4
>         print "Current Gold = ", gold
>     elif Command == "Q":
>         keepGoing = False
>     else:
>         print "That doesn't work."
>
>     def RoomTwo():
>         print "Current Gold = ", gold
>         print "In the middle of the room is a large Gargoyle with 
> fiery red eyes."
>         print "He's holding a cup. In the southeast corner of the room 
> you see a broom"
>         print "with dust and cob-webs on it. Next to the broom is a 
> dead rat."
>         print "To the north is another door. In front of the door is 
> an overturned basket."
>
>     promptTwo = raw_input("What are you going to do? ")
>     promptTwo = promptTwo.upper()
>
>     if promptTwo == "N":
>         RoomThree()
>     elif promptTwo == "S":
>         print "There is no door there."
>     elif promptTwo == "W":
>         RoomOne()
>     elif promptTwo == "E":
>         print "There is only a wall there."
>     elif promptTwo == "Q":
>         keepGoing = False
>     elif promptTwo == "PICK UP BASKET":
>         print "You pick up the basket, revealing 2 gold pieces."
>         RoomTwo()
>     elif promptTwo == "PICK UP 2 GOLD COINS":
>         gold = gold + 2
>         print "Current Gold = ", gold
>         RoomTwo()
>     elif promptTwo == "LOOK AT GARGOYLE":
>         print "Looking at the Gargoyle you notice he's really mean, 
> and really still."
>         RoomTwo()
>     elif promptTwo == "LOOK AT BROOM":
>         print "Looking at the broom, you notice it's unnecessarity dirty."
>     elif promptTwo == "PICK UP BROOM":
>         print " You pick up the broom. But you don't notice anything 
> special, so you"
>         print "set it back down where it was."
>     elif promptTwo == "LOOK AT CUP":
>         print "You look at the cup, and find nothing of interest."
>     elif promptTwo == "LOOK AT DEAD RAT":
>         print "You look at the dead rat and find it utterly disgusting."
>     elif promptTwo == "HELP":
>         print "List of Commands: 'Help',then enter for this list."
>         print                   "'N', then enter = Door to the North."
>         print                   "'S', then enter = Door to the South."
>         print                   "'E', then enter = Door to the East."
>         print                   "'W', then enter = Door to the West."
>         print                   "'Look at', then 'objects name', then 
> enter = Looks at an object."
>         print                   "'Pick Up', then 'objects name', then 
> enter = Picks up an object."
>         print                   "'Q', then enter = Quit Game."
>     else:
>         print "That didn't work."
>
>
>     def RoomThree():
>         print "Current Gold = ", gold
>         print "To the north is a giant replica of a wooley mamoth. 
>  His tusks are made"
>         print "of gold. To the east is a painting of Mother Theresa. 
>  Under the painting"
>         print "is a baby's crib. The only doors you see are to the 
> south and west."
>
>     promptThree = raw_input("What would you like to do? ")
>     promptThree = promptThree.upper()
>
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From alan.gauld at btinternet.com  Sat Aug 28 10:57:46 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 28 Aug 2010 09:57:46 +0100
Subject: [Tutor] help, complete beginner please!
References: 
Message-ID: 


"kevin hayes"  wrote

> Hi all! I'm trying to write a basic text adventure game to start 
> learning
> python (just for fun). I've gone through the first four chapters of 
> a "learn
> python game programming book" and I'm having trouble with the 
> exercise on
> writing a text adventure.

Sorry I don't know the book but...

>         I'm looking for the simplest version of this as possible, 
> because
> I'm having trouble with the concepts.

What is your programming background? Have you programmed in
any other language before or is Python your fist?

> an idea where I'm at. However, I would really like someone to lay 
> out a
> little code structure for me.

I think you are maybe trying to run too fast.

Its good practice in programming to build things up slowly, pece by 
piece.
In your case forget about the loop initially. Just write the 
individual functions
and test each one individually. Once you get the functions working on
their own you can start to build the structure to call them. [This 
approach
is known as bottom-up programming in case you are interested]

This approach is particularl;y powerful in a language like Python 
because
if you put the functions in a file you can import that file as a 
module
(have you covered modules yet?)

Then at the intreractive prompt(>>>) you can interactively test your
functions to check they work.

>
> keepGoing = True
> while keepGoing == True:
>
>    global gold

You don;t need this global is only used inside a function definition
so that the function can modify variables outside the function.
You are not inside a function at this point.

>    gold = 0
>
>    def RoomOne():

Here you are defining a function inside the while loop.
So you will redefine the function every time through the loop.
This is wasteful and not needed. Take the definition
outside the loop.

>        print "You find yourself in a large room. Above you is a 
> massive
> crystal"
>        print "chandelier. In front of you is round stone fountain, 
> spewing
> water"
>        print "from it's center. On the walls hang green satin 
> drapery.  The
> ceiling"
>        print "is comprised of three ornate arches. There is an arch 
> in
> front of you"
>        print "and to your right and left. A staircase leads up from 
> under
> the arch"
>        print "in front of you. Under the arches to your left and 
> right are
> large wooden"
>        print "doors, each with an iron handle. Enter 'Help' for a 
> full list
> of commands."

Use a triple quoted string to avoid multiple print statements.

>    RoomOne()
>    Command = raw_input("Please enter a command. ")
>    Command = Command.upper()
>    if Command == "N":
>        RoomFour()
>    elif Command == "S":
>        print "You ditched the creepy castle and headed for the 
> road."
>        keepGoing == False
>    elif Command == "E":
>        RoomTwo()
>    elif Command == "HELP":
>        print "List of Commands: 'Help',then enter for this list."
>        print                   "'N', then enter = Door to the 
> North."
>        print                   "'S', then enter = Door to the 
> South."
>        print                   "'E', then enter = Door to the East."
>        print                   "'W', then enter = Door to the West."
>        print                   "'Look at', then 'objects name', then 
> enter
> = Looks at an object."
>        print                   "'Pick Up', then 'objects name', then 
> enter
> = Picks up an object."
>        print                   "'Q', then enter = Quit Game."
>
>    elif Command == "W":
>        RoomSix()
>    elif Command == "LOOK AT FOUNTAIN":
>        print "There appears to be 4 gold coins in it."
>    elif Command == "PICK UP 4 GOLD COINS":
>        gold = gold + 4
>        print "Current Gold = ", gold
>    elif Command == "Q":
>        keepGoing = False
>
>    else:
>        print "That doesn't work."
>
>    def RoomTwo():
>        print "Current Gold = ", gold
>        print "In the middle of the room is a large Gargoyle with 
> fiery red
> eyes."
>        print "He's holding a cup. In the southeast corner of the 
> room you
> see a broom"
>        print "with dust and cob-webs on it. Next to the broom is a 
> dead
> rat."
>        print "To the north is another door. In front of the door is 
> an
> overturned basket."
>
>    promptTwo = raw_input("What are you going to do? ")
>    promptTwo = promptTwo.upper()
>
>    if promptTwo == "N":
>        RoomThree()
>    elif promptTwo == "S":
>        print "There is no door there."
>    elif promptTwo == "W":
>        RoomOne()
>    elif promptTwo == "E":
>        print "There is only a wall there."
>    elif promptTwo == "Q":
>        keepGoing = False
>    elif promptTwo == "PICK UP BASKET":
>        print "You pick up the basket, revealing 2 gold pieces."
>        RoomTwo()
>    elif promptTwo == "PICK UP 2 GOLD COINS":
>        gold = gold + 2
>        print "Current Gold = ", gold
>        RoomTwo()
>    elif promptTwo == "LOOK AT GARGOYLE":
>        print "Looking at the Gargoyle you notice he's really mean, 
> and
> really still."
>        RoomTwo()
>    elif promptTwo == "LOOK AT BROOM":
>        print "Looking at the broom, you notice it's unnecessarity 
> dirty."
>    elif promptTwo == "PICK UP BROOM":
>        print " You pick up the broom. But you don't notice anything
> special, so you"
>        print "set it back down where it was."
>    elif promptTwo == "LOOK AT CUP":
>        print "You look at the cup, and find nothing of interest."
>    elif promptTwo == "LOOK AT DEAD RAT":
>        print "You look at the dead rat and find it utterly 
> disgusting."
>    elif promptTwo == "HELP":
>        print "List of Commands: 'Help',then enter for this list."
>        print                   "'N', then enter = Door to the 
> North."
>        print                   "'S', then enter = Door to the 
> South."
>        print                   "'E', then enter = Door to the East."
>        print                   "'W', then enter = Door to the West."
>        print                   "'Look at', then 'objects name', then 
> enter
> = Looks at an object."
>        print                   "'Pick Up', then 'objects name', then 
> enter
> = Picks up an object."
>        print                   "'Q', then enter = Quit Game."
>    else:
>        print "That didn't work."
>
>
>    def RoomThree():
>        print "Current Gold = ", gold
>        print "To the north is a giant replica of a wooley mamoth. 
> His
> tusks are made"
>        print "of gold. To the east is a painting of Mother Theresa. 
> Under
> the painting"
>        print "is a baby's crib. The only doors you see are to the 
> south and
> west."
>
>    promptThree = raw_input("What would you like to do? ")
>    promptThree = promptThree.upper()
>
You could improve the generality of the code by building a data model
of your castle using a multi dimensional list.

Rooms = [[Room3, Room4,NotExist],
               [Room0,Room1,Room2]]

You can access your functions like:

Rooms[X][Y]()

Now you can define your movement commands as arithmetic operations
on the indices of the Rooms map, eg:

N increment the Y index
S decrement the Y index
E increment the X index
W decrement the X index

If you pass the direction value as a parameter the room functions can
check if a valid entrance exists on that side. So in Room3 you might 
have:

def Room3(dir):
    if dir == 'N':
        raise NoDoorError, "Cannot enter Room3 from the South"
     # rest of code here

Just some ideas.

HTH,
-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/






From rwobben at hotmail.com  Sat Aug 28 18:54:28 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sat, 28 Aug 2010 16:54:28 +0000
Subject: [Tutor] import prroblem
Message-ID: 


Hello, 

Im trying to do a import on a linux machine.
But now Im gettting this message :

Python 2.6.5 (r265:79063, Apr  1 2010, 05:28:39) 
[GCC 4.4.3 20100316 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import calender
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named calender
>>> 

But the module calender exist
I can be found here : /usr/lib/python26/site-packages

How to solve this one ?

Roelof

 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From joel.goldstick at gmail.com  Sat Aug 28 19:13:07 2010
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Sat, 28 Aug 2010 13:13:07 -0400
Subject: [Tutor] import prroblem
In-Reply-To: 
References: 
Message-ID: 

But the module calender exist
> I can be found here : /usr/lib/python26/site-packages
>
> How to solve this one ?
>
> Roelof
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
it is spelled wrong -- should be calendar


-- 
Joel Goldstick
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From christopher.henk at allisontransmission.com  Sat Aug 28 19:21:36 2010
From: christopher.henk at allisontransmission.com (christopher.henk at allisontransmission.com)
Date: Sat, 28 Aug 2010 13:21:36 -0400
Subject: [Tutor] import problem
In-Reply-To: 
Message-ID: 

tutor-bounces+christopher.henk=allisontransmission.com at python.org wrote on 
08/28/2010 12:54:28 PM:

> Hello, 
> 
> Im trying to do a import on a linux machine.
> But now Im gettting this message :
> 
> Python 2.6.5 (r265:79063, Apr  1 2010, 05:28:39) 
> [GCC 4.4.3 20100316 (prerelease)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import calender
> Traceback (most recent call last):
>   File "", line 1, in 
> ImportError: No module named calender
> >>> 

Did you try calendar (with an 'a')?  it might have just been a spelling 
mistake in your import

Can you do other imports from site-packages?


Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From bgailer at gmail.com  Sat Aug 28 19:39:01 2010
From: bgailer at gmail.com (bob gailer)
Date: Sat, 28 Aug 2010 13:39:01 -0400
Subject: [Tutor] help, complete beginner please! CORRECTION
In-Reply-To: 
References: 
Message-ID: <4C7949B5.4020908@gmail.com>

  Thanks to Luke for pointing out that Room1() did not return anything. 
I now add a return statement:

9) have the functions return text rather than printing it. Use triple 
quoted text. e.g.:

def Room1():
   description = """You find yourself in a large room. Above you is a 
massive crystal
chandelier. In front of you is round stone fountain, spewing water."""
    return description


-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From rwobben at hotmail.com  Sat Aug 28 19:41:58 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Sat, 28 Aug 2010 17:41:58 +0000
Subject: [Tutor] import prroblem
In-Reply-To: 
References: ,
	
Message-ID: 




> Date: Sat, 28 Aug 2010 10:24:06 -0700
> Subject: Re: [Tutor] import prroblem
> From: thudfoo at opensuse.us
> To: rwobben at hotmail.com
> 
> On Sat, Aug 28, 2010 at 9:54 AM, Roelof Wobben  wrote:
> > Hello,
> >
> > Im trying to do a import on a linux machine.
> > But now Im gettting this message :
> >
> > Python 2.6.5 (r265:79063, Apr  1 2010, 05:28:39)
> > [GCC 4.4.3 20100316 (prerelease)] on linux2
> > Type "help", "copyright", "credits" or "license" for more information.
> >>>> import calender
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > ImportError: No module named calender
> >>>>
> >
> > But the module calender exist
> > I can be found here : /usr/lib/python26/site-packages
> >
> > How to solve this one ?
> 
> Spell it "calendar" if you want the one in the standard library.

Hello Everyone,

I was a stupid typo from me.
Sorry for the troubles,

Roelof

 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From amartin7211 at gmail.com  Sat Aug 28 20:29:43 2010
From: amartin7211 at gmail.com (Andrew Martin)
Date: Sat, 28 Aug 2010 14:29:43 -0400
Subject: [Tutor] Trouble with exercise regarding classes
In-Reply-To: 
References: 
	
	
	
Message-ID: 

Ok I think I got it. Thanks everybody. And sorry for the late reply. My
classes have just started so learned python unfortunately must be bumped
down on the priority list

On Thu, Aug 26, 2010 at 4:32 AM, Alan Gauld wrote:

>
> "Andrew Martin"  wrote
>
>  I want to compare zenith, a floating point number, with the current y
>> value?
>> I thought the current y value could be retrieved by Projectile.getY.
>>
>
> Projectile.getY is a reference to the getY method of the Projectile class.
> (See the separate thread on function objects for more on this topic)
>
> You want to execute the method so you need parens on the end.
>
> But, you also want to execute it for the cball instance.
> You have already done this earlier in your code, here:
>
>    while cball.getY() >= 0:
>>>>>
>>>>
> So you just need to make the if test compatible with that:
>
>
>         if Projectile.getY > zenith:
>>>
>>
> becomes
>
>           if cball.getY() > zenith:
>
> And similarly for the assignment
>
>            zenith = Projectile.getY()
>>>>>
>>>> becomes
>                   zenith = cball.getY()
>
>
> As an aside you can do this using Projectile, but its bad practice:
>
> Projectile.getY(cball)
>
> This explicitly provides the self argument instead of Python doing
> it for you when you use the instance. We can use this technique when
> calling inherited methods inside a class method definition. Anywhere
> else its best to use the instance to call a method.
>
> HTH,
>
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nitin.162 at gmail.com  Sun Aug 29 05:21:40 2010
From: nitin.162 at gmail.com (Nitin Das)
Date: Sun, 29 Aug 2010 08:51:40 +0530
Subject: [Tutor] import problem
In-Reply-To: 
References: 
	
Message-ID: 

it is >>> import calendar not calender

--nitin

On Sat, Aug 28, 2010 at 10:51 PM,
wrote:

>
>
> tutor-bounces+christopher.henk=allisontransmission.com at python.org wrote on
> 08/28/2010 12:54:28 PM:
>
> > Hello,
> >
> > Im trying to do a import on a linux machine.
> > But now Im gettting this message :
> >
> > Python 2.6.5 (r265:79063, Apr  1 2010, 05:28:39)
> > [GCC 4.4.3 20100316 (prerelease)] on linux2
> > Type "help", "copyright", "credits" or "license" for more information.
> > >>> import calender
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > ImportError: No module named calender
> > >>>
>
> Did you try calendar (with an 'a')?  it might have just been a spelling
> mistake in your import
>
> Can you do other imports from site-packages?
>
>
> Chris
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nblack3 at student.gsu.edu  Sun Aug 29 09:08:24 2010
From: nblack3 at student.gsu.edu (Nick)
Date: Sun, 29 Aug 2010 07:08:24 +0000
Subject: [Tutor] project euler prime factorization problem
Message-ID: 

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

#don't forget 2,3,5,7.  this function doesn't deliver those as output.

def is_prime(b):  #checks a number greater than 7 to see if it is prime and returns if is.
    if b % 2 != 0 and b % 3 != 0 and b % 5 != 0 and b % 7 != 0:
        print b,

def factor(num):
    x = num
    b = 1
    c = num
    while b <= c:       #starts at 1 and searches all the numbers up to the number you put in
        if x % b == 0:
            is_prime(b)
            b += 1
        else:
            b += 1

print "Don't forget to consider primes 2, 3, 5, and 7\n"


#600851475143

#shows what numbers in given range are prime
'''
def is_prime(b):
    return [2,3,5,7] + [x for x in xrange(3, 10000, 2) if x % 2 != 0 and x % 3 != 0 and x % 5 != 0 and x % 7 != 0]
'''

I'm looking for some help with this problem.  I realize my code is inefficient for such a big number, and also I'm not quite sure it works perfectly in and of itself.

My current reasoning was something of this sort:  Find all the factors of a number, then reduce them to just the prime factors and you can then multiply them together to get that number thus having the prime factors.  I need a lot of help haha.  Thanks in advance everyone.  If anyone has a good resource to point me to other than the open book project and dive into python it would be much appreciated.  Would it be useful for me to buy a book, and if so what are some easily accessible ones?  I feel dive into python is just too advanced for me.  I understand a lot of the teachings, but the examples seem unwieldy and esoteric.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From alan.gauld at btinternet.com  Sun Aug 29 09:56:31 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 29 Aug 2010 08:56:31 +0100
Subject: [Tutor] project euler prime factorization problem
References: 
Message-ID: 


"Nick"  wrote

> What is the largest prime factor of the number 600851475143 ?

For help on the math aspects try Wikipedia.
Look up Prime factors...

>   Would it be useful for me to buy a book, and if so what are some
> easily accessible ones?  I feel dive into python is just too 
> advanced for me.
> I understand a lot of the teachings, but the examples seem unwieldy 
> and esoteric.

If you have programmed before in any language just use the standard 
Python tutorial.
If not choose one of the several tutorials on the Non Programmes 
beginners page.

Without knowing more about your personal needs and objectives its 
impossible
to be any more specific.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/






--------------------------------------------------------------------------------


> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 



From fomcl at yahoo.com  Sun Aug 29 13:23:47 2010
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Sun, 29 Aug 2010 04:23:47 -0700 (PDT)
Subject: [Tutor] more on wx and tiff
In-Reply-To: <11704.1631.qm@web110705.mail.gq1.yahoo.com>
References: <733084.22051.qm@web110713.mail.gq1.yahoo.com>
	
	<11704.1631.qm@web110705.mail.gq1.yahoo.com>
Message-ID: <689886.7617.qm@web110711.mail.gq1.yahoo.com>

Hi,

Got it. Thought it would be nice to share it. What set me on the wrong foot 
completely was that writing gif files is not possible due to copyright issues.
Below is a very simple version of a conversion function for Group 4 Tif to png.

import wx, os, time

def g4TifToPng(tif, png = None):
    if png is None:
        png = os.path.splitext(tif)[0] + ".png"
    myImg = wx.Image(tif)
    if myImg.GetImageCount(tif) == 2:
        SECONDPAGE = 1
        myImg = wx.Image(tif, type = wx.BITMAP_TYPE_TIF, index = SECONDPAGE)
        # myImg = myImg.GetSubImage((0, 2338, 3304, 2338)) # offset h & w, rect 
h & w
        myImg.SaveFile(png, wx.BITMAP_TYPE_PNG)
        newW, newH = myImg.GetSize()
        print "%s:: writing file %s (%s x %s pixels)" % \
              (time.strftime("%H:%M:%S"), png, newW, newH)
        
g4TifToPng(tif = "c:/temp/somefile.tif")



 Cheers!!
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?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~




________________________________
From: Albert-Jan Roskam 
To: Wayne Werner 
Cc: Python Mailing List 
Sent: Fri, August 27, 2010 8:00:16 PM
Subject: Re: [Tutor] more on wx and tiff


Hi Wayne,

Yep, I considered using PIL, but that package won't read so-called Group 4 Tiffs 
[1]. They're two-page, black-and-white scanned forms. I need part of the second 
form (i.e., the backside of a certificate). The page contains some hand-written 
info which needs to be presented in a simple data entry program, which I made 
using Tkinter.

The forms are confidential so they may not leave the company network. And the IT 
droids are somewhat paranoid so it's very time-consuming to get some new 
executable 'inside' the company network. Beeeh, formalities... :-(

 
[1] http://www.digitalpreservation.gov/formats/fdd/fdd000024.shtml

Cheers!!
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?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~




________________________________
From: Wayne Werner 
To: Albert-Jan Roskam 
Cc: Python Mailing List 
Sent: Fri, August 27, 2010 6:44:04 PM
Subject: Re: [Tutor] more on wx and tiff


On Fri, Aug 27, 2010 at 11:25 AM, Albert-Jan Roskam  wrote:

Hi again,
>
>Some more questions about tiff conversion. 
>
>First, thanks for your previous replies. I cannot use IrfanView any time soon, 
>nor will my boss switch to Linux. 
>
>

Have you tried using the PIL?
http://www.pythonware.com/products/pil/

import Image
i = Image.open("file.tiff")
i.save(open('file.png', 'w'), filetype='png')

I don't know if that was previously suggested, but it should work on any 
platform with PIL installed. 

HTH,
Wayne



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From aeneas24 at priest.com  Sun Aug 29 20:12:06 2010
From: aeneas24 at priest.com (aeneas24 at priest.com)
Date: Sun, 29 Aug 2010 14:12:06 -0400
Subject: [Tutor] Adding to a CSV file?
Message-ID: <8CD15BCD305C752-1490-1989B@web-mmc-d06.sysops.aol.com>


Hi,
 
I'm learning Python so I can take advantage of the really cool stuff in the Natural Language Toolkit. But I'm having problems with some basic file manipulation stuff.
 
My basic question: How do I read data in from a csv, manipulate it, and then add it back to the csv in new columns (keeping the manipulated data in the "right row")?
 
Here's an example of what my data looks like ("test-8-29-10.csv"):
 



MyWord

Category

Ct

CatCt


!

A

2932

456454


!

B

2109

64451


a

C

7856

90000


a

A

19911

456454


abnormal

C

174

90000


abnormally

D

5

77777


cats

E

1999

886454


cat

B

160

64451



 
# I want to read in the MyWord for each row and then do some stuff to it and add in some new columns. Specifically, I want to "lemmatize" and "stem", which basically means I'll turn "abnormally" into "abnormal" and "cats" into "cat".
 
import nltk
wnl=nltk.WordNetLemmatizer()
porter=nltk.PorterStemmer()
text=nltk.word_tokenize(TheStuffInMyWordColumn)
textlemmatized=[wnl.lemmatize(t) for t in text]
textPort=[porter.stem(t) for t in text]
 
# This creates the right info, but I don't really want "textlemmatized" and "textPort" to be independent lists, I want them inside the csv in new columns. 
 
# If I didn't want to keep the information in the Category and Counts columns, I would probably do something like this:
 
for word in text:
word2=wnl.lemmatize(word)
word3=porter.stem(word)
print word+";"+word2+";"+word3+"\r\n")
 
# Looking through some of the older discussions about the csv module, I found this code helps identify headers, but I'm still not sure how to use them--or how to word the for-loop that I need correctly so I iterate through each row in the csv file. 
 
f_out.close()
fp=open(r'c:test-8-29-10.csv', 'r')
inputfile=csv.DictReader(fp)
for record in inputfile:
print record
{'Category': 'A', 'CatCt': '456454', 'MyWord': '!', 'Ct': '2932'}
{'Category': 'B', 'CatCt': '64451', 'MyWord': '!', 'Ct': '2109'}
...
fp.close() 
 
# So I feel like I have *some* of the pieces, but I'm just missing a bunch of little connections. Any and all help would be much appreciated!
 
Tyler
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From bgailer at gmail.com  Sun Aug 29 21:31:00 2010
From: bgailer at gmail.com (bob gailer)
Date: Sun, 29 Aug 2010 15:31:00 -0400
Subject: [Tutor] project euler prime factorization problem
In-Reply-To: 
References: 
Message-ID: <4C7AB574.6070206@gmail.com>

  On 8/29/2010 3:08 AM, Nick wrote:
>
> The prime factors of 13195 are 5, 7, 13 and 29.
>
> What is the largest prime factor of the number 600851475143 ?
>
> #don't forget 2,3,5,7.  this function doesn't deliver those as output.
>
> def is_prime(b):  #checks a number greater than 7 to see if it is 
> prime and returns if is.
>     if b % 2 != 0 and b % 3 != 0 and b % 5 != 0 and b % 7 != 0:
>         print b,
> def factor(num):
>     x = num
>     b = 1
>     c = num
>     while b <= c:       #starts at 1 and searches all the numbers up 
> to the number you put in
>         if x % b == 0:
>             is_prime(b)
>             b += 1
>         else:
>             b += 1
>
> print "Don't forget to consider primes 2, 3, 5, and 7\n"
>
>
> #600851475143
>
> #shows what numbers in given range are prime
> '''
> def is_prime(b):
>     return [2,3,5,7] + [x for x in xrange(3, 10000, 2) if x % 2 != 0 
> and x % 3 != 0 and x % 5 != 0 and x % 7 != 0]
> '''
>
> I'm looking for some help with this problem.  I realize my code is 
> inefficient for such a big number, and also I'm not quite sure it 
> works perfectly in and of itself.

Did you test the program? That is one way to tell whether it works 
perfectly. What you showed above will do one visible thing - it will 
print "Don't forget to consider primes 2, 3, 5, and 7\n". The rest is a 
somewhat confusing collection of function definitions and comments. You 
never call the functions so nothing else will happen.

As Alan said - research prime factors to see how others approach it.
>
> My current reasoning was something of this sort:  Find all the factors 
> of a number, then reduce them to just the prime factors

Very inefficient. IMHO the proper way is to generate a list of all the 
prime numbers up to the square root of 600851475143, then test each 
(starting with the largest and working down) till you discover a factor. 
That then is the answer.

There are many published algorithms for generating primes.

> and you can then multiply them together to get that number thus having 
> the prime factors.  I need a lot of help haha.  Thanks in advance 
> everyone.  If anyone has a good resource to point me to other than the 
> open book project and dive into python it would be much appreciated. 
>  Would it be useful for me to buy a book, and if so what are some 
> easily accessible ones?  I feel dive into python is just too advanced 
> for me.  I understand a lot of the teachings, but the examples seem 
> unwieldy and esoteric.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nblack3 at student.gsu.edu  Sun Aug 29 23:58:48 2010
From: nblack3 at student.gsu.edu (Nick)
Date: Sun, 29 Aug 2010 21:58:48 +0000
Subject: [Tutor] project euler prime factorization problem
In-Reply-To: <4C7AB574.6070206@gmail.com>
References: ,
	<4C7AB574.6070206@gmail.com>
Message-ID: 

"Did you test the program? That is one way to tell whether it works perfectly. What you showed above will do one visible thing - it will print "Don't forget to consider primes 2, 3, 5, and 7\n". The rest is a somewhat confusing collection of function definitions and comments. You never call the functions so nothing else will happen.

As Alan said - research prime factors to see how others approach it.

My current reasoning was something of this sort:  Find all the factors of a number, then reduce them to just the prime factors

Very inefficient. IMHO the proper way is to generate a list of all the prime numbers up to the square root of 600851475143, then test each (starting with the largest and working down) till you discover a factor. That then is the answer.

There are many published algorithms for generating primes.

and you can then multiply them together to get that number thus having the prime factors.  I need a lot of help haha.  Thanks in advance everyone.  If anyone has a good resource to point me to other than the open book project and dive into python it would be much appreciated.  Would it be useful for me to buy a book, and if so what are some easily accessible ones?  I feel dive into python is just too advanced for me.  I understand a lot of the teachings, but the examples seem unwieldy and esoteric.


--
Bob Gailer
"


Yeah, thanks everyone for the comments.  I will follow your advice Bob.  I didn't call the

functions in the program because I was calling them myself in the interpreter after running it.  I

don't know if that is the way everyone else programs, but I just write it in idle and save it and run

it over and over making sure it is doing what I want
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From steve at pearwood.info  Mon Aug 30 01:34:59 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 30 Aug 2010 09:34:59 +1000
Subject: [Tutor] project euler prime factorization problem
In-Reply-To: <4C7AB574.6070206@gmail.com>
References: 
	<4C7AB574.6070206@gmail.com>
Message-ID: <201008300934.59627.steve@pearwood.info>

On Mon, 30 Aug 2010 05:31:00 am bob gailer wrote:

> > My current reasoning was something of this sort:  Find all the
> > factors of a number, then reduce them to just the prime factors
>
> Very inefficient. IMHO the proper way is to generate a list of all
> the prime numbers up to the square root of 600851475143, then test
> each (starting with the largest and working down) till you discover a
> factor. That then is the answer.


Actually your approach is inefficient too, and it won't always work. 
Consider what happens if you are asked for the prime factors of 101. 
You would generate the primes up to 10:

2, 3, 5, 7

but none of those are factors.

In the case of 600851475143, you wastefully generate 62113 prime numbers 
when you actually only need 224.

The right way is to start at 2, then 3, and so forth, working up rather 
than down. Don't forget that there can be repeated factors.



-- 
Steven D'Aprano

From alan.gauld at btinternet.com  Mon Aug 30 02:19:47 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 30 Aug 2010 01:19:47 +0100
Subject: [Tutor] project euler prime factorization problem
References: ,
	<4C7AB574.6070206@gmail.com>
	
Message-ID: 


"Nick"  wrote

>   I didn't call the functions in the program because I was
> calling them myself in the interpreter after running it.

I assume you mean after importing it?
Running a program is generally taken to mean executing the script as
a standalone program. To execute the internal functions one has to
import the file as a module.

> ...know if that is the way everyone else programs,

Its a good way of developing code because you get instant feedback
but its not a comprehensive or reliable way to test code, for that you
are better creating a set of systematic tests checking upper and
lower boundaries as well as midrange and out of range values plus
various types of invalid inputs.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From davea at ieee.org  Mon Aug 30 03:32:35 2010
From: davea at ieee.org (Dave Angel)
Date: Sun, 29 Aug 2010 21:32:35 -0400
Subject: [Tutor] project euler prime factorization problem
In-Reply-To: <201008300934.59627.steve@pearwood.info>
References: 	<4C7AB574.6070206@gmail.com>
	<201008300934.59627.steve@pearwood.info>
Message-ID: <4C7B0A33.3080004@ieee.org>

Steven D'Aprano wrote:
> On Mon, 30 Aug 2010 05:31:00 am bob gailer wrote:
>
>   
>>> My current reasoning was something of this sort:  Find all the
>>> factors of a number, then reduce them to just the prime factors
>>>       
>> Very inefficient. IMHO the proper way is to generate a list of all
>> the prime numbers up to the square root of 600851475143, then test
>> each (starting with the largest and working down) till you discover a
>> factor. That then is the answer.
>>     
>
>
> Actually your approach is inefficient too, and it won't always work. 
> Consider what happens if you are asked for the prime factors of 101. 
> You would generate the primes up to 10:
>
> 2, 3, 5, 7
>
> but none of those are factors.
>
> 
I agree about inefficient, but not "won't always work."

If you've got a list of all the primes up to the square root of n, and 
none of them are factors, then n is prime as well.  Not necessarily the 
next prime in the list, but prime nonetheless.  So perhaps you're 
objecting that Bob didn't say the else-portion of his algorithm -  He 
said "till you discover a factor" but neglected to say what it means if 
you don't.  If you don't, then the value 600851475143 is prime.  So the 
number would be its own largest prime factor.

DaveA


From gregbair at gmail.com  Mon Aug 30 04:26:50 2010
From: gregbair at gmail.com (Greg Bair)
Date: Sun, 29 Aug 2010 22:26:50 -0400
Subject: [Tutor] Adding to a CSV file?
In-Reply-To: <8CD15BCD305C752-1490-1989B@web-mmc-d06.sysops.aol.com>
References: <8CD15BCD305C752-1490-1989B@web-mmc-d06.sysops.aol.com>
Message-ID: <4C7B16EA.5040703@gmail.com>

On 08/29/2010 02:12 PM, aeneas24 at priest.com wrote:
> 
> Hi,
>  
> I'm learning Python so I can take advantage of the really cool stuff in the Natural Language Toolkit. But I'm having problems with some basic file manipulation stuff.
>  
> My basic question: How do I read data in from a csv, manipulate it, and then add it back to the csv in new columns (keeping the manipulated data in the "right row")?
>  
> Here's an example of what my data looks like ("test-8-29-10.csv"):

Python has a great module in the standard library - csv.  It's really
easy to use.

http://docs.python.org/library/csv.html

Greg

From rwobben at hotmail.com  Mon Aug 30 11:44:06 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Mon, 30 Aug 2010 09:44:06 +0000
Subject: [Tutor] can this be done easerly
Message-ID: 


Hello,

 

For a exerise I made this one :"

 

import string

def extract_words(s):
    """
      >>> extract_words('Now is the time!  "Now", is the time? Yes, now.')
      ['now', 'is', 'the', 'time', 'now', 'is', 'the', 'time', 'yes', 'now']
      >>> extract_words('she tried to curtsey as she spoke--fancy')
      ['she', 'tried', 'to', 'curtsey', 'as', 'she', 'spoke', 'fancy']
    """
    word= ""
    s=string.lower(s)
    for char in s :
        if ord(char) >=65 and ord(char) <= 122 or ord(char)==32 or ord(char)==45:
              word= word + char 
    word=string.split(word, "--")
    word=string.join(word, " ")
    word=word.replace ("  ", " ")
    word=string.split(word, " ")
    return word
        
if __name__ == '__main__':
    import doctest
    doctest.testmod()

 

But now I wonder if this can be done more easerly ?

 

Roelof

 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From evert.rol at gmail.com  Mon Aug 30 12:04:08 2010
From: evert.rol at gmail.com (Evert Rol)
Date: Mon, 30 Aug 2010 12:04:08 +0200
Subject: [Tutor] can this be done easerly
In-Reply-To: 
References: 
Message-ID: 

> For a exerise I made this one :"
>  
> import string
> def extract_words(s):
>     """
>       >>> extract_words('Now is the time!  "Now", is the time? Yes, now.')
>       ['now', 'is', 'the', 'time', 'now', 'is', 'the', 'time', 'yes', 'now']
>       >>> extract_words('she tried to curtsey as she spoke--fancy')
>       ['she', 'tried', 'to', 'curtsey', 'as', 'she', 'spoke', 'fancy']
>     """
>     word= ""
>     s=string.lower(s)
>     for char in s :
>         if ord(char) >=65 and ord(char) <= 122 or ord(char)==32 or ord(char)==45:
>               word= word + char 
>     word=string.split(word, "--")
>     word=string.join(word, " ")
>     word=word.replace ("  ", " ")
>     word=string.split(word, " ")
>     return word
>         
> if __name__ == '__main__':
>     import doctest
>     doctest.testmod()
>  
> But now I wonder if this can be done more easerly ?

Using regular expressions could work, depending on your view of regular expressions being 'easy':

import re
re.split('\W+', s.lower()) 

will do most of what you want (though you'll end up with the occasional empty string.

  Evert


From rwobben at hotmail.com  Mon Aug 30 12:09:00 2010
From: rwobben at hotmail.com (Roelof Wobben)
Date: Mon, 30 Aug 2010 10:09:00 +0000
Subject: [Tutor] can this be done easerly
In-Reply-To: 
References: ,
	
Message-ID: 



 

> Subject: Re: [Tutor] can this be done easerly
> From: evert.rol at gmail.com
> Date: Mon, 30 Aug 2010 12:04:08 +0200
> CC: tutor at python.org
> To: rwobben at hotmail.com
> 
> > For a exerise I made this one :"
> > 
> > import string
> > def extract_words(s):
> > """
> > >>> extract_words('Now is the time! "Now", is the time? Yes, now.')
> > ['now', 'is', 'the', 'time', 'now', 'is', 'the', 'time', 'yes', 'now']
> > >>> extract_words('she tried to curtsey as she spoke--fancy')
> > ['she', 'tried', 'to', 'curtsey', 'as', 'she', 'spoke', 'fancy']
> > """
> > word= ""
> > s=string.lower(s)
> > for char in s :
> > if ord(char) >=65 and ord(char) <= 122 or ord(char)==32 or ord(char)==45:
> > word= word + char 
> > word=string.split(word, "--")
> > word=string.join(word, " ")
> > word=word.replace (" ", " ")
> > word=string.split(word, " ")
> > return word
> > 
> > if __name__ == '__main__':
> > import doctest
> > doctest.testmod()
> > 
> > But now I wonder if this can be done more easerly ?
> 
> Using regular expressions could work, depending on your view of regular expressions being 'easy':
> 
> import re
> re.split('\W+', s.lower()) 
> 
> will do most of what you want (though you'll end up with the occasional empty string.
> 
> Evert
> 

 

Hello Evert, 

 

Thank you for the answer.
I following this tutorial (http://openbookproject.net/thinkcs/python/english2e/) and till chapter 10 there is no talking about regular expressions.
So this is not easy for me.

But thanks , I will read on regular expressions so I understand that one too.

 

Roelof


 
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From alan.gauld at btinternet.com  Mon Aug 30 12:34:10 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 30 Aug 2010 11:34:10 +0100
Subject: [Tutor] can this be done easerly
References: 
Message-ID: 

"Roelof Wobben"  wrote

> import string

I know your tutorial uses the string module but you really should
get out of that habit. It will not work in the newer versions of 
Python
and is less efficient that using the builtin methods.
And invariably requires more typing! :-)

def extract_words(s):
    """
      >>> extract_words('Now is the time!  "Now", is the time? Yes, 
now.')
      ['now', 'is', 'the', 'time', 'now', 'is', 'the', 'time', 'yes', 
'now']

This is a bad example since it uses " twice in the same string.
It should probably read

      >>> extract_words('Now is the time!  'Now', is the time? Yes, 
now.")

    word= ""
    s=string.lower(s)

So this should be
    s = s.lower()

>    for char in s :
>        if ord(char) >=65 and ord(char) <= 122 or ord(char)==32 or 
> ord(char)==45:
>              word= word + char

You don't really need to process it letter by letter and even if you 
do
you don't need the ord() tests, just use isalpha() etc

if char.isalpha(): word += char

>    word=string.split(word, "--")
>    word=string.join(word, " ")

Becomes

     word = " " .join(word.split('--'))

But you could just have used strip() - see below - or even replace()

 >   word=word.replace ("  ", " ")

But oddly you use the string method here rather than string.replace() 
?
A good choice.

>    word=string.split(word, " ")

    word = word.split(" ")

>    return word

if __name__ == '__main__':
    import doctest
    doctest.testmod()

> But now I wonder if this can be done more easily ?

Yes, you can do it all at the word level and you can remove
the characters you don't want rather than testing for their
presence etc.

Look at the documentation for strip() you will see that you
can provide a list of characters that you want removed.
So a single call to split() followed by strip() on each word
should do the vast bulk of the work for you.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From steve at pearwood.info  Mon Aug 30 14:29:09 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 30 Aug 2010 22:29:09 +1000
Subject: [Tutor] can this be done easerly
In-Reply-To: 
References: 
Message-ID: <201008302229.10302.steve@pearwood.info>

On Mon, 30 Aug 2010 07:44:06 pm Roelof Wobben wrote:
> Hello,
>
>
>
> For a exerise I made this one :"
>
>
>
> import string
>
> def extract_words(s):
[...]

> But now I wonder if this can be done more easerly ?


def extract_words(s):
? ? """
? ? >>> extract_words('Now is the time! ?"Now", is the time?')
 ?  ['now', 'is', 'the', 'time', 'now', 'is', 'the', 'time']
 ?  >>> extract_words('she tried to curtsy as she spoke--fancy')
? ? ['she', 'tried', 'to', 'curtsy', 'as', 'she', 'spoke', 'fancy']
? ? """
? ? s = s.lower()
    # Replace anything that isn't a letter with a space.
    chars = [c if c.isalpha() else " " for c in s]
    s = ''.join(chars)
    words = s.split()
    return words


import doctest
doctest.run_docstring_examples(extract_words, globals())
print extract_words("Hello, world! I ate 6 slices of cheese.")

=> prints:
['hello', 'world', 'i', 'ate', 'slices', 'of', 'cheese']




-- 
Steven D'Aprano

From knacktus at googlemail.com  Mon Aug 30 16:44:08 2010
From: knacktus at googlemail.com (Knacktus)
Date: Mon, 30 Aug 2010 16:44:08 +0200
Subject: [Tutor] Conditional attribute access / key access
Message-ID: <4C7BC3B8.2030403@googlemail.com>

Hey everyone,

I have a huge number of data items coming from a database. So far 
there're no restrictions about how to model the items. They can be 
dicts, objects of a custom class (preferable with __slots__) or namedTuple.

Those items have references to each other using ids. Fresh from the 
database the items look like this (using dicts as examples):

item_1 = {"id": 1, "name": "root", "children_ids": [2, 3]}
item_2 = {"id": 2, "name": "child_1", "children_ids": [4]}
item_3 = {"id": 3, "name": "child_2", "children_ids": [6, 7, 8]}

Now I'd like to resolve the references on demand. For that purpose I 
think about adding another entry in my dicts ("children_obj_refs"):

item_1 = {"id" = 1, "nam"e = "root", "children_ids" = [2, 3], 
"children_obj_refs" = [item_2, item_3]}

To achieve that substitution dynamically on demand I could use a function:

def get_children(item):
     try:
         return item["children_obj_refs"]
     except AttributeError:
         # pseudocode for retrieving items from db based on ids
         fresh_items_from_db = get_items_from_db(item["children_ids"])
         # Now create new dict entry for future usage
         item["children_obj_refs"] = fresh_items_from_db

However, I dislike to have to call a function all the time. I'd rather 
get this done under the hood when accessing the dict with 
item["children_obj_refs"]. So I've looked into subclassing a dict and 
overwriting the __getitem__() method like this:

class TestSubDict(dict):

     def __getitem__(self, key):
         try:
             return self[key]
         except KeyError:
             # load item from db and so on ...

But I run into recursion limit problems.

Any recommendations about that? (I'm not restricted to dicts, custom 
classes are OK to, but with __slots__ to limit memory consumption.)

Many thanks in advance and cheers,

Jan


From fal at libero.it  Mon Aug 30 17:53:12 2010
From: fal at libero.it (Francesco Loffredo)
Date: Mon, 30 Aug 2010 17:53:12 +0200
Subject: [Tutor] Conditional attribute access / key access
In-Reply-To: <4C7BC3B8.2030403@googlemail.com>
References: <4C7BC3B8.2030403@googlemail.com>
Message-ID: <4C7BD3E8.2020607@libero.it>

On 30/08/2010 16.44, Knacktus wrote:
> Hey everyone,
>
> I have a huge number of data items coming from a database. So far
> there're no restrictions about how to model the items. They can be
> dicts, objects of a custom class (preferable with __slots__) or namedTuple.
>
> Those items have references to each other using ids. Fresh from the
> database the items look like this (using dicts as examples):
>
> item_1 = {"id": 1, "name": "root", "children_ids": [2, 3]}
> item_2 = {"id": 2, "name": "child_1", "children_ids": [4]}
> item_3 = {"id": 3, "name": "child_2", "children_ids": [6, 7, 8]}
>
> Now I'd like to resolve the references on demand.

Two questions and one doubt for you:
1- How many "generations" do you want to keep in a single item (call it 
dictionary or list, or record, whatever)? I mean, what if some children 
have children too, and some of those have more children, etc ?

2- Are you SURE that there are no circular references in your database? 
In your example, what if item_3 was
item_3 = {"id": 3, "name": "child_2", "children_ids": [6, 1, 8]}? Is't 
it possible that those recursion limit problems you had could come from 
some circular reference in your data?

d- If the number of data items is really huge, are you sure that you 
want to keep the whole family in memory at the same time? It depends on 
the answer you gave to my question #1, of course, but if retrieving an 
item from your database is quick as it should be, you could use a query 
to resolve the references on demand, and you wouldn't need a special 
structure to hold "the rest of the family". If the retrieval is slow or 
difficult, then the creation of your structure could take a significant 
amount of time.

Hope this helps,
Francesco
-------------- next part --------------

Nessun virus nel messaggio in uscita.
Controllato da AVG - www.avg.com 
Versione: 9.0.851 / Database dei virus: 271.1.1/3100 -  Data di rilascio: 08/29/10 08:34:00

From alan.gauld at btinternet.com  Mon Aug 30 19:01:04 2010
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Mon, 30 Aug 2010 17:01:04 +0000 (GMT)
Subject: [Tutor] can this be done easerly
In-Reply-To: 
References: ,
	
	
Message-ID: <809893.80576.qm@web86701.mail.ird.yahoo.com>



> I tried your suggestion with strip and it looks like this :
 
> import string

You don't need this now

> def extract_words(s):
>    word= ""

You dont need this

>     s2=[]
>     s = string.lower(s)
>     s = s.replace( "--", " ")

You probably don't need this either - just add '-' to the strip set.

>     s = s.split()
>     for word in s:

And you could combine those to

for word in s.split():

>         test = word 
>         test = word.strip('!?,.')

You don't need test, just use

word = word.strip('!?",.-')  #added " and - to your set...

>         s2.append(test)
>     return s2
        
> It works well only I can't get it to work the strip with ". 
> I always get a EOF error message. I tried it with 
> word.strip('!?,.") and with word.strip('!?,./"'') but no go.

It looks like you are mixing quote styles.
Notice how I included the " in the strip() above... 
See if that works for you.

Alan G.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From aeneas24 at priest.com  Mon Aug 30 19:04:48 2010
From: aeneas24 at priest.com (aeneas24 at priest.com)
Date: Mon, 30 Aug 2010 13:04:48 -0400
Subject: [Tutor] Adding to a CSV file?
Message-ID: <8CD167C96A1D7D7-1490-2A14@web-mmc-d06.sysops.aol.com>


I checked out the csv module and got a little further along, but still can't quite figure out how to iterate line by line properly. 

# This shows that I'm reading the file in correctly:

input_file=open("test-8-29-10.csv","rb")
for row in input_file:
   print row

MyWord,Category,Ct,CatCt
!,A,2932,456454
!,B,2109,64451
a,C,7856,90000
abandoned,A,11,456454
....

# But when I try to add columns, I'm only filling in some static value. So there's something wrong with my looping.

testReader=csv.reader(open('test-8-29-10.csv', 'rb'))
for line in testReader:
 for MyWord, Category, Ct, CatCt in testReader:
   text=nltk.word_tokenize(MyWord)
   word2=wnl.lemmatize(word)
   word3=porter.stem(word)
   print MyWord+","+Category+","+Ct+","+CatCt+","+word+","+word2+","+word3+"\r\n"
  
!,A,2932,456454,yrs,yr,yr
!,B,2109,64451,yrs,yr,yr
a,C,7856,90000,yrs,yr,yr
abandoned,A,11,456454,yrs,yr,yr
...

# I tried adding another loop, but it gives me an error.

testReader=csv.reader(open('test-8-29-10.csv', 'rb'))
for line in testReader:
   for MyWord, Category, Ct, CatCt in line:  # I thought this line inside the other was clever, but, uh, not so much
       text=nltk.word_tokenize(MyWord)
       word2=wnl.lemmatize(word)
       word3=porter.stem(word)
  print MyWord+","+Category+","+Ct+","+CatCt+","+word+","+word2+","+word3+"\r\n"
  
Traceback (most recent call last):
  File "", line 2, in 
    for MyWord, Category, Ct, CatCt in line:
ValueError: too many values to unpack



My hope is that once I can figure out this problem, it'll be easy to write the csv file with the csv module. But I'm stumped about the looping.

Thanks for any suggestions,

Tyler
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rabidpoobear at gmail.com  Mon Aug 30 19:44:07 2010
From: rabidpoobear at gmail.com (Luke Paireepinart)
Date: Mon, 30 Aug 2010 12:44:07 -0500
Subject: [Tutor] Adding to a CSV file?
In-Reply-To: <8CD167C96A1D7D7-1490-2A14@web-mmc-d06.sysops.aol.com>
References: <8CD167C96A1D7D7-1490-2A14@web-mmc-d06.sysops.aol.com>
Message-ID: 

On Mon, Aug 30, 2010 at 12:04 PM,   wrote:
> I checked out the csv module and got a little further along, but still can't
> quite figure out how to iterate line by line properly.
> ?> # But when I try to add columns, I'm only filling in some static value. So
> there's something wrong with my looping.
>
> testReader=csv.reader(open('test-8-29-10.csv', 'rb'))
> for line in testReader:
> ?for MyWord, Category, Ct, CatCt in testReader:
> ???text=nltk.word_tokenize(MyWord)
> ? ?word2=wnl.lemmatize(word)
> ?? word3=porter.stem(word)

here's your problem.  MyWord is the value that is changing in each
iteration of the loop, not word.
Change your lines to
word2=wnl.lemmatize(MyWord)
word3=proter.stem(MyWord)
and it should work fine.

You should've gotten an undefined variable exception, unless you
defined word somewhere else.

Watch those variable names!
HTH,
-Luke

From oberoc at gmail.com  Mon Aug 30 20:13:15 2010
From: oberoc at gmail.com (Tino Dai)
Date: Mon, 30 Aug 2010 14:13:15 -0400
Subject: [Tutor] Help with Object Oriented Programming
Message-ID: 

Hi Everybody,

       I'm beefing up my Object-Oriented Analysis and Design - getting
the gaps in my
knowledge filled in through the Head First OOAD book
(http://headfirstlabs.com/books/hfooad/).
 That book focuses on Java - is there a comparable book for Python? I
have already read the
Alan Gauld's intro on classes, but I'm looking for more. My goal is to
be able to design
and code in Python in an OO fashion exploiting the OO paradigm as it related to
Python at the level of  Kent Johnston (hey, if I'm going to dream,
might as well dream big! :)  ).
Currently, some of the things such as inheritance and encapsulation
apply across OO languages
but interfaces (I know that Zope has this) and mixin's are language
specific constructs.
If anybody could point me in the right direction, that would be great!

TIA,
Tino

From knacktus at googlemail.com  Mon Aug 30 20:25:46 2010
From: knacktus at googlemail.com (Knacktus)
Date: Mon, 30 Aug 2010 20:25:46 +0200
Subject: [Tutor] Conditional attribute access / key access
In-Reply-To: <4C7BD3E8.2020607@libero.it>
References: <4C7BC3B8.2030403@googlemail.com> <4C7BD3E8.2020607@libero.it>
Message-ID: <4C7BF7AA.1030103@googlemail.com>

Am 30.08.2010 17:53, schrieb Francesco Loffredo:
>
> Two questions and one doubt for you:
> 1- How many "generations" do you want to keep in a single item (call it
> dictionary or list, or record, whatever)? I mean, what if some children
> have children too, and some of those have more children, etc ?
There's always one level (generation) of children in an item. An item 
can have zero or more direct children. And a lot of grandchildren and 
grandgrandchildren etc. The item-structure represent an assembly 
hierarchy of the parts of a car. So overall the structure can be up to 
about 20 levels "deep" and consist of up to 200000 items overall, where 
the application needs to handle several structures.
>
> 2- Are you SURE that there are no circular references in your database?
> In your example, what if item_3 was
> item_3 = {"id": 3, "name": "child_2", "children_ids": [6, 1, 8]}? Is't
> it possible that those recursion limit problems you had could come from
> some circular reference in your data?
That's a good hint. But the recursion limit doesn't come from that (the 
test data actually had no children. I used a single instance of my dict.)
>
> d- If the number of data items is really huge, are you sure that you
> want to keep the whole family in memory at the same time? It depends on
> the answer you gave to my question #1, of course, but if retrieving an
> item from your database is quick as it should be, you could use a query
> to resolve the references on demand, and you wouldn't need a special
> structure to hold "the rest of the family". If the retrieval is slow or
> difficult, then the creation of your structure could take a significant
> amount of time.
One thing is, that I have to do some additional calculations when 
resolving the structure. The items will get some kind of 
labels/conditions and versions, further, when resolving the structure a 
set of rules for those conditions is given. At my first shot I'll have 
to do those calculations in the Python code (even if it would be very 
wicked to do stuff like that with SQL). So, I will always have a large 
number of items in memory, as I don't want to call the database for each 
structure-level I want to expand. Also, I'm using a pyqt-treeview 
(AbstractItemModel) for a client-site gui. For this purpose I need to 
create an additional structure, as in the original data items can have 
more than one parent, which is not permitted in the model for the treeview.
The whole idea of replacing the id-references to object-references is to 
enhance performance and make the application code easier.

Thanks for the feedback so far.
>
> Hope this helps,
> Francesco
>
>
>
>
> Nessun virus nel messaggio in uscita.
> Controllato da AVG - www.avg.com
> Versione: 9.0.851 / Database dei virus: 271.1.1/3100 -  Data di rilascio: 08/29/10 08:34:00
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From tumgorenz at washpost.com  Mon Aug 30 20:26:03 2010
From: tumgorenz at washpost.com (Serdar Tumgoren)
Date: Mon, 30 Aug 2010 14:26:03 -0400
Subject: [Tutor] Help with Object Oriented Programming
In-Reply-To: 
References: 
Message-ID: 

I haven't read it yet myself, but the below book just came out:

http://www.amazon.com/Python-3-Object-Oriented-Programming/dp/1849511268/ref=cm_cr_pr_sims_t

I'm not aware of any other book that focuses exclusively on OO in Python,
though you'll find good intros to the topic in a number of the "classics,"
such as the newest Learning Python (4th Edition) and Core Python (2nd
Edition).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From knacktus at googlemail.com  Mon Aug 30 20:43:20 2010
From: knacktus at googlemail.com (Knacktus)
Date: Mon, 30 Aug 2010 20:43:20 +0200
Subject: [Tutor] Help with Object Oriented Programming
In-Reply-To: 
References: 
Message-ID: <4C7BFBC8.6010302@googlemail.com>

Am 30.08.2010 20:13, schrieb Tino Dai:
> Hi Everybody,
>
>         I'm beefing up my Object-Oriented Analysis and Design - getting
> the gaps in my
> knowledge filled in through the Head First OOAD book
> (http://headfirstlabs.com/books/hfooad/).
>   That book focuses on Java - is there a comparable book for Python? I
> have already read the
> Alan Gauld's intro on classes, but I'm looking for more. My goal is to
> be able to design
> and code in Python in an OO fashion exploiting the OO paradigm as it related to
> Python at the level of  Kent Johnston (hey, if I'm going to dream,
> might as well dream big! :)  ).
> Currently, some of the things such as inheritance and encapsulation
> apply across OO languages
> but interfaces (I know that Zope has this) and mixin's are language
> specific constructs.
> If anybody could point me in the right direction, that would be great!
>
> TIA,
> Tino
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
Hi Tino,

I've started in a very simliar fashion. My first OO-app was a procedural 
Fortran-style Java application ;-)
Then I stumbled over Python but was aware that I had no clue about 
OO-Programming. I read the book Head First OOAD, too. And also stuff 
about design patterns.
At the beginning, it's a bit confusing. There's a lot of overhead 
involved due to Java's static typing. You have to use inheritance, 
interfaces, abstract classes etc. to achieve certain things, e.g. make 
code general ("develop for interface not implementation ...") With 
Python the same things can be achieved a loooooot easier and in the end 
clearer (at least to me). One example are the iterator and visitor 
patterns. Those can be done so smoothly in Python thanks to "everything 
is a first class object". It would be fatal to try to translate Java 
Code from the DP book to python.
Overall, Java OO and DP are helpful to know and understanding the ideas 
behind them will help you with Python. But things are done differently 
with Pyhton (don't try to mimick Java!) and you will be very very happy 
about that.

From alan.gauld at btinternet.com  Mon Aug 30 20:56:14 2010
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Mon, 30 Aug 2010 18:56:14 +0000 (GMT)
Subject: [Tutor] can this be done easerly
In-Reply-To: 
References: ,
	
	,
	<809893.80576.qm@web86701.mail.ird.yahoo.com>
	
Message-ID: <731133.87975.qm@web86704.mail.ird.yahoo.com>

Ok, Looks like you need the replace() on anything that could be a separator...

BTW.
Did you see Steven's implementation? He used a list comprehension 
which is probably a little beyond your "comprehension" for now (sorry, 
I couldn't resist! :-) but can be translated easily back to an explicit loop. 


He is using your original character based approach but with isalpha() 
instead of the ord() checks

Alan Gauld
Author of the Learn To Program website
http://www.alan-g.me.uk/



>
>From: Roelof Wobben 
>To: alan.gauld at btinternet.com
>Sent: Monday, 30 August, 2010 18:41:58
>Subject: RE: [Tutor] can this be done easerly
>
> Hello, 
> 
>It don't work for me:
> 
>I changed everything to this :
> 
>def extract_words(s):
>    """
>      >>> extract_words('Now is the time!  "Now", is the time? Yes, now.')
>      ['now', 'is', 'the', 'time', 'now', 'is', 'the', 'time', 'yes', 'now']
>      >>> extract_words('she tried to curtsey as she spoke--fancy')
>      ['she', 'tried', 'to', 'curtsey', 'as', 'she', 'spoke', 'fancy']
>    """
>    s2=[]
>    s = s.lower()
>    for word in s.split():
>        test = word.strip('!?,.--')
>        s2.append(test)
>    return s2
>        
>if __name__ == '__main__':
>    import doctest
>    doctest.testmod()
> 
>But now the doctest failes with this :
> 
>Expected:
>['she', 'tried', 'to', 'curtsey', 'as', 'she', 'spoke', 'fancy']
>Got:
>['she', 'tried', 'to', 'curtsey', 'as', 'she', 'spoke--fancy']
>**********************************************************************
>1 items had failures:
>1 of 2 in __main__.extract_words
***Test Failed*** 1 failures.
>
> 
>________________________________
 Date: Mon, 30 Aug 2010 17:01:04 +0000
>From: alan.gauld at btinternet.com
>Subject: Re: [Tutor] can this be done easerly
>To: rwobben at hotmail.com
>CC: tutor at python.org
>
> 
>
>
>> I tried your suggestion with strip and it looks like this :
> 
>> import string
>
>You don't need this now
>
>> def extract_words(s):
>>    word= ""
>
>You dont need this
>
>>     s2=[]
>>     s = string.lower(s)
>>     s = s.replace( "--", " ")
>
>You probably don't need this either - just add '-' to the strip set.
>
>>     s = s.split()
>>     for word in s:
>
>And you could combine those to
>
>for word in s.split():
>
>>         test = word 
>>         test = word.strip('!?,.')
>
>You don't need test, just use
>
>word = word.strip('!?",.-')  #added " and - to your set...
>
>>         s2.append(test)
>>     return s2
>        
>> It works well only I can't get it to work the strip with ". 
>> I always get a EOF error message. I tried it with 
>> word.strip('!?,.") and with word.strip('!?,./"'') but no go.
>
>It looks like you are mixing quote styles.
>Notice how I included the " in the strip() above... 
>See if that works for you.
>
>Alan G.
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From knacktus at googlemail.com  Mon Aug 30 20:59:54 2010
From: knacktus at googlemail.com (Knacktus)
Date: Mon, 30 Aug 2010 20:59:54 +0200
Subject: [Tutor] Help with Object Oriented Programming
In-Reply-To: 
References: 
Message-ID: <4C7BFFAA.2000907@googlemail.com>

You could google for

1) Alex Martelli, Design Patterns
He's a Pyton guru and there're some online talks (at Google and some 
conferences) about DP; a bit difficult to understand, well, he's guru ;-)

2) http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html
I like that one.

Also, there're some presentations about "the lack of design patterns in 
Python" on the web. Google should help or look at the PyCon archives. 
Very useful stuff there.

And finally, 1 gramm of practice weighs more than 1 ton of theory. I see 
it right now after some month absence from coding.

Cheers,

Jan

From alan.gauld at btinternet.com  Mon Aug 30 21:21:57 2010
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 30 Aug 2010 20:21:57 +0100
Subject: [Tutor] Help with Object Oriented Programming
References: 
Message-ID: 


"Tino Dai"  wrote

>       I'm beefing up my Object-Oriented Analysis and Design - 
> getting
> the gaps in my
> knowledge filled in through the Head First OOAD book

I don't know it although I've seen a couple of others in the series.

My recommendations for general OOAD books are:

Timothy Budd - OOP. It's not Python but covers the basic principles 
well.

Grady Booch - OOAD - The second edition is all in C++, The first 
edition, if you can find one,
is in 5 different langiages and IMHO much better for it. It stops you 
focusing on the
language and helps focus on the OO principles.

Bruce Eckel - Thinking in Java - One of the very few books on Java 
that does a good
job of teaching OO. He was going to do a Thinking in Python but I 
think it died :-(

And finally the original Design Patterns book by the Gang of Four. Its 
a bit heavy
but the information is excellent.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/



From sm9191 at gmail.com  Mon Aug 30 22:52:18 2010
From: sm9191 at gmail.com (Sam M)
Date: Mon, 30 Aug 2010 16:52:18 -0400
Subject: [Tutor] Newbie - regex question
Message-ID: 

Hi Guys,

I'd like remove contents between tags  that matches pattern "WORD1"  
as follows:

Change
"stuff WORD1-EMAILID at DOMAIN.COM more stuff  
WORD1-EMAILID at DOMAIN.COM still more stuff  
WORD2-EMAILID at DOMAIN.COM stuff after WORD2  
WORD1-EMAILID at DOMAIN.COM"

To
"stuff  more stuff  still more stuff  
WORD2-EMAILID at DOMAIN.COM stuff after WORD2 "

The following did not work
newl = re.sub (r'WORD1-.*',"",line)

Thanks in advance!

From hugo.yoshi at gmail.com  Mon Aug 30 23:56:34 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Mon, 30 Aug 2010 23:56:34 +0200
Subject: [Tutor] Newbie - regex question
In-Reply-To: 
References: 
Message-ID: 

On Mon, Aug 30, 2010 at 10:52 PM, Sam M  wrote:
> Hi Guys,
>
> I'd like remove contents between tags  that matches pattern "WORD1"
> as follows:
>
> Change
> "stuff WORD1-EMAILID at DOMAIN.COM more stuff
> WORD1-EMAILID at DOMAIN.COM still more stuff
> WORD2-EMAILID at DOMAIN.COM stuff after WORD2
> WORD1-EMAILID at DOMAIN.COM"
>
> To
> "stuff ?more stuff ?still more stuff WORD2-EMAILID at DOMAIN.COM
> stuff after WORD2 "
>
> The following did not work
> newl = re.sub (r'WORD1-.*',"",line)
>

This precise problem is actually described in the re documentation on
python.org:

http://docs.python.org/howto/regex.html#greedy-versus-non-greedy

In short: .* is greedy and gobbles up as much as it can. That means
 will resolve to the last  tag in the line, and all
the previous ones are simply eaten by .*

To solve, we have the non-greedy patterns. They eat not as much
possible, but as little as possible. To make a qualifier non-greedy,
simply add an asterix at its end:

r'WORD1-.*?'

Hugo

From zstumgoren at gmail.com  Tue Aug 31 00:02:35 2010
From: zstumgoren at gmail.com (Serdar Tumgoren)
Date: Mon, 30 Aug 2010 18:02:35 -0400
Subject: [Tutor] Newbie - regex question
In-Reply-To: 
References: 
	
Message-ID: 

 To make a qualifier non-greedy,

> simply add an asterix at its end:
>
> r'WORD1-.*?'
>
>
Hugo explains this nicely, but I just wanted to make one minor correction
 -- the non-greedy qualifier is the question mark AFTER an the asterisk
(which is what Hugo's code shows but I believe he accidentally left off).

Serdar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From bgailer at gmail.com  Tue Aug 31 00:11:10 2010
From: bgailer at gmail.com (bob gailer)
Date: Mon, 30 Aug 2010 18:11:10 -0400
Subject: [Tutor] Newbie - regex question
In-Reply-To: 
References: 
Message-ID: <4C7C2C7E.809@gmail.com>

  On 8/30/2010 4:52 PM, Sam M wrote:
> Hi Guys,
>
> I'd like remove contents between tags  that matches pattern 
> "WORD1" as follows:
>
> Change
> "stuff WORD1-EMAILID at DOMAIN.COM more stuff 
> WORD1-EMAILID at DOMAIN.COM still more stuff 
> WORD2-EMAILID at DOMAIN.COM stuff after WORD2 
> WORD1-EMAILID at DOMAIN.COM"
>
> To
> "stuff  more stuff  still more stuff 
> WORD2-EMAILID at DOMAIN.COM stuff after WORD2 "
>
> The following did not work
> newl = re.sub (r'WORD1-.*',"",line)

Please remember to explain "did not work".
Did you get an exception?
Did you get unexpected results? If so what were they?

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From hugo.yoshi at gmail.com  Tue Aug 31 00:12:36 2010
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Tue, 31 Aug 2010 00:12:36 +0200
Subject: [Tutor] Newbie - regex question
In-Reply-To: 
References: 
	
	
Message-ID: 

On Tue, Aug 31, 2010 at 12:02 AM, Serdar Tumgoren  wrote:
> ?To make a qualifier non-greedy,
>>
>> simply add an asterix at its end:
>>
>> r'WORD1-.*?'
>>
>
> Hugo explains this nicely, but I just wanted to make one minor correction
> ?-- the non-greedy qualifier is the question mark AFTER an the asterisk
> (which is what Hugo's code shows but I believe he accidentally left off).
>

ah, sorry, a bit of cognitive dissonance on my end. You're right of
course. That should've read "To make a qualifier non-greedy, add a
*question mark* at the end."

Hugo

From marc.tompkins at gmail.com  Tue Aug 31 00:16:35 2010
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Mon, 30 Aug 2010 15:16:35 -0700
Subject: [Tutor] Newbie - regex question
In-Reply-To: 
References: 
	
Message-ID: 

On Mon, Aug 30, 2010 at 2:56 PM, Hugo Arts  wrote:

> To solve, we have the non-greedy patterns. They eat not as much
> possible, but as little as possible. To make a qualifier non-greedy,
> simply add an asterix at its end:
>
> r'WORD1-.*?'
>
> I would also like to offer one small correction: an asterisk may be greedy,
but Asterix is a cheerful, brave Gaul.


-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From payal-python at scriptkitchen.com  Tue Aug 31 04:22:40 2010
From: payal-python at scriptkitchen.com (Payal)
Date: Mon, 30 Aug 2010 19:22:40 -0700
Subject: [Tutor] __new__ over __init__
Message-ID: <20100831022240.GA6772@scriptkitchen.com>

Hi all,

Can someone please give a very simple example of using __new__ wherein
__init__ cannot be used?

With warm regards,
-Payal
-- 



From __peter__ at web.de  Tue Aug 31 08:27:10 2010
From: __peter__ at web.de (Peter Otten)
Date: Tue, 31 Aug 2010 08:27:10 +0200
Subject: [Tutor] __new__ over __init__
References: <20100831022240.GA6772@scriptkitchen.com>
Message-ID: 

Payal wrote:

> Can someone please give a very simple example of using __new__ wherein
> __init__ cannot be used?

Subclasses of immutable types, e. g. tuple:

>>> class A(tuple):
...     def __init__(self, a, b):
...             pass
...
>>> a = A(1,2)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: tuple() takes at most 1 argument (2 given)
>>> class A(tuple):
...     def __new__(cls, a, b):
...             return tuple.__new__(cls, (a, b))
...
>>> A(1, 2)
(1, 2)
>>> type(_)


Peter


From dineshbvadhia at hotmail.com  Tue Aug 31 10:44:22 2010
From: dineshbvadhia at hotmail.com (Dinesh B Vadhia)
Date: Tue, 31 Aug 2010 01:44:22 -0700
Subject: [Tutor] Plural words to Singular
Message-ID: 

Has anyone come across a quality program to turn plural words to singular words?  We don't want to use a stemmer.  Thanks.

Dinesh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From steve at pearwood.info  Tue Aug 31 11:47:13 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 31 Aug 2010 19:47:13 +1000
Subject: [Tutor] Conditional attribute access / key access
In-Reply-To: <4C7BC3B8.2030403@googlemail.com>
References: <4C7BC3B8.2030403@googlemail.com>
Message-ID: <201008311947.18007.steve@pearwood.info>

On Tue, 31 Aug 2010 12:44:08 am Knacktus wrote:
> Hey everyone,
>
> I have a huge number of data items coming from a database. 

Huge?

Later in this thread, you mentioned 200,000 items overall. That might 
be "huge" to you, but it isn't to Python. Here's an example:

class K(object):
    def __init__(self):
        self.info = {"id": id(self),
                    "name": "root " + str(id(self)), 
                    "children_ids": [2*id(self), 3*id(self)+1]}


And the size:

>>> k = K()
>>> sys.getsizeof(k)
28
>>> sys.getsizeof(k.info)
136
>>> L = [K() for _ in xrange(200000)]
>>> sys.getsizeof(L)
835896

The sizes given are in bytes. So 200,000 instances of this class, plus 
the list to hold them, would take approximately 34 megabytes. An entry 
level PC these days has 1000 megabytes of memory. "Huge"? Not even 
close.

Optimizing with __slots__ is premature. Perhaps if you had 1000 times 
that many instances, then it might be worth while.



> So far 
> there're no restrictions about how to model the items. They can be
> dicts, objects of a custom class (preferable with __slots__) or
> namedTuple.
>
> Those items have references to each other using ids.

That approach sounds slow and ponderous to me. Why don't you just give 
items direct references to each other, instead of indirect using ids?

I presume you're doing something like this:

ids = {0: None}  # Map IDs to objects.
a = Part(0)
ids[1] = a
b = Part(1)  # b is linked to a via its ID 1.
ids[2] = b
c = Part(2)  # c is linked to b via its ID 2.
ids[3] = c

(only presumably less painfully).


If that's what you're doing, you should dump the ids and just do this:

a = Part(None)
b = Part(a)
c = Part(b)

Storing references to objects in Python is cheap -- it's only a pointer. 
Using indirection via an ID you manage yourself is a pessimation, not 
an optimization: it requires more code, slower speed, and more memory 
too (because the integer IDs themselves are pointers to 12 byte 
objects, not 4 byte ints).

If you *need* indirection, say because you are keeping the data in a 
database and you want to only lazily load it when needed, rather than 
all at once, then the right approach is probably a proxy object:

class PartProxy(object):
    def __init__(self, database_id):
        self._info = None
        self.database_id = database_id
    @property
    def info(self):
        if self._info is None:
            self._info = get_from_database(self.database_id)
        return self._info




-- 
Steven D'Aprano

From metallourlante at gmail.com  Tue Aug 31 13:40:54 2010
From: metallourlante at gmail.com (Alex)
Date: Tue, 31 Aug 2010 13:40:54 +0200
Subject: [Tutor] Understanding Custom Exception
Message-ID: 

Hi all.

I'm working on a thin wrapper around the unix crontab command (just the
command, non the cron service).  The module will do some simple operation
like:
- Read the crontab file
- Adding a job to crontab identified by an id
- Deleting a job
- Deleting all jobs added

Now I have two questions:

1. Does it make sense to create a couple of custom exceptions like:

   class CrontabDoesNotExist(Exception): pass
   class CrontabSyntaxError(Exception): pass

  Or I should use builtin exception?

2. Does it make sense to catch an exception raised by a function just to
raise your own custom exception? For instance

subprocess.check_call(['crontab','-l'])

will raise a CalledProcessError exception if the crontab of the current user
does not exist. Does it make sense to catch the exception just to raise my
own custom exception? For instance:

try:
    subprocess.check_call(['crontab','-l'])
except CalledProcessError:
    raise CrontabDoesNotExist()

Maybe I could also make the CrontabDoesNotExist exception more useful
printing a message to inform the user that the crontab does not exist for
the current user.

Thanks in advance.

Alex

From steve at pearwood.info  Tue Aug 31 15:25:47 2010
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 31 Aug 2010 23:25:47 +1000
Subject: [Tutor] Understanding Custom Exception
In-Reply-To: 
References: 
Message-ID: <201008312325.48104.steve@pearwood.info>

On Tue, 31 Aug 2010 09:40:54 pm Alex wrote:

> 1. Does it make sense to create a couple of custom exceptions like:
>
>    class CrontabDoesNotExist(Exception): pass
>    class CrontabSyntaxError(Exception): pass
>
>   Or I should use builtin exception?

Yes, it makes sense, although I'd consider making them subclasses of 
more specific exceptions, e.g. perhaps CronTabMissing (shorter name 
than CronTabDoesNotExist) might be a subclass of the error you get when 
you try to open a missing file (IOError if memory serves me right), and 
CronTabSyntaxError might be a subclass of SyntaxError.

Or perhaps not -- you might choose to have a general CronTabError 
exception class, that inherits from Exception, and then inherit from 
that, so that all errors related to CronTab fall under a single 
exception hierarchy. Both strategies are valid.


> 2. Does it make sense to catch an exception raised by a function just
> to raise your own custom exception? For instance
>
> subprocess.check_call(['crontab','-l'])
>
> will raise a CalledProcessError exception if the crontab of the
> current user does not exist. Does it make sense to catch the
> exception just to raise my own custom exception? For instance:
>
> try:
>     subprocess.check_call(['crontab','-l'])
> except CalledProcessError:
>     raise CrontabDoesNotExist()


It certainly does. I'm sure you'll see that technique used in the 
standard library.

[/me goes and looks]

Yep, here you go, in httplib.py:

        # The status code is a three-digit number
        try:
            status = int(status)
            if status < 100 or status > 999:
                raise BadStatusLine(line)
        except ValueError:
            raise BadStatusLine(line)



> Maybe I could also make the CrontabDoesNotExist exception more useful
> printing a message to inform the user that the crontab does not exist
> for the current user.

The point of specific exception types is to be more specific rather than 
less, so yes. If you want to be less specific, you should stick to 
built-in exceptions.


-- 
Steven D'Aprano

From oberoc at gmail.com  Tue Aug 31 15:41:18 2010
From: oberoc at gmail.com (Tino Dai)
Date: Tue, 31 Aug 2010 09:41:18 -0400
Subject: [Tutor] Help with Object Oriented Programming
In-Reply-To: 
References: 
	
Message-ID: 

On Mon, Aug 30, 2010 at 2:26 PM, Serdar Tumgoren  wrote:
> I haven't read it yet myself, but the below book just came out:
>
> http://www.amazon.com/Python-3-Object-Oriented-Programming/dp/1849511268/ref=cm_cr_pr_sims_t
>
> I'm not aware of any other book that focuses exclusively on OO in Python,
> though you'll find good intros to the topic in a number of the "classics,"
> such as the newest Learning Python (4th Edition) and Core Python (2nd
> Edition).
>

I will check all of those out. Thanks Serdar!

From oberoc at gmail.com  Tue Aug 31 15:43:57 2010
From: oberoc at gmail.com (Tino Dai)
Date: Tue, 31 Aug 2010 09:43:57 -0400
Subject: [Tutor] Help with Object Oriented Programming
In-Reply-To: 
References: 
	
Message-ID: 

On Mon, Aug 30, 2010 at 3:21 PM, Alan Gauld  wrote:
>
> "Tino Dai"  wrote
>
>> ? ? ?I'm beefing up my Object-Oriented Analysis and Design - getting
>> the gaps in my
>> knowledge filled in through the Head First OOAD book
>
> I don't know it although I've seen a couple of others in the series.
>
> My recommendations for general OOAD books are:
>
> Timothy Budd - OOP. It's not Python but covers the basic principles well.
>
> Grady Booch - OOAD - The second edition is all in C++, The first edition, if
> you can find one,
> is in 5 different langiages and IMHO much better for it. It stops you
> focusing on the
> language and helps focus on the OO principles.
>
> Bruce Eckel - Thinking in Java - One of the very few books on Java that does
> a good
> job of teaching OO. He was going to do a Thinking in Python but I think it
> died :-(
>
> And finally the original Design Patterns book by the Gang of Four. Its a bit
> heavy
> but the information is excellent.
>

I have Design Patterns on my desk. And I will check out the Timothy Budd and
Grady Booch book. I think we might even have the first edition of that
book - a benefit
of working at a library. Thanks Alan!

-Tino

From anand.shashwat at gmail.com  Tue Aug 31 15:44:01 2010
From: anand.shashwat at gmail.com (Shashwat Anand)
Date: Tue, 31 Aug 2010 19:14:01 +0530
Subject: [Tutor] Plural words to Singular
In-Reply-To: 
References: 
Message-ID: 

On Tue, Aug 31, 2010 at 2:14 PM, Dinesh B Vadhia
wrote:

>  Has anyone come across a quality program to turn plural words to singular
> words?  We don't want to use a stemmer.  Thanks.
>
> Dinesh
>

Create 'rule' for each cases and code it up.


>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 
~l0nwlf
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From oberoc at gmail.com  Tue Aug 31 15:46:14 2010
From: oberoc at gmail.com (Tino Dai)
Date: Tue, 31 Aug 2010 09:46:14 -0400
Subject: [Tutor] Help with Object Oriented Programming
In-Reply-To: <4C7BFFAA.2000907@googlemail.com>
References: 
	<4C7BFFAA.2000907@googlemail.com>
Message-ID: 

On Mon, Aug 30, 2010 at 2:59 PM, Knacktus  wrote:
> You could google for
>
> 1) Alex Martelli, Design Patterns
> He's a Pyton guru and there're some online talks (at Google and some
> conferences) about DP; a bit difficult to understand, well, he's guru ;-)


>
> 2) http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html
> I like that one.
>
> Also, there're some presentations about "the lack of design patterns in
> Python" on the web. Google should help or look at the PyCon archives. Very
> useful stuff there.

Will check those out. Especially the Alex Martelli information. I
think I have this
Python cookbook somewhere around here. Thanks Jan!

-Tino

From knacktus at googlemail.com  Tue Aug 31 15:53:48 2010
From: knacktus at googlemail.com (Knacktus)
Date: Tue, 31 Aug 2010 15:53:48 +0200
Subject: [Tutor] Conditional attribute access / key access
In-Reply-To: <201008311947.18007.steve@pearwood.info>
References: <4C7BC3B8.2030403@googlemail.com>
	<201008311947.18007.steve@pearwood.info>
Message-ID: <4C7D096C.5020006@googlemail.com>


> The sizes given are in bytes. So 200,000 instances of this class, plus
> the list to hold them, would take approximately 34 megabytes. An entry
> level PC these days has 1000 megabytes of memory. "Huge"? Not even
> close.

The items hold a lot of metadata, which I didn't provide in my example. 
Depending on the source up to 30 addional attributes per item, mainly 
strings. And I will have several sources.

>> So far
>> there're no restrictions about how to model the items. They can be
>> dicts, objects of a custom class (preferable with __slots__) or
>> namedTuple.
>>
>> Those items have references to each other using ids.
>
> That approach sounds slow and ponderous to me. Why don't you just give
> items direct references to each other, instead of indirect using ids?
>

Unfortunately I have to able to use a relational database later on. 
Currently I'm using a document database for developement. That's where 
the ids are coming from and you're right: They are a pain ... ;-)

>
> If you *need* indirection, say because you are keeping the data in a
> database and you want to only lazily load it when needed, rather than
> all at once, then the right approach is probably a proxy object:
>
> class PartProxy(object):
>      def __init__(self, database_id):
>          self._info = None
>          self.database_id = database_id
>      @property
>      def info(self):
>          if self._info is None:
>              self._info = get_from_database(self.database_id)
>          return self._info
>

That's it! Excactly what I was looking for! That eases the id-pain. Thanks!!

Jan


From sm9191 at gmail.com  Tue Aug 31 14:45:43 2010
From: sm9191 at gmail.com (Sam M)
Date: Tue, 31 Aug 2010 08:45:43 -0400
Subject: [Tutor] Newbie - regex question
In-Reply-To: 
References: 
	
Message-ID: 

Thanks everyone for prompt response and explanation.
Cheers!

From thudfoo at opensuse.us  Tue Aug 31 17:10:08 2010
From: thudfoo at opensuse.us (member thudfoo)
Date: Tue, 31 Aug 2010 08:10:08 -0700
Subject: [Tutor] Plural words to Singular
In-Reply-To: 
References: 
Message-ID: 

On Tue, Aug 31, 2010 at 1:44 AM, Dinesh B Vadhia
 wrote:
>
> Has anyone come across a quality program to turn plural words to singular words?? We don't want to use a stemmer.? Thanks.

All I know about this one is what it says on PyPI:

Correctly generate plurals, singular nouns, ordinals, indefinite articles;
convert numbers to words

http://pypi.python.org/pypi/inflect/0.2.1

From alessandro.martin at yahoo.it  Tue Aug 31 20:41:36 2010
From: alessandro.martin at yahoo.it (Alessandro Martin)
Date: Tue, 31 Aug 2010 20:41:36 +0200
Subject: [Tutor] Understanding Custom Exception
Message-ID: 

> The point of specific exception types is to be more specific rather than
> less, so yes. If you want to be less specific, you should stick to
> built-in exceptions.

Thanks Steven. It's all clear now.
As soon as I finished the module I'll post it here for a code review.

Alex

From fomcl at yahoo.com  Tue Aug 31 20:48:31 2010
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Tue, 31 Aug 2010 11:48:31 -0700 (PDT)
Subject: [Tutor] Help with Object Oriented Programming
In-Reply-To: 
References: 
	
	
Message-ID: <745831.72375.qm@web110708.mail.gq1.yahoo.com>

I read Head First Design Patterns (http://oreilly.com/catalog/9780596007126). It 
focuses on Java and it's not only good because of the nice woman on the cover. 
;-)

 Cheers!!
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?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~




________________________________
From: Tino Dai 
To: Alan Gauld 
Cc: tutor at python.org
Sent: Tue, August 31, 2010 3:43:57 PM
Subject: Re: [Tutor] Help with Object Oriented Programming

On Mon, Aug 30, 2010 at 3:21 PM, Alan Gauld  wrote:
>
> "Tino Dai"  wrote
>
>>      I'm beefing up my Object-Oriented Analysis and Design - getting
>> the gaps in my
>> knowledge filled in through the Head First OOAD book
>
> I don't know it although I've seen a couple of others in the series.
>
> My recommendations for general OOAD books are:
>
> Timothy Budd - OOP. It's not Python but covers the basic principles well.
>
> Grady Booch - OOAD - The second edition is all in C++, The first edition, if
> you can find one,
> is in 5 different langiages and IMHO much better for it. It stops you
> focusing on the
> language and helps focus on the OO principles.
>
> Bruce Eckel - Thinking in Java - One of the very few books on Java that does
> a good
> job of teaching OO. He was going to do a Thinking in Python but I think it
> died :-(
>
> And finally the original Design Patterns book by the Gang of Four. Its a bit
> heavy
> but the information is excellent.
>

I have Design Patterns on my desk. And I will check out the Timothy Budd and
Grady Booch book. I think we might even have the first edition of that
book - a benefit
of working at a library. Thanks Alan!

-Tino
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: