From losermeloser at yahoo.com Fri Mar 1 03:33:12 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Thu, 28 Feb 2013 18:33:12 -0800 (PST) Subject: [Tutor] confusing installation Message-ID: <1362105192.70127.YahooMailNeo@web121105.mail.ne1.yahoo.com> Hi all. Im working through a database tutorial in a book called Core Python Applications. On page 290 it asks of me to install something though its not clear what it is. I think it has to do with SQLAlchemy. It says if you use Python 3 you'll need to get distribute first. You'll need a web browser (or the curl if you have it). ? Mind you i havent a clue what it is on about.. then it goes on: ? And to download the installation file (available at http://python-distribute.org/distribute_setup.py), and then get SQLAlchemy with easy install. Here is what this entire process might look like on a Windows-based PC... then it proceeds to? write a whole bunch of god know what. It looks similar to when you install something on linux.. Im a windows only user btw. ? That link i went there to download the file but if you look at that site i dont know what on earth im supposed to do to install/retrieve that file. I do not know what easy install is.What do they mean i need a web browser? doesnt every computer have a web-browser?? what is curl???I can not proceed with this tutorial if i recieve no help... Please can anyone assist me on what i have to do to use the tools they are presenting. ? i use Python 3 and Windows -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Mar 1 09:58:29 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 01 Mar 2013 08:58:29 +0000 Subject: [Tutor] confusing installation In-Reply-To: <1362105192.70127.YahooMailNeo@web121105.mail.ne1.yahoo.com> References: <1362105192.70127.YahooMailNeo@web121105.mail.ne1.yahoo.com> Message-ID: On 01/03/13 02:33, Lolo Lolo wrote: > Hi all. Im working through a database tutorial in a book called Core > Python Applications. I'm not familiar with that book so can't offer specific help. > SQLAlchemy with easy install. Here is what this entire process might > look like on a Windows-based PC... then it proceeds to write a whole > bunch of god know what. It looks similar to when you install something > on linux.. Im a windows only user btw. Welcome to the world of software development. GUIs like Windows are great for doing simple things but they can't compete with command line tools for doing powerful things quickly. So pretty much every programmer has to get used to using the command line sooner or later. If you are not used to using the Windowsc CMD program there are several short tutorials available to help you get started. > That link i went there to download the file but if you look at that site > i dont know what on earth im supposed to do to install/retrieve that > file. I do not know what easy install is. easy install is a toolset for making the installation of Python modules easy. Again there are tutorials/manual pages available and the first time you use it you may want to read one of those. > What do they mean i need a web browser? doesnt every computer have > a web-browser?? Mostly, but some don't. Especially older ones or special purpose ones. Some only have text based browsers that can't show graphics etc. > what is curl?? A software tool for fetching files from urls. Its not installed on Windows by default you would need to download and install a copy of that too. But I suspect you can do the same thing using your browser, it will just take a bit more effort. > not proceed with this tutorial if i recieve no help... Please can anyone > assist me on what i have to do to use the tools they are presenting. It may be that the tutorial is too far ahead of your current level of computer skills. Its assuming you are comfortable using a command line. It might be worth finding a more basic tutorial until your skill level gets back up to the point you can go back to that one. The good news there are lots of free tutorials at all levels. It sounds to me like finding a new tutorial that takes a slower pace might be your best option here. Do you know what you are trying to learn specifically? Or is it just the next topic in the tutorial? Do you have a specific need to use SQL Alchemy? If not maybe you can just jump over a chapter tor two... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From losermeloser at yahoo.com Fri Mar 1 12:50:29 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Fri, 1 Mar 2013 03:50:29 -0800 (PST) Subject: [Tutor] confusing installation In-Reply-To: References: <1362105192.70127.YahooMailNeo@web121105.mail.ne1.yahoo.com> Message-ID: <1362138629.35548.YahooMailNeo@web121101.mail.ne1.yahoo.com> >Welcome to the world of software development. GUIs like Windows are great for doing simple things but they can't compete with >command line tools for doing powerful things quickly. So pretty much every programmer has to get used to using the command line >sooner or later. >If you are not used to using the Windowsc CMD program there are several short tutorials available to help you get started. ? so CMD has features like linux when you can download/install/build files from the command line? i didnt think this was possible ? ? >easy install is a toolset for making the installation of Python modules easy. Again there are tutorials/manual pages available and the >first time you use it you may want to read one of those. ? on a google search for easy install, easy install python was auto completed. Is this what im after or is it easy install windows? >It sounds to me like finding a new tutorial that takes a slower pace might be your best option here. Do you know what you are trying >to >learn specifically? Or is it just the next topic in the tutorial? Do you have a specific need to use SQL Alchemy? If not maybe you >can >just jump over a chapter tor two... i want to learn about how to use databases and this specific chapter is meant to introduce its readers to options available (not just SQLAlchemy). It's already at a beginner's level so i might run into the same problems else where. i will look for some easy install tutorials -------------- next part -------------- An HTML attachment was scrubbed... URL: From vijaya.r at excelindia.com Fri Mar 1 14:07:29 2013 From: vijaya.r at excelindia.com (Vijay Kumar R) Date: Fri, 1 Mar 2013 18:37:29 +0530 Subject: [Tutor] Problem with os.system Message-ID: <000001ce167d$baebc620$30c35260$@excelindia.com> I was using python for some application which used to create directories and also to run some exes using the os.system command from a program.py file which was working fine. For some reasons I got my system formatted and got the windows 7 installed. Now again I installed python and tried running the same program.py. The program executes successfully with no errors but my directory and exes are not getting invoked. I tried creating the below sample program and executed it #!/usr/bin/env python import os global name_wo_ext name_wo_ext = "d:\\fun" os.system("mkdir %s" % (name_wo_ext)) This gets executed well but there is no directory created L I tried with another command as below and it works for me #!/usr/bin/env python import os global name_wo_ext name_wo_ext = "d:\\fun" if not os.path.exists("%s\\thumbnail\\" % (name_wo_ext)): os.makedirs("%s" % (name_wo_ext)) I am not able to find out why os.system is not executing the commands. Could somebody please help me out in resolving the problem as I have used os.system enormously in my program. Thanks and regards, Vijay R -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Fri Mar 1 15:11:18 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 1 Mar 2013 06:11:18 -0800 (PST) Subject: [Tutor] Problem with os.system In-Reply-To: <000001ce167d$baebc620$30c35260$@excelindia.com> References: <000001ce167d$baebc620$30c35260$@excelindia.com> Message-ID: <1362147078.22765.YahooMailNeo@web163805.mail.gq1.yahoo.com> >I was using python for some application which used to create directories and also to run some exes using the os.system command from a program.py file which was working fine. For some reasons I got my system formatted and got the windows 7 installed. >? >Now again I installed python and tried running the same program.py.? The program executes successfully with no errors but my directory and exes are not getting invoked. >? >I tried creating the below sample program and executed it >? >#!/usr/bin/env python >import os >global name_wo_ext >name_wo_ext = "d:\\fun" >os.system("mkdir %s" % (name_wo_ext)) Hello, not sure if it solves things, but are you aware of os.mkdir? And do you have sufficient rights to create a dir where you want to create it? >>> help(os.mkdir) Help on built-in function mkdir in module nt: mkdir(...) ??? mkdir(path [, mode=0777]) ??? ??? Create a directory. >>> From wprins at gmail.com Fri Mar 1 16:15:21 2013 From: wprins at gmail.com (Walter Prins) Date: Fri, 1 Mar 2013 17:15:21 +0200 Subject: [Tutor] confusing installation In-Reply-To: References: <1362105192.70127.YahooMailNeo@web121105.mail.ne1.yahoo.com> Message-ID: Hi, On 1 March 2013 10:58, Alan Gauld wrote: > On 01/03/13 02:33, Lolo Lolo wrote: > >> SQLAlchemy with easy install. Here is what this entire process might >> > look like on a Windows-based PC... then it proceeds to write a whole >> bunch of god know what. It looks similar to when you install something >> on linux.. Im a windows only user btw. >> > > Welcome to the world of software development. GUIs like Windows are great > for doing simple things but they can't compete with command line tools for > doing powerful things quickly. So pretty much every programmer has to get > used to using the command line sooner or later. > > If you are not used to using the Windowsc CMD program there are several > short tutorials available to help you get started. > This should be relevant: http://www.voidspace.org.uk/python/articles/command_line.shtml Cheers, Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From jf_byrnes at comcast.net Fri Mar 1 16:27:44 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Fri, 01 Mar 2013 09:27:44 -0600 Subject: [Tutor] confusing installation In-Reply-To: <1362105192.70127.YahooMailNeo@web121105.mail.ne1.yahoo.com> References: <1362105192.70127.YahooMailNeo@web121105.mail.ne1.yahoo.com> Message-ID: On 02/28/2013 08:33 PM, Lolo Lolo wrote: > Hi all. Im working through a database tutorial in a book called Core > Python Applications. On page 290 it asks of me to install something > though its not clear what it is. I think it has to do with > SQLAlchemy. It says if you use Python 3 you'll need to get distribute > first. You'll need a web browser (or the curl if you have it). I have the book but I am only on chapter one and I don't use Windows so my explanation may not be 100% accurate. Since you use python 3 you will need to download the file: distribute_setup.py. To do so you will need a web browser or the command line tool curl. I use Firefox and when I click on the url you give below it immediately offers to download the required file. > Mind you i havent a clue what it is on about.. then it goes on: > > And to download the installation file (available at > http://python-distribute.org/distribute_setup.py), and then get > SQLAlchemy with easy install. Here is what this entire process might > look like on a Windows-based PC... then it proceeds to write a whole > bunch of god know what. It looks similar to when you install > something on linux.. Im a windows only user btw. He is showing you what to expect. Where ever you see a line starting with C:\ that is what he typed into the command line session, and the lines that follow is the program you are installing informing you what it is doing. (Until you get to the next C:\ or the end) > > That link i went there to download the file but if you look at that > site i dont know what on earth im supposed to do to install/retrieve > that file. I do not know what easy install is.What do they mean i > need a web browser? doesnt every computer have a web-browser?? what > is curl?? I can not proceed with this tutorial if i recieve no > help... Please can anyone assist me on what i have to do to use the > tools they are presenting. > > i use Python 3 and Windows > > Regards, Jim From losermeloser at yahoo.com Fri Mar 1 17:05:36 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Fri, 1 Mar 2013 08:05:36 -0800 (PST) Subject: [Tutor] confusing installation In-Reply-To: References: <1362105192.70127.YahooMailNeo@web121105.mail.ne1.yahoo.com> Message-ID: <1362153936.84892.YahooMailNeo@web121101.mail.ne1.yahoo.com> > This should be relevant:?http://www.voidspace.org.uk/python/articles/command_line.shtml in searching for command line tutorials i also came across Powershell and noticed commands that work in one don't work in the other. Would you recommend Powershell over CMD? -------------- next part -------------- An HTML attachment was scrubbed... URL: From losermeloser at yahoo.com Fri Mar 1 17:18:44 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Fri, 1 Mar 2013 08:18:44 -0800 (PST) Subject: [Tutor] confusing installation In-Reply-To: References: <1362105192.70127.YahooMailNeo@web121105.mail.ne1.yahoo.com> Message-ID: <1362154724.36518.YahooMailNeo@web121101.mail.ne1.yahoo.com> > Since you use python 3 you will need to download the file: distribute_setup.py.? To do so you will need a web browser or the > command line tool curl.? I use Firefox and when I click on the url you give below it immediately offers to download the required file. thanks i tried it on firefox and it did the trick > He is showing you what to expect.? Where ever you see a line starting with C:\ that is what he typed into the command line session, > and the lines that follow is the program you are installing informing you what it is doing. (Until you get to the next C:\ or the end) ? thanks for this explanation, i will try and read that section a bit more carefully and do what he is typing -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Fri Mar 1 17:27:35 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 1 Mar 2013 16:27:35 +0000 Subject: [Tutor] confusing installation In-Reply-To: <1362138629.35548.YahooMailNeo@web121101.mail.ne1.yahoo.com> References: <1362105192.70127.YahooMailNeo@web121105.mail.ne1.yahoo.com> <1362138629.35548.YahooMailNeo@web121101.mail.ne1.yahoo.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474181D043F@SCACMX008.exchad.jpmchase.net> Lolo Lolo wrote: > >Welcome to the world of software development. GUIs like Windows are great for doing simple things but > they can't compete with >command line tools for doing powerful things quickly. So pretty much every > programmer has to get used to using the command line >sooner or later. > > >If you are not used to using the Windowsc CMD program there are several short tutorials available to > help you get started. > > so CMD has features like linux when you can download/install/build files from the command line? i > didnt think this was possible Yes, this is very possible. In fact, there are entire projects towards creating Linux-like environments in Windows. Cygwin[0] and MinGW[1] are two big ones of which I am aware. I am sure there are other smaller/more specialized version. You can also use many Linux command line programs that have been compiled for Windows. I frequently use GnuWin32's[2] programs. [0] http://www.cygwin.com/ [1] http://www.mingw.org/ [2] http://gnuwin32.sourceforge.net/ Tangentially yours, Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From davea at davea.name Fri Mar 1 19:00:19 2013 From: davea at davea.name (Dave Angel) Date: Fri, 01 Mar 2013 13:00:19 -0500 Subject: [Tutor] Problem with os.system In-Reply-To: <000001ce167d$baebc620$30c35260$@excelindia.com> References: <000001ce167d$baebc620$30c35260$@excelindia.com> Message-ID: <5130ECB3.6010104@davea.name> On 03/01/2013 08:07 AM, Vijay Kumar R wrote: > I was using python for some application which used to create directories and > also to run some exes using the os.system command from a program.py file > which was working fine. For some reasons I got my system formatted and got > the windows 7 installed. > > > > Now again I installed python and tried running the same program.py. The > program executes successfully with no errors but my directory and exes are > not getting invoked. > > > > I tried creating the below sample program and executed it > > > > #!/usr/bin/env python > > import os > > global name_wo_ext > > name_wo_ext = "d:\\fun" > > os.system("mkdir %s" % (name_wo_ext)) > > > > This gets executed well but there is no directory created I'm not running Windows, so I can't do the obvious checks. What kind of drive is your D: partition? For example if it's a CD, you can't write to it. Likewise, if the root directory is restricted, and your user doesn't have permissions. cmd.exe doesn't return an error level, so you don't get much of a clue from there. Have you tried a different internal command, one that displays something? Like DIR ? Have you made sure you have a COMSPEC variable, and that it has a reasonable velu? Have you tried a real program? 'mkdir' and 'dir' are internal commands, built into cmd.exe. Maybe Windows 7 decided to remove it after 30 years. After all, it's just an alias for 'md' > > > > Could somebody please help me out in resolving the problem as I have used > os.system enormously in my program. os.system has been deprecated at least 8 years, in favor of the subprocess module. Its flexibility and error handling are quite limited. >-- DaveA From alan.gauld at btinternet.com Fri Mar 1 20:06:17 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 01 Mar 2013 19:06:17 +0000 Subject: [Tutor] confusing installation In-Reply-To: <1362153936.84892.YahooMailNeo@web121101.mail.ne1.yahoo.com> References: <1362105192.70127.YahooMailNeo@web121105.mail.ne1.yahoo.com> <1362153936.84892.YahooMailNeo@web121101.mail.ne1.yahoo.com> Message-ID: On 01/03/13 16:05, Lolo Lolo wrote: > > This should be > relevant: http://www.voidspace.org.uk/python/articles/command_line.shtml > in searching for command line tutorials i also came across Powershell > and noticed commands that work in one don't work in the other. Would you > recommend Powershell over CMD? Powershell is much more powerful than CMD and offers a full programming language of its own. But mostly I find its used by sysadmin types rather than normal users. CMD is fine for most things and is all I use when working on windows PCs. If you read the CMD help file there are some registry hacks you can do to make it more powerful and user friendly. (Almost as good as bash on Unix) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Fri Mar 1 20:10:21 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 01 Mar 2013 19:10:21 +0000 Subject: [Tutor] confusing installation In-Reply-To: <1362138629.35548.YahooMailNeo@web121101.mail.ne1.yahoo.com> References: <1362105192.70127.YahooMailNeo@web121105.mail.ne1.yahoo.com> <1362138629.35548.YahooMailNeo@web121101.mail.ne1.yahoo.com> Message-ID: On 01/03/13 11:50, Lolo Lolo wrote: > i want to learn about how to use databases and this specific chapter is > meant to introduce its readers to options available (not just > SQLAlchemy). It's already at a beginner's level so i might run into the > same problems else where. i will look for some easy install tutorials If you just want to know about SQL databases you could try my tutorial topic (only in the V2 version at the moment but it's nearly identical on V3) It uses SQLite which is part of standard Python, although you can also download a Windows installer for standalone use. If nothing else it will give you a quick intro to the topic and doesn't cost anything but time... It sounds like your book is covering a wider range of options than SQL but you might still find mine useful. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jhuperetes at gmail.com Fri Mar 1 20:48:08 2013 From: jhuperetes at gmail.com (Huperetes) Date: Fri, 1 Mar 2013 14:48:08 -0500 Subject: [Tutor] Reversed dictionary returned by default Message-ID: I am getting the following for my installation. Why is this happening, and how do I get it to work properly (returning element 0 - n, versus n - 0)? Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"} >>> ["%s=%s" % (k, v) for k, v in params.items()] ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim'] >>> ";".join(["%s=%s" % (k, v) for k, v in params.items()]) 'pwd=secret;database=master;uid=sa;server=mpilgrim' >>> Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From brad.hudson at gmail.com Fri Mar 1 20:52:52 2013 From: brad.hudson at gmail.com (Brad Hudson) Date: Fri, 1 Mar 2013 13:52:52 -0600 Subject: [Tutor] Problem with os.system In-Reply-To: <000001ce167d$baebc620$30c35260$@excelindia.com> References: <000001ce167d$baebc620$30c35260$@excelindia.com> Message-ID: > #!/usr/bin/env python > > import os > > global name_wo_ext > > name_wo_ext = "d:\\fun" > > os.system("mkdir %s" % (name_wo_ext)) > > > > This gets executed well but there is no directory created L I tried with > another command as below and it works for me > This is not a problem with os.system. Windows 7 has new permission concepts. You must use elevated privileges (i.e. Administrator) to modify items on anything other than your own "Library" space (thank you horrible 'sync' idea). In order to overcome the 'permission' issues you will encounter on Windows 7 whenever creating/modifying folders or files, you must either be "Administrator" (i.e. actually logged in as Administrator) or take ownership of the full path you are trying to use for creation/modification of dirs or files. See the help for "takeown /?" at the command prompt. From dyoo at hashcollision.org Fri Mar 1 21:01:25 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Fri, 1 Mar 2013 13:01:25 -0700 Subject: [Tutor] Reversed dictionary returned by default In-Reply-To: References: Message-ID: > Why is this happening, and how do I get it to work properly (returning > element 0 - n, versus n - 0)? Python dictionaries are unordered collections. When we iterate across them, we can not guarantee that we'll walk the elements in the order that we inserted them. The reason for that is because of the underlying algorithm behind dictionaries, which is the hash table data structure: http://en.wikipedia.org/wiki/Hash_table where the keys are deliberately scattered evenly through the underlying array, in what looks like "random" order, so that later lookups can be very, very fast. For your application, does it matter that you preserve some kind of order of the key-value pairs? From joel.goldstick at gmail.com Fri Mar 1 21:02:06 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 1 Mar 2013 15:02:06 -0500 Subject: [Tutor] Reversed dictionary returned by default In-Reply-To: References: Message-ID: On Fri, Mar 1, 2013 at 2:48 PM, Huperetes wrote: > I am getting the following for my installation. > > Why is this happening, and how do I get it to work properly (returning > element 0 - n, versus n - 0)? > This is happening because dictionaries are not ordered. The fact that it happens to look like it is reverse order isn't guaranteed either. You use the key to access the value. To learn more about this google 'why python dicts are unordered' > > Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] > on win32 > Type "help", "copyright", "credits" or "license" for more information. > > >>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", > "pwd":"secret"} > >>> ["%s=%s" % (k, v) for k, v in params.items()] > > ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim'] > > >>> ";".join(["%s=%s" % (k, v) for k, v in params.items()]) > > 'pwd=secret;database=master;uid=sa;server=mpilgrim' > > >>> > > Thank you. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Fri Mar 1 21:03:07 2013 From: davea at davea.name (Dave Angel) Date: Fri, 01 Mar 2013 15:03:07 -0500 Subject: [Tutor] Reversed dictionary returned by default In-Reply-To: References: Message-ID: <5131097B.8060707@davea.name> On 03/01/2013 02:48 PM, Huperetes wrote: > I am getting the following for my installation. > > Why is this happening, and how do I get it to work properly (returning > element 0 - n, versus n - 0)? > > Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] > on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", > "pwd":"secret"} >>>> ["%s=%s" % (k, v) for k, v in params.items()] > > ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim'] > >>>> ";".join(["%s=%s" % (k, v) for k, v in params.items()]) > > 'pwd=secret;database=master;uid=sa;server=mpilgrim' > >>>> > A dict has by specification no specific ordering. If you want the data sorted, then sort the data after extracting it. Or use some other type. >>>> ["%s=%s" % (k, v) for k, v in sorted(params.items())] the only ordering guarantee that you get from dict is that if you iterate over it twice with no changes to the dict in the meantime, you'll get the same ordering. But what that ordering is, is undefined. It's certainly not the order that things were entered into the dict. -- DaveA From brad.hudson at gmail.com Fri Mar 1 21:07:58 2013 From: brad.hudson at gmail.com (Brad Hudson) Date: Fri, 1 Mar 2013 14:07:58 -0600 Subject: [Tutor] Reversed dictionary returned by default In-Reply-To: References: Message-ID: > I am getting the following for my installation. > > Why is this happening, and how do I get it to work properly (returning > element 0 - n, versus n - 0)? > > Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", >>>> "pwd":"secret"} >>>> ["%s=%s" % (k, v) for k, v in params.items()] > > ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim'] > Dictionaries are unordered, which is why you got the output above (converted from a dict to a list). >>>> ";".join(["%s=%s" % (k, v) for k, v in params.items()]) > > 'pwd=secret;database=master;uid=sa;server=mpilgrim' > example when 'sorted': >>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"} >>> ["%s=%s" % (k, v) for k, v in params.items()] ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim'] >>> ['%s=%s' % (k, v) for k, v in (sorted(params.items()))] ['database=master', 'pwd=secret', 'server=mpilgrim', 'uid=sa'] >>> From ramit.prasad at jpmorgan.com Fri Mar 1 21:35:39 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 1 Mar 2013 20:35:39 +0000 Subject: [Tutor] Reversed dictionary returned by default In-Reply-To: <5131097B.8060707@davea.name> References: <5131097B.8060707@davea.name> Message-ID: <5B80DD153D7D744689F57F4FB69AF474181D0EB4@SCACMX008.exchad.jpmchase.net> Dave Angel wrote: > On 03/01/2013 02:48 PM, Huperetes wrote: > > I am getting the following for my installation. > > > > Why is this happening, and how do I get it to work properly (returning > > element 0 - n, versus n - 0)? > > > > Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] > > on win32 > > Type "help", "copyright", "credits" or "license" for more information. > > > >>>> params = {"server":"mpilgrim", "database":"master", "uid":"sa", > > "pwd":"secret"} > >>>> ["%s=%s" % (k, v) for k, v in params.items()] > > > > ['pwd=secret', 'database=master', 'uid=sa', 'server=mpilgrim'] > > > >>>> ";".join(["%s=%s" % (k, v) for k, v in params.items()]) > > > > 'pwd=secret;database=master;uid=sa;server=mpilgrim' > > > >>>> > > > > A dict has by specification no specific ordering. If you want the data > sorted, then sort the data after extracting it. Or use some other type. > > >>>> ["%s=%s" % (k, v) for k, v in sorted(params.items())] > > the only ordering guarantee that you get from dict is that if you > iterate over it twice with no changes to the dict in the meantime, > you'll get the same ordering. But what that ordering is, is undefined. > It's certainly not the order that things were entered into the dict. > > In Python 2.7+, OP can also try using an OrderedDict[0]. "When iterating over an ordered dictionary, the items are returned in the order their keys were first added." Note, that updating a key will NOT change the order, so you must remove the key/value pair and then re-add it to change the ordering. Ramit [0] http://docs.python.org/2/library/collections.html#collections.OrderedDict This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From losermeloser at yahoo.com Sat Mar 2 00:19:00 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Fri, 1 Mar 2013 15:19:00 -0800 (PST) Subject: [Tutor] confusing installation In-Reply-To: References: <1362105192.70127.YahooMailNeo@web121105.mail.ne1.yahoo.com> Message-ID: <1362179940.21179.YahooMailNeo@web121105.mail.ne1.yahoo.com> > He is showing you what to expect.? Where ever you see a line starting with C:\ that is what he typed into the command line session, and > the lines that follow is the program you are installing informing you what it is doing. (Until you get to the next C:\ or the end) ? i managed to install that file but in the book it shows the file going into http://www.alchemy.org/ and installing it into?site packages, my?install unfortunately didnt do this very last step that involved adding sqlalchemy to easy-install.pth. not sure how to fix it thanks to every that has helped -------------- next part -------------- An HTML attachment was scrubbed... URL: From losermeloser at yahoo.com Sat Mar 2 01:14:26 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Fri, 1 Mar 2013 16:14:26 -0800 (PST) Subject: [Tutor] confusing installation In-Reply-To: References: <1362105192.70127.YahooMailNeo@web121105.mail.ne1.yahoo.com> <1362138629.35548.YahooMailNeo@web121101.mail.ne1.yahoo.com> Message-ID: <1362183266.58296.YahooMailNeo@web121104.mail.ne1.yahoo.com> > problems else where. i will look for some easy install tutorials > If you just want to know about SQL databases you could try my tutorial topic (only in the V2 version at the moment but it's nearly > > identical on V3) It uses SQLite which is part of standard Python, although you can also download a Windows installer for standalone use. > If nothing else it will give you a quick intro to the topic and doesn't cost anything but time... > It sounds like your book is covering a wider range of options than SQL but you might still find mine useful. ? i didnt see this Alan. my interests is only SQL but the book indicates things like ORMs are very important?.. but it doesnt cover SQL indepth, just?simple examples of the same script in?sqlite mysql postgresql and gadfly i think. Im definately after an indepth SQL tutorial. I'll?have a look at yours?now. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jf_byrnes at comcast.net Sat Mar 2 01:42:28 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Fri, 01 Mar 2013 18:42:28 -0600 Subject: [Tutor] confusing installation In-Reply-To: <1362179940.21179.YahooMailNeo@web121105.mail.ne1.yahoo.com> References: <1362105192.70127.YahooMailNeo@web121105.mail.ne1.yahoo.com> <1362179940.21179.YahooMailNeo@web121105.mail.ne1.yahoo.com> Message-ID: On 03/01/2013 05:19 PM, Lolo Lolo wrote: >> He is showing you what to expect. Where ever you see a line >> starting with C:\ that is what he typed into the command line >> session, and > the lines that follow is the program you are >> installing informing you what it is doing. (Until you get to the >> next C:\ or the end) > > i managed to install that file but in the book it shows the file > going into http://www.alchemy.org/ and installing it into site > packages, my install unfortunately didnt do this very last step that > involved adding sqlalchemy to easy-install.pth. not sure how to fix > it > > thanks to every that has helped > I'm sorry I can't help you with with this as I run linux. Even if I jumped ahead and did that chapter I'm sure being on linux my results would be entirely different than you would see on Windows. Regards, Jim From alan.gauld at btinternet.com Sat Mar 2 01:58:53 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 02 Mar 2013 00:58:53 +0000 Subject: [Tutor] confusing installation In-Reply-To: <1362183266.58296.YahooMailNeo@web121104.mail.ne1.yahoo.com> References: <1362105192.70127.YahooMailNeo@web121105.mail.ne1.yahoo.com> <1362138629.35548.YahooMailNeo@web121101.mail.ne1.yahoo.com> <1362183266.58296.YahooMailNeo@web121104.mail.ne1.yahoo.com> Message-ID: On 02/03/13 00:14, Lolo Lolo wrote: > i didnt see this Alan. my interests is only SQL but the book indicates > things like ORMs are very important?.. It depends. In some frameworks like TurboGears or Django ORMs are a big part of the story. In everyday programming I tend to just use straight SQL. Personally I find the extra complexity (and often limitations) that ORMs add is not worth the gain. > gadfly i think. Im definately after an indepth SQL tutorial. I'll have a > look at yours now. Mime isn't in-depth but it does cover the main concepts and how to integrate Python and SQL. Like everything in my tutorial the intention is to get you to the point where you can do the basics yourself but also read and understand the in depth tutorials when you need to go there. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bessenkphilip at gmail.com Sat Mar 2 05:06:30 2013 From: bessenkphilip at gmail.com (bessenkphilip) Date: Sat, 02 Mar 2013 09:36:30 +0530 Subject: [Tutor] Need a mentor, Any help would be great Message-ID: <51317AC6.7090905@gmail.com> Hello, I'm just a newbie in python and it would be great if someone could help me in this. I don't know where to start, I'd like to contribute to small opensource projects too which will help me to learn more in python. Thanks & Regards, -Bessen From alan.gauld at btinternet.com Sat Mar 2 09:16:21 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 02 Mar 2013 08:16:21 +0000 Subject: [Tutor] Need a mentor, Any help would be great In-Reply-To: <51317AC6.7090905@gmail.com> References: <51317AC6.7090905@gmail.com> Message-ID: On 02/03/13 04:06, bessenkphilip wrote: > I'm just a newbie in python and it would be great if someone could > help me in this. Welcome, treat this mailing list as a virtual 'someone'. > I don't know where to start, Tell us something about your background. What level of computer skill do you have? Basic user, sysadmin? etc Have you programmed before? In what languages? What OS and Python version are you using? What kind of programs would you like to work on? There are Python tutorials for every level and style, its just a matter of choosing to the right one for you. Then work through one of them and ask questions here. > I'd like to contribute to small opensource projects > too which will help me to learn more in python. That's a good goal, especially once you get past the beginner stage Start with SourceForge and search for Python projects. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From losermeloser at yahoo.com Sat Mar 2 17:08:00 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Sat, 2 Mar 2013 08:08:00 -0800 (PST) Subject: [Tutor] confusing installation In-Reply-To: References: <1362105192.70127.YahooMailNeo@web121105.mail.ne1.yahoo.com> <1362138629.35548.YahooMailNeo@web121101.mail.ne1.yahoo.com> <1362183266.58296.YahooMailNeo@web121104.mail.ne1.yahoo.com> Message-ID: <1362240480.40578.YahooMailNeo@web121105.mail.ne1.yahoo.com> > Like everything in my tutorial the intention is to get you to the point where you can do the basics yourself but also read and understand > the in depth tutorials when you need to go there. ? i read through some of your tutorial last night and its definately what i need. so i will complete it.. thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From bessenkphilip at gmail.com Sun Mar 3 02:48:48 2013 From: bessenkphilip at gmail.com (bessenkphilip) Date: Sun, 03 Mar 2013 07:18:48 +0530 Subject: [Tutor] Need a mentor, Any help would be great In-Reply-To: References: <51317AC6.7090905@gmail.com> Message-ID: <5132AC00.4010808@gmail.com> Hello, Thanks for the "Welcome". I'm now working as a System admin in Linux that too a Junior level (L1, only coming to a 6 months in experience). I've got 2 to 3 hrs a day to learn python. I've programmed a little bit before like our college staff given us a challenge to display letter format for any number given as input(upto 9 digit). I've done that using C language. I think i know some basics in C, C++ and a little bit java(like small programs which explains concepts of class and objects). I'd love to program something real that too in python. The system i'm working is Ubuntu 11.04 and the python version is Python 2.7.1+ I'd love to work on something (as i don't know about the specific types) real :) Thanks again, -Bessen On 03/02/2013 01:46 PM, Alan Gauld wrote: > On 02/03/13 04:06, bessenkphilip wrote: >> I'm just a newbie in python and it would be great if someone could >> help me in this. > > Welcome, treat this mailing list as a virtual 'someone'. > > > I don't know where to start, > > Tell us something about your background. > > What level of computer skill do you have? Basic user, sysadmin? etc > Have you programmed before? In what languages? > What OS and Python version are you using? > What kind of programs would you like to work on? > > There are Python tutorials for every level and style, its just > a matter of choosing to the right one for you. Then work through > one of them and ask questions here. > >> I'd like to contribute to small opensource projects > > too which will help me to learn more in python. > > That's a good goal, especially once you get past the beginner stage > Start with SourceForge and search for Python projects. > From alan.gauld at btinternet.com Sun Mar 3 09:29:23 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 03 Mar 2013 08:29:23 +0000 Subject: [Tutor] Need a mentor, Any help would be great In-Reply-To: <5132AC00.4010808@gmail.com> References: <51317AC6.7090905@gmail.com> <5132AC00.4010808@gmail.com> Message-ID: On 03/03/13 01:48, bessenkphilip wrote: > Thanks for the "Welcome". I'm now working as a System admin in Linux > I've got 2 to 3 hrs a day to learn python. In that case I'd start with the official tutorial on python.org. Its targeted at people with a little bit of programming experience moving to Python. It's also fairly *nix biased and relevant for sys admin type tasks. > The system i'm working is Ubuntu 11.04 and the python version is Python > 2.7.1+ OK, that's a good solid platform. Once you have done the tutorial try automating some of the tasks you don on a regular basis as a first project. Once comfortable go to SourceForge and find something in Python you can contribute too. Testing and Bug fixing is often a good place to start. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bessenkphilip at gmail.com Sun Mar 3 10:34:58 2013 From: bessenkphilip at gmail.com (bessenkphilip) Date: Sun, 03 Mar 2013 15:04:58 +0530 Subject: [Tutor] Need a mentor, Any help would be great In-Reply-To: References: <51317AC6.7090905@gmail.com> <5132AC00.4010808@gmail.com> Message-ID: <51331942.6070609@gmail.com> Hello, Thank you very much for the help -Bessen On 03/03/2013 01:59 PM, Alan Gauld wrote: > On 03/03/13 01:48, bessenkphilip wrote: > >> Thanks for the "Welcome". I'm now working as a System admin in Linux >> I've got 2 to 3 hrs a day to learn python. > > In that case I'd start with the official tutorial on python.org. > Its targeted at people with a little bit of programming experience > moving to Python. > > It's also fairly *nix biased and relevant for sys admin type tasks. > >> The system i'm working is Ubuntu 11.04 and the python version is Python >> 2.7.1+ > > OK, that's a good solid platform. Once you have done the tutorial try > automating some of the tasks you don on a regular basis as a first > project. > > Once comfortable go to SourceForge and find something in Python you > can contribute too. Testing and Bug fixing is often a good place to > start. > > From russel at winder.org.uk Sun Mar 3 10:55:12 2013 From: russel at winder.org.uk (Russel Winder) Date: Sun, 03 Mar 2013 09:55:12 +0000 Subject: [Tutor] Need a mentor, Any help would be great In-Reply-To: References: <51317AC6.7090905@gmail.com> <5132AC00.4010808@gmail.com> Message-ID: <1362304512.32103.45.camel@anglides.winder.org.uk> On Sun, 2013-03-03 at 08:29 +0000, Alan Gauld wrote: [?] > Once comfortable go to SourceForge and find something in Python you can > contribute too. Testing and Bug fixing is often a good place to start. Probably should flag BitBucket and GitHub as well ? -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From kwpolska at gmail.com Sun Mar 3 13:51:21 2013 From: kwpolska at gmail.com (Kwpolska) Date: Sun, 3 Mar 2013 13:51:21 +0100 Subject: [Tutor] Need a mentor, Any help would be great In-Reply-To: <1362304512.32103.45.camel@anglides.winder.org.uk> References: <51317AC6.7090905@gmail.com> <5132AC00.4010808@gmail.com> <1362304512.32103.45.camel@anglides.winder.org.uk> Message-ID: On Sun, Mar 3, 2013 at 10:55 AM, Russel Winder wrote: > On Sun, 2013-03-03 at 08:29 +0000, Alan Gauld wrote: > [?] >> Once comfortable go to SourceForge and find something in Python you can >> contribute too. Testing and Bug fixing is often a good place to start. > > Probably should flag BitBucket and GitHub as well ? Not ?as well?, ?instead?. Because SF is anywhere near human-friendly, and many awesome coders are on BitBucket (eg. the Pocoo team) and GitHub (eg. Kenneth Reitz), you can also find some good people on Launchpad. -- Kwpolska | GPG KEY: 5EAAEA16 stop html mail | always bottom-post http://asciiribbon.org | http://caliburn.nl/topposting.html From russel at winder.org.uk Sun Mar 3 14:17:53 2013 From: russel at winder.org.uk (Russel Winder) Date: Sun, 03 Mar 2013 13:17:53 +0000 Subject: [Tutor] Need a mentor, Any help would be great In-Reply-To: References: <51317AC6.7090905@gmail.com> <5132AC00.4010808@gmail.com> <1362304512.32103.45.camel@anglides.winder.org.uk> Message-ID: <1362316673.6545.12.camel@launcelot.winder.org.uk> On Sun, 2013-03-03 at 13:51 +0100, Kwpolska wrote: > On Sun, Mar 3, 2013 at 10:55 AM, Russel Winder wrote: > > On Sun, 2013-03-03 at 08:29 +0000, Alan Gauld wrote: > > [?] > >> Once comfortable go to SourceForge and find something in Python you can > >> contribute too. Testing and Bug fixing is often a good place to start. > > > > Probably should flag BitBucket and GitHub as well ? > > Not ?as well?, ?instead?. Because SF is anywhere near human-friendly, > and many awesome coders are on BitBucket (eg. the Pocoo team) and > GitHub (eg. Kenneth Reitz), you can also find some good people on > Launchpad. Actually I was thinking "instead" :-) I am less sure about Launchpad these days. For whatever reasons Bazaar is having Canonical resource removed so has no development momentum. It is a great DVCS but Mercurial and especially Git have the mindshare. Although Python (and Java) are in Mercurial, there seems to be a trend to say Git is the winner of the DVCS war. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From doanviettrung at gmail.com Mon Mar 4 03:24:37 2013 From: doanviettrung at gmail.com (DoanVietTrungAtGmail) Date: Mon, 4 Mar 2013 13:24:37 +1100 Subject: [Tutor] A CSV field is a list of integers - how to read it as such? Message-ID: Dear tutors I am checking out csv as a possible data structure for my records. In each record, some fields are an integer and some are a list of integers of variable length. I use csv.DictWriter to write data. When reading out using csv.DictReader, each row is read as a string, per the csv module's standard behaviour. To get these columns as lists of integers, I can think of only a multi-step process: first, remove the brackets enclosing the string; second, split the string into a list containing substrings; third, convert each substring into an integer. This process seems inelegant. Is there a better way to get integers and lists of integers from a csv file? Or, is a csv file simply not the best data structure given the above requirement? Apart from csv, I considered using a dict or list, or using an object to represent each row. I am being attracted to csv because csv means serialisation is unnecessary, I just need to close and open the file to stop and continue later (it's a simulation experiment). Also, I am guessing but haven't checked, csv is more space efficient. Each row contains a few integers plus a few lists containing hundreds of integers, and there will be up to hundreds of millions of rows. CODE: My Python 2.7 code is below. It doesn't have the third step (substring -> int). import csv record1 = {'id':1, 'type':1, 'level':1, 'ListInRecord':[2, 9]} record2 = {'id':2, 'type':1, 'level':1, 'ListInRecord':[1, 9]} record3 = {'id':3, 'type':2, 'level':1, 'ListInRecord':[2]} record9 = {'id':9, 'type':3, 'level':0, 'ListInRecord':[]} rows = [record1, record2, record3, record9] header = ['id', 'type', 'level', 'ListInRecord'] with open('testCSV.csv', 'wb') as f: fCSV = csv.DictWriter(f, header) fCSV.writeheader() fCSV.writerows(rows) with open('testCSV.csv', 'r') as f: fCSV = csv.DictReader(f) for row in fCSV: print 'ID=', row['id'],'ListInRecord=', row['ListInRecord'][1:-1].split(', ') # I want this to be a list of integers, NOT list of strings OUTPUT: ID= 1 ListInRecord= ['2', '9'] ID= 2 ListInRecord= ['1', '9'] ID= 3 ListInRecord= ['2'] ID= 9 ListInRecord= [''] Trung Doan -------------- next part -------------- An HTML attachment was scrubbed... URL: From dfjennings at gmail.com Mon Mar 4 03:52:57 2013 From: dfjennings at gmail.com (Don Jennings) Date: Sun, 3 Mar 2013 21:52:57 -0500 Subject: [Tutor] A CSV field is a list of integers - how to read it as such? In-Reply-To: References: Message-ID: On Mar 3, 2013, at 9:24 PM, DoanVietTrungAtGmail wrote: > Dear tutors > > I am checking out csv as a possible data structure for my records. In each record, some fields are an integer and some are a list of integers of variable length. I use csv.DictWriter to write data. When reading out using csv.DictReader, each row is read as a string, per the csv module's standard behaviour. To get these columns as lists of integers, I can think of only a multi-step process: first, remove the brackets enclosing the string; second, split the string into a list containing substrings; third, convert each substring into an integer. This process seems inelegant. Is there a better way to get integers and lists of integers from a csv file? A quick search for "python list object from string representation of list" returned an idea from stackoverflow which I have adapted for integers: >>> import ast >>> num_string = "[1, 2, 3]" >>> ast.literal_eval(num_string) [1, 2, 3] Take care, Don From davea at davea.name Mon Mar 4 04:12:40 2013 From: davea at davea.name (Dave Angel) Date: Sun, 03 Mar 2013 22:12:40 -0500 Subject: [Tutor] A CSV field is a list of integers - how to read it as such? In-Reply-To: References: Message-ID: <51341128.7070902@davea.name> On 03/03/2013 09:24 PM, DoanVietTrungAtGmail wrote: > Dear tutors > > I am checking out csv as a possible data structure for my records. In each > record, some fields are an integer and some are a list of integers of > variable length. I use csv.DictWriter to write data. When reading out using > csv.DictReader, each row is read as a string, per the csv module's standard > behaviour. To get these columns as lists of integers, I can think of only a > multi-step process: first, remove the brackets enclosing the string; > second, split the string into a list containing substrings; third, convert > each substring into an integer. This process seems inelegant. Is there a > better way to get integers and lists of integers from a csv file? > > Or, is a csv file simply not the best data structure given the above > requirement? Your terminology is very confusing. A csv is not a data structure, it's a method of serializing lists of strings. Or in this case dicts of strings. If a particular dict value isn't a string, it'll get converted to one implicitly. csv does not handle variable length records, so this is close to the best you're going to do. Apart from csv, I considered using a dict or list, or using an > object to represent each row. Objects don't exist in a file, so they don't persist between multiple runs of the program. Likewise dict and list. So no idea what you really meant. I am being attracted to csv because csv means > serialisation is unnecessary, I just need to close and open the file to > stop and continue later (it's a simulation experiment). Closing and opening don't do anything to persist data, but we can guess you must have meant to imply reading and writing as well. And you've nicely finessed the serialization in the write step, but as you discovered, you'll have to handle the deserialization to get back to ints and list. Also, I am guessing > but haven't checked, csv is more space efficient. More space efficient than what? Each row contains a few > integers plus a few lists containing hundreds of integers, and there will > be up to hundreds of millions of rows. > > CODE: My Python 2.7 code is below. It doesn't have the third step > (substring -> int). > > import csv > > record1 = {'id':1, 'type':1, 'level':1, 'ListInRecord':[2, 9]} > record2 = {'id':2, 'type':1, 'level':1, 'ListInRecord':[1, 9]} > record3 = {'id':3, 'type':2, 'level':1, 'ListInRecord':[2]} > record9 = {'id':9, 'type':3, 'level':0, 'ListInRecord':[]} > rows = [record1, record2, record3, record9] > header = ['id', 'type', 'level', 'ListInRecord'] > > with open('testCSV.csv', 'wb') as f: > fCSV = csv.DictWriter(f, header) > fCSV.writeheader() > fCSV.writerows(rows) > > with open('testCSV.csv', 'r') as f: > fCSV = csv.DictReader(f) > for row in fCSV: I'd add the deserialization here. For each item in row, if the value begins and ends with [ ] then make it into a list, and if a digit or minus-sign, make it into an int. Then for the lists, convert each element to an int. You can use Don Jennings suggestion to save a lost of effort here. This should reconstruct the original recordn precisely. But it'll take some testing to be sure. > print 'ID=', row['id'],'ListInRecord=', > row['ListInRecord'][1:-1].split(', ') # I want this to be a list of > integers, NOT list of strings > > OUTPUT: > > ID= 1 ListInRecord= ['2', '9'] > ID= 2 ListInRecord= ['1', '9'] > ID= 3 ListInRecord= ['2'] > ID= 9 ListInRecord= [''] > -- DaveA From doanviettrung at gmail.com Mon Mar 4 07:48:28 2013 From: doanviettrung at gmail.com (DoanVietTrungAtGmail) Date: Mon, 4 Mar 2013 17:48:28 +1100 Subject: [Tutor] A CSV field is a list of integers - how to read it as such? In-Reply-To: <51341128.7070902@davea.name> References: <51341128.7070902@davea.name> Message-ID: Don, Dave - Thanks for your help! Don: Thanks! I've just browsed the AST documentation, much of it goes over my head, but the ast.literal_eval helper function works beautifully for me. Dave: Again, thanks! Also, you asked "More space efficient than what?" I meant .csv versus dict, list, and objects. Specifically, if I read a 10-million row .csv file into RAM, how is its RAM footprint compared to a list or dict containing 10M equivalent items, or to 10M equivalent class instances living in RAM. I've just tested and learned that a .csv file has very little overhead, in the order of bytes not KB. Presumably the same applies when the file is read into RAM. As to the RAM overheads of dict, list, and class instances, I've just found some stackoverflow discussions. Onesays that for large lists in CPython, "the overallocation is 12.5 percent". Trung Doan ============ On Mon, Mar 4, 2013 at 2:12 PM, Dave Angel wrote: > On 03/03/2013 09:24 PM, DoanVietTrungAtGmail wrote: > >> Dear tutors >> >> I am checking out csv as a possible data structure for my records. In each >> record, some fields are an integer and some are a list of integers of >> variable length. I use csv.DictWriter to write data. When reading out >> using >> csv.DictReader, each row is read as a string, per the csv module's >> standard >> behaviour. To get these columns as lists of integers, I can think of only >> a >> multi-step process: first, remove the brackets enclosing the string; >> second, split the string into a list containing substrings; third, convert >> each substring into an integer. This process seems inelegant. Is there a >> better way to get integers and lists of integers from a csv file? >> >> Or, is a csv file simply not the best data structure given the above >> requirement? >> > > Your terminology is very confusing. A csv is not a data structure, it's a > method of serializing lists of strings. Or in this case dicts of strings. > If a particular dict value isn't a string, it'll get converted to one > implicitly. csv does not handle variable length records, so this is close > to the best you're going to do. > > > Apart from csv, I considered using a dict or list, or using an > >> object to represent each row. >> > > Objects don't exist in a file, so they don't persist between multiple runs > of the program. Likewise dict and list. So no idea what you really meant. > > > I am being attracted to csv because csv means > >> serialisation is unnecessary, I just need to close and open the file to >> stop and continue later (it's a simulation experiment). >> > > Closing and opening don't do anything to persist data, but we can guess > you must have meant to imply reading and writing as well. And you've > nicely finessed the serialization in the write step, but as you discovered, > you'll have to handle the deserialization to get back to ints and list. > > > Also, I am guessing > >> but haven't checked, csv is more space efficient. >> > > More space efficient than what? > > > Each row contains a few > >> integers plus a few lists containing hundreds of integers, and there will >> be up to hundreds of millions of rows. >> >> CODE: My Python 2.7 code is below. It doesn't have the third step >> (substring -> int). >> >> import csv >> >> record1 = {'id':1, 'type':1, 'level':1, 'ListInRecord':[2, 9]} >> record2 = {'id':2, 'type':1, 'level':1, 'ListInRecord':[1, 9]} >> record3 = {'id':3, 'type':2, 'level':1, 'ListInRecord':[2]} >> record9 = {'id':9, 'type':3, 'level':0, 'ListInRecord':[]} >> rows = [record1, record2, record3, record9] >> header = ['id', 'type', 'level', 'ListInRecord'] >> >> with open('testCSV.csv', 'wb') as f: >> fCSV = csv.DictWriter(f, header) >> fCSV.writeheader() >> fCSV.writerows(rows) >> >> with open('testCSV.csv', 'r') as f: >> fCSV = csv.DictReader(f) >> for row in fCSV: >> > > I'd add the deserialization here. For each item in row, if the value > begins and ends with [ ] then make it into a list, and if a digit or > minus-sign, make it into an int. Then for the lists, convert each element > to an int. You can use Don Jennings suggestion to save a lost of effort > here. > > This should reconstruct the original recordn precisely. But it'll take > some testing to be sure. > > > print 'ID=', row['id'],'ListInRecord=', >> row['ListInRecord'][1:-1].**split(', ') # I want this to be a list of >> integers, NOT list of strings >> >> OUTPUT: >> >> ID= 1 ListInRecord= ['2', '9'] >> ID= 2 ListInRecord= ['1', '9'] >> ID= 3 ListInRecord= ['2'] >> ID= 9 ListInRecord= [''] >> >> > > -- > DaveA > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > On Mon, Mar 4, 2013 at 2:12 PM, Dave Angel wrote: > On 03/03/2013 09:24 PM, DoanVietTrungAtGmail wrote: > >> Dear tutors >> >> I am checking out csv as a possible data structure for my records. In each >> record, some fields are an integer and some are a list of integers of >> variable length. I use csv.DictWriter to write data. When reading out >> using >> csv.DictReader, each row is read as a string, per the csv module's >> standard >> behaviour. To get these columns as lists of integers, I can think of only >> a >> multi-step process: first, remove the brackets enclosing the string; >> second, split the string into a list containing substrings; third, convert >> each substring into an integer. This process seems inelegant. Is there a >> better way to get integers and lists of integers from a csv file? >> >> Or, is a csv file simply not the best data structure given the above >> requirement? >> > > Your terminology is very confusing. A csv is not a data structure, it's a > method of serializing lists of strings. Or in this case dicts of strings. > If a particular dict value isn't a string, it'll get converted to one > implicitly. csv does not handle variable length records, so this is close > to the best you're going to do. > > > Apart from csv, I considered using a dict or list, or using an > >> object to represent each row. >> > > Objects don't exist in a file, so they don't persist between multiple runs > of the program. Likewise dict and list. So no idea what you really meant. > > > I am being attracted to csv because csv means > >> serialisation is unnecessary, I just need to close and open the file to >> stop and continue later (it's a simulation experiment). >> > > Closing and opening don't do anything to persist data, but we can guess > you must have meant to imply reading and writing as well. And you've > nicely finessed the serialization in the write step, but as you discovered, > you'll have to handle the deserialization to get back to ints and list. > > > Also, I am guessing > >> but haven't checked, csv is more space efficient. >> > > More space efficient than what? > > > Each row contains a few > >> integers plus a few lists containing hundreds of integers, and there will >> be up to hundreds of millions of rows. >> >> CODE: My Python 2.7 code is below. It doesn't have the third step >> (substring -> int). >> >> import csv >> >> record1 = {'id':1, 'type':1, 'level':1, 'ListInRecord':[2, 9]} >> record2 = {'id':2, 'type':1, 'level':1, 'ListInRecord':[1, 9]} >> record3 = {'id':3, 'type':2, 'level':1, 'ListInRecord':[2]} >> record9 = {'id':9, 'type':3, 'level':0, 'ListInRecord':[]} >> rows = [record1, record2, record3, record9] >> header = ['id', 'type', 'level', 'ListInRecord'] >> >> with open('testCSV.csv', 'wb') as f: >> fCSV = csv.DictWriter(f, header) >> fCSV.writeheader() >> fCSV.writerows(rows) >> >> with open('testCSV.csv', 'r') as f: >> fCSV = csv.DictReader(f) >> for row in fCSV: >> > > I'd add the deserialization here. For each item in row, if the value > begins and ends with [ ] then make it into a list, and if a digit or > minus-sign, make it into an int. Then for the lists, convert each element > to an int. You can use Don Jennings suggestion to save a lost of effort > here. > > This should reconstruct the original recordn precisely. But it'll take > some testing to be sure. > > > print 'ID=', row['id'],'ListInRecord=', >> row['ListInRecord'][1:-1].**split(', ') # I want this to be a list of >> integers, NOT list of strings >> >> OUTPUT: >> >> ID= 1 ListInRecord= ['2', '9'] >> ID= 2 ListInRecord= ['1', '9'] >> ID= 3 ListInRecord= ['2'] >> ID= 9 ListInRecord= [''] >> >> > > -- > DaveA > ______________________________**_________________ > 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 steve at pearwood.info Mon Mar 4 08:27:46 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 04 Mar 2013 18:27:46 +1100 Subject: [Tutor] A CSV field is a list of integers - how to read it as such? In-Reply-To: References: <51341128.7070902@davea.name> Message-ID: <51344CF2.9020309@pearwood.info> On 04/03/13 17:48, DoanVietTrungAtGmail wrote: > Don, Dave - Thanks for your help! > > Don: Thanks! I've just browsed the AST documentation, much of it goes over > my head, but the ast.literal_eval helper function works beautifully for me. > > Dave: Again, thanks! Also, you asked "More space efficient than what?" I > meant .csv versus dict, list, and objects. Specifically, if I read a > 10-million row .csv file into RAM, how is its RAM footprint compared to a > list or dict containing 10M equivalent items, or to 10M equivalent class > instances living in RAM. I've just tested and learned that a .csv file has > very little overhead, in the order of bytes not KB. Presumably the same > applies when the file is read into RAM. How many items per row? How many characters per item? CSV files are just text files. So they'll take as much memory as they have characters, multiplied by the number of bytes per character, e.g.: ASCII or Latin-1: 1 byte per character UTC-16: 2 bytes per character UTC-32: 4 bytes per character UTF-8: variable, depends on the characters but typically close to 1 byte for Western-European text. Suppose you have CSV stored in UTC-16, 10-million rows, with 1 hundred columns per row, and each column averages 30 characters, giving approximately 6200 bytes per row, or 62 gigabytes in total. That's a pretty big file. Does your computer have 62 GB of memory? If not, you're going to have a bit of trouble reading in the entire file all at once... But if you process only one row at a time, you only have to handle about 6.2 KB per row at a time. When that gets converted into a list of strings, that will take about 24 KB. > As to the RAM overheads of dict, list, and class instances, I've just found > some stackoverflow discussions. > Onesays > that for large lists in CPython, "the overallocation is 12.5 percent". Yes. Do you have a question about it? -- Steven From brad.hudson at gmail.com Mon Mar 4 13:41:57 2013 From: brad.hudson at gmail.com (Brad Hudson) Date: Mon, 4 Mar 2013 06:41:57 -0600 Subject: [Tutor] Problem with os.system In-Reply-To: <007301ce18a5$6d59df80$480d9e80$@excelindia.com> References: <000001ce167d$baebc620$30c35260$@excelindia.com> <007301ce18a5$6d59df80$480d9e80$@excelindia.com> Message-ID: > I have given the admin privileges for my drive but still os.system won't > work :( > Are you saying you applied "Administrator" privileges to the drive/folder? If so, are you executing your script as a normal user or as "Administrator"? Example: In order to run something from the command prompt as "Administrator" when you are not directly logged in as "Administrator" in Windows 7, you must right click on the "Command Prompt" shortcut and then click "Run as administrator" to invoke those privileges. > I have used os.system not only to create directories but to invoke some > exe's as well. But this also not seems to work. > > Is there any other settings that I need to check or enable ? Have you tried simply invoking python (i.e. idle) and walking through each of your commands step by step? From davea at davea.name Mon Mar 4 14:24:47 2013 From: davea at davea.name (Dave Angel) Date: Mon, 04 Mar 2013 08:24:47 -0500 Subject: [Tutor] A CSV field is a list of integers - how to read it as such? In-Reply-To: References: <51341128.7070902@davea.name> Message-ID: <5134A09F.1090907@davea.name> On 03/04/2013 01:48 AM, DoanVietTrungAtGmail wrote: > Don, Dave - Thanks for your help! > > Don: Thanks! I've just browsed the AST documentation, much of it goes over > my head, but the ast.literal_eval helper function works beautifully for me. > > Dave: Again, thanks! Also, you asked "More space efficient than what?" I > meant .csv versus dict, list, and objects. Specifically, if I read a > 10-million row .csv file into RAM, how is its RAM footprint compared to a > list or dict containing 10M equivalent items, or to 10M equivalent class > instances living in RAM. Once a csv file has been read by a csv reader (such as DictReader), it's no longer a csv file. The data in memory never exists as a copy of the file on disk. The way you wrote the code, each row exists as a dict of strings, but more commonly, each row would exist as a list of strings. The csv logic does not keep more than one row at a time, so if you want a big list to exist at one time, you'll be making one yourself. (Perhaps by using append inside the loop instead of the print you're doing now). So the question is not how much RAM does the csvdata take up, but how much RAM is used by whatever form you use. In that, you shouldn't worry about the overhead of the list, but the overhead of however you store each individual row. When a list overallocates, the "unused rows" each take up 4 or 8 bytes, as opposed to probably thousands of bytes for each row that is used. I've just tested and learned that a .csv file has > very little overhead, in the order of bytes not KB. Presumably the same > applies when the file is read into RAM. > > As to the RAM overheads of dict, list, and class instances, I've just found > some stackoverflow discussions. > Onesays > that for large lists in CPython, "the > overallocation is 12.5 percent". > So the first question is whether you really need the data to all be instantly addressable in RAM at one time. If you can do all your processing a row at a time, then the problem goes away. Assuming you do need random access to the rows, then the next thing to consider is whether a dict is the best way to describe the "columns". Since every dict has the same keys, and since they're presumably known to your source code, then a custom class for the row is probably better, and a namedtuple is probably exactly what you want. There is then no overhead for the names of the columns, and the elements of the tuple are either ints or lists of ints. If that's not compact enough, then the next thing to consider is how you store those ints. If there's lots of them, and especially if you can constrain how big the largest is, then you could use the array module. It assumes all the numeric items are limited to a particular size, and you can specify that size. For example, if all the ints are nonnegative and less than 256, you could do: import array myarray = array.array('b', mylist) An array is somewhat slower than a list, but it holds lots more integers in a given space. Since ram size is your concern, the fact that you happen to serialize it into a csv is irrelevant. That's a good choice if you want to be able to examine the data in a text editor, or import it into a spreadsheet. If you have other requirements, we can figure them out in a separate question. -- DaveA From steve at pearwood.info Mon Mar 4 15:01:22 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 05 Mar 2013 01:01:22 +1100 Subject: [Tutor] A CSV field is a list of integers - how to read it as such? In-Reply-To: <5134A09F.1090907@davea.name> References: <51341128.7070902@davea.name> <5134A09F.1090907@davea.name> Message-ID: <5134A932.4020305@pearwood.info> On 05/03/13 00:24, Dave Angel wrote: > import array > myarray = array.array('b', mylist) > > An array is somewhat slower than a list, I think that it's true that using a list *can* be faster, but that's only because we're comparing apples with oranges. Arrays do more work than lists. For example, using Python 2.7 constructing an array is much slower than constructing a list: [steve at ando ~]$ python -m timeit -s "from array import array" "array('b', xrange(100))" 100000 loops, best of 3: 19.1 usec per loop [steve at ando ~]$ python -m timeit "list(xrange(100))" 100000 loops, best of 3: 3.26 usec per loop but that's only because the list code doesn't perform the same range checking as the array does. If we add range checking ourselves, we see very different results: [steve at ando ~]$ python -m timeit "list(x for x in xrange(100) if 0 <= x < 256)" 10000 loops, best of 3: 27.4 usec per loop So I would suggest that constructing an array is significantly faster than constructing a restricted list. Here's another example: summing a list versus an array. In this specific example, there is a small but consistent advantage to lists, but probably not one that's worth caring about: [steve at ando ~]$ python -m timeit -s "arr = range(100)" "sum(arr)" 100000 loops, best of 3: 2.34 usec per loop [steve at ando ~]$ python -m timeit -s "from array import array" -s "arr = array('b', range(100))" "sum(arr)" 100000 loops, best of 3: 2.78 usec per loop -- Steven From losermeloser at yahoo.com Mon Mar 4 17:30:15 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Mon, 4 Mar 2013 08:30:15 -0800 (PST) Subject: [Tutor] some web and python version questions Message-ID: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> Hey all, i am running python 3.0 but i realized a lot of modules that support version 3 do not support 3.0. now i want to install Python 3.3 but im worried the two versions?(3.0 and 3.3) might confuse my machine. i don't want to lose my work in 3.0 and i installed some modules and saved some work in that version. Im on Windows, and my main worry is confusing my PC and making it get the versions mixed up. i also want to leave room to install version 2 if i ever need to but ill cross that bridge when i get there. For now i want to know if i have to delete version 3.0 before installing 3.3? ? Also i want to learn web development and saw only a few modules support Python 3. As i don't know anything about this subject i just wanted to ask which is a better bet, Bottle or Cherrypy? I am not creating/managing any websites this is just to learn. Also is Pyramid a lightweight framework as its description suggests or is it big/complex like Django? As a learner are my 1st two options a safer bet than the latter 2? -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Mon Mar 4 18:29:27 2013 From: davea at davea.name (Dave Angel) Date: Mon, 04 Mar 2013 12:29:27 -0500 Subject: [Tutor] some web and python version questions In-Reply-To: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> Message-ID: <5134D9F7.7010407@davea.name> On 03/04/2013 11:30 AM, Lolo Lolo wrote: > Hey all, i am running python 3.0 but i realized a lot of modules that support version 3 do not support 3.0. now i want to install Python 3.3 but im worried the two versions (3.0 and 3.3) might confuse my machine. i don't want to lose my work in 3.0 and i installed some modules and saved some work in that version. Im on Windows, and my main worry is confusing my PC and making it get the versions mixed up. i also want to leave room to install version 2 if i ever need to but ill cross that bridge when i get there. For now i want to know if i have to delete version 3.0 before installing 3.3? > It's also a good idea to specify your OS and version. I'm going to guess you're running Windows, XP or Win7. I'd migrate off of Python 3.0 as soon as possible. It was the buggiest version out there. Not surprising because it was the first version of some major rewriting. Anyway, 3.3 not only has more features, but the implementation has been greatly cleaned up. Python 3.3 will definitely install independently of 3.0 on Windows. It's only the minor versions that happen in place, like going from 3.3 to 3.3.1 The catches are that: 1) any 3rd party libraries you've installed in 3.0's install directory will need to be reinstalled in the new directory. 2) Only one of the two can be the "default" installation. That's a choice you make while installing the new one, either to keep the old version as default, or to make the new one default. Windows registry entries may have to change if you later change your mind about the default. Python 3.3 on Windows does come with a version detector, where it installs a stub in the Windows directory, and that stub examines the shebang line of your main script to figure out which version of Python to run. I've never used it, since it came out after I had stopped using Windows. If you're running your scripts explicitly, by something like: python myscript.py then you should be able to say python3.3 myscript.py or python3.0 myscript.py to be explicit. These are just batch files, and you can add more to suit your requirements. > Also i want to learn web development .... > I can't help here. -- DaveA From alan.gauld at btinternet.com Mon Mar 4 18:58:54 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 04 Mar 2013 17:58:54 +0000 Subject: [Tutor] some web and python version questions In-Reply-To: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> Message-ID: On 04/03/13 16:30, Lolo Lolo wrote: > Also i want to learn web development ... > ask which is a better bet, Bottle or Cherrypy? ... Also is Pyramid a > lightweight framework as its description suggests or is it big/complex > like Django? There are so many web frameworks for Python that asking which is bet is rather pointless. They are all fairly good, some are very good for specific tasks, others are more general. The main thing to start with is pick one and learn it. You can switch later once you understand the concepts but stick with one until you do. My personal recommendation would be either to go direct to Django or try CherryPy. But there are plenty of advocates for the other options too. It really is less important which one you choose, rather focus on understanding the concepts of translating urls to Python methods, using templates to isolate code from presentation and using databases to store data. The frameworks all facilitate these features in one way or another. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From russel at winder.org.uk Mon Mar 4 19:41:19 2013 From: russel at winder.org.uk (Russel Winder) Date: Mon, 04 Mar 2013 18:41:19 +0000 Subject: [Tutor] some web and python version questions In-Reply-To: References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> Message-ID: <1362422479.6267.24.camel@lionors.winder.org.uk> On Mon, 2013-03-04 at 17:58 +0000, Alan Gauld wrote: [?] > There are so many web frameworks for Python that asking which is bet is > rather pointless. They are all fairly good, some are very good for > specific tasks, others are more general. The main thing to start with is > pick one and learn it. You can switch later once you understand the > concepts but stick with one until you do. I think it probably is worth dividing the "full stack" frameworks from the microframeworks since although the latter can be combined with other frameworks to emulate the former, they can serve better for some web applications that do not need big database support. > My personal recommendation would be either to go direct to Django > or try CherryPy. But there are plenty of advocates for the other options > too. It really is less important which one you choose, rather focus on > understanding the concepts of translating urls to Python methods, using > templates to isolate code from presentation and using databases to store > data. The frameworks all facilitate these features in one way or another. Many will argue that there are better full stack frameworks, but as of today Django is definitely a "not wrong" proposal. Principally because the documentation is very extensive and there is an excellent tutorial using TDD at http://www.tdd-django-tutorial.com/ For microframeworks, Bottle is getting a lot of good press. Flask also except that it doesn't have a Python 3 presence as far as I know just now. -- Russel. ============================================================================= Dr Russel Winder t: +44 20 7585 2200 voip: sip:russel.winder at ekiga.net 41 Buckmaster Road m: +44 7770 465 077 xmpp: russel at winder.org.uk London SW11 1EN, UK w: www.russel.org.uk skype: russel_winder -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 198 bytes Desc: This is a digitally signed message part URL: From losermeloser at yahoo.com Mon Mar 4 20:58:16 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Mon, 4 Mar 2013 11:58:16 -0800 (PST) Subject: [Tutor] some web and python version questions In-Reply-To: <5134D9F7.7010407@davea.name> References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> <5134D9F7.7010407@davea.name> Message-ID: <1362427096.33527.YahooMailNeo@web121102.mail.ne1.yahoo.com> >Python 3.3 will definitely install independently of 3.0 on Windows. It's only the minor versions that happen in place, like going from 3.3 >to 3.3.1 >If you're running your scripts explicitly, by something like: > ? python? myscript.py >then you should be able to say > ? python3.3? myscript.py >or? python3.0? myscript.py ? thanks it installed independently like you said. and those? python3.3 or? python3.0 in the command line seems to do the trick! -------------- next part -------------- An HTML attachment was scrubbed... URL: From losermeloser at yahoo.com Mon Mar 4 21:02:27 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Mon, 4 Mar 2013 12:02:27 -0800 (PST) Subject: [Tutor] some web and python version questions In-Reply-To: References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> Message-ID: <1362427347.74887.YahooMailNeo@web121105.mail.ne1.yahoo.com> thanks for the recommendations. I think i will try?a smaller framework first (haven't decided which) to learn how it all works without the additional features. Then probably will go for Django?after i?get comfortable working with the web??? -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Tue Mar 5 00:35:55 2013 From: eryksun at gmail.com (eryksun) Date: Mon, 4 Mar 2013 18:35:55 -0500 Subject: [Tutor] some web and python version questions In-Reply-To: <1362427096.33527.YahooMailNeo@web121102.mail.ne1.yahoo.com> References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> <5134D9F7.7010407@davea.name> <1362427096.33527.YahooMailNeo@web121102.mail.ne1.yahoo.com> Message-ID: On Mon, Mar 4, 2013 at 2:58 PM, Lolo Lolo wrote: >>then you should be able to say >> python3.3 myscript.py >>or python3.0 myscript.py > > thanks it installed independently like you said. and those python3.3 or > python3.0 in the command line seems to do the trick! I don't know how that's working. There are no executables or batch files with those names in the default installations. It's always "python.exe". Plus the default install options don't muck with the PATH environment variable. Did you rename (or NTFS symlink) the executables and add the install directories to your PATH? 3.3 installs py.exe to the Windows directory, which you can use like this: py -3.3 myscript.py py -3.0 myscript.py Or add a shebang to the first line of the script such as #!/usr/bin/env python3.0 Then you can simply run myscipt.py. The 3.3 installer associates the extension with py.exe, which parses the shebang line. From pravyareddy at gmail.com Tue Mar 5 01:28:58 2013 From: pravyareddy at gmail.com (Pravya Reddy) Date: Mon, 4 Mar 2013 16:28:58 -0800 Subject: [Tutor] print label error Message-ID: Hi I am having a builtin intendation error for print Addem(3,2).Does it vary for different versions of python? How to clear the error? def Addem(this, that): return this + that print Addem(3, 2) print Addem("book", "worm") print Addem(3.2, 1) try: print Addem("caution",1) except TypeError: print('typeerror raised for Addem("caution", 1)) try: print Addem(14) except TypeError: print('typeerror raised for Addem(14)') print Addem print("Addems done.") def PrintSum(this, that): print(this + that) print(printsum('high', 'heel') def DoSomething(data): for index,datum in enumerate(data): print(datum,) if index % 3 == 2: print print a_string = "earthshine" a_list = [1,2,3,4,5,6,7] DoSomething(a_string) DoSomething(a_list) -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Tue Mar 5 02:00:57 2013 From: davea at davea.name (Dave Angel) Date: Mon, 04 Mar 2013 20:00:57 -0500 Subject: [Tutor] print label error In-Reply-To: References: Message-ID: <513543C9.5040405@davea.name> On 03/04/2013 07:28 PM, Pravya Reddy wrote: > Hi > I am having a builtin intendation error for print Addem(3,2).Does it vary > for different versions of python? > How to clear the error? > > > def Addem(this, that): > return this + that > print Addem(3, 2) The print statement doesn't line up with the return statement, and it doesn't line up with the def statement. Those are the only two valid indentations. I expect you intended these lines to begin at the left margin, and the two spaces are going to be a problem. This is true for every version of Python. However, there is one difference about indentation that I know of: starting in version 3, mixing tabs and spaces is an explicit error instead of just a really stupid idea. > print Addem("book", "worm") > print Addem(3.2, 1) > try: > print Addem("caution",1) > except TypeError: > print('typeerror raised for Addem("caution", 1)) > try: > print Addem(14) > except TypeError: > print('typeerror raised for Addem(14)') > print Addem > print("Addems done.") > def PrintSum(this, that): > print(this + that) > print(printsum('high', 'heel') > def DoSomething(data): > for index,datum in enumerate(data): > print(datum,) > if index % 3 == 2: > print > print > a_string = "earthshine" > a_list = [1,2,3,4,5,6,7] > DoSomething(a_string) > DoSomething(a_list) > > Next time, please include the actual error message, which was probably about 4 lines long. It would make things much easier. -- DaveA From charles.leviton at gmail.com Tue Mar 5 02:22:07 2013 From: charles.leviton at gmail.com (Charles Leviton) Date: Mon, 4 Mar 2013 20:22:07 -0500 Subject: [Tutor] Fwd: findall() returns tuples or string? In-Reply-To: References: Message-ID: I have some confusion regarding when findall returns a list of strings and when it returns a list of tuples. Would appreciate an explanation. I thought if I "grouped" my match string using parentheses I'd get a list of tuples but this example below belies my expectation. s1 = '1MichaelJessica' >>> strlist = re.findall(r'(\w{1,})',s1) >>> strlist ['1', 'Michael', 'Jessica'] >>> strlist = re.findall(r'(\d+)(\w+)\(\w+)', s1) >>> strlist [('1', 'Michael', 'Jessica')] -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanpierreda at gmail.com Tue Mar 5 02:47:12 2013 From: jeanpierreda at gmail.com (Devin Jeanpierre) Date: Mon, 4 Mar 2013 20:47:12 -0500 Subject: [Tutor] Fwd: findall() returns tuples or string? In-Reply-To: References: Message-ID: On Mon, Mar 4, 2013 at 8:22 PM, Charles Leviton wrote: > I have some confusion regarding when findall returns a list of strings and > when it returns a list of tuples. > Would appreciate an explanation. If there are no groups, it returns a list of strings, where the strings are the whole match. If there is one group, it returns a list of strings, where the strings are the content of the group. Otherwise, it returns a list of tuples of strings, where the tuples contain the group contents (the same as if an individual match had its groups() method called). If you want consistency, use finditer instead of findall. http://docs.python.org/2/library/re.html#re.finditer -- Devin From alan.gauld at btinternet.com Tue Mar 5 03:13:40 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 05 Mar 2013 02:13:40 +0000 Subject: [Tutor] Fwd: findall() returns tuples or string? In-Reply-To: References: Message-ID: On 05/03/13 01:22, Charles Leviton wrote: > I have some confusion regarding when findall returns a list of strings > and when it returns a list of tuples. > Would appreciate an explanation. re is not my strongest suite but I'll have a go. My understanding of how findall works is that it returns a list of matches. If groups are used in the pattern each match will be a tuple containing the groups (if there is only one group in the pattern it will be a tuple of only one element) > s1 = '1MichaelJessica' > >>> re.findall(r'(\w{1,})',s1) > ['1', 'Michael', 'Jessica'] > >>> re.findall(r'(\d+)(\w+)\(\w+)', s1) > >>> strlist > [('1', 'Michael', 'Jessica')] In the first example you define a single group so you get the three separate matches in a list. ie 3 separate entries each of a single value. In the second you define 3 groups within your pattern and re locates only one occurrence of the pattern so returns a single entry which is a tuple of the 3 group items. Consider now a slightly forced example: >>> re.findall(r'(\w)(\w)',s1) [('M', 'i'), ('J', 'e')] >>> This uses two groups so we get back a tuple of two elements. And because the pattern matches twice we get two tuples. I'm sure somebody else will give a more lucid explanation... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From losermeloser at yahoo.com Tue Mar 5 03:49:09 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Mon, 4 Mar 2013 18:49:09 -0800 (PST) Subject: [Tutor] some web and python version questions In-Reply-To: References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> <5134D9F7.7010407@davea.name> <1362427096.33527.YahooMailNeo@web121102.mail.ne1.yahoo.com> Message-ID: <1362451749.73424.YahooMailNeo@web121104.mail.ne1.yahoo.com> I don't know how that's working. There are no executables or batch files with those names in the default installations. It's always "python.exe". Plus the default install options don't muck with the PATH environment variable. Did you rename (or NTFS symlink) the executables and add the install directories to your PATH? 3.3 installs py.exe to the Windows directory, which you can use like this: ? ? py -3.3 myscript.py ? ? py -3.0 myscript.py Or add a shebang to the first line of the script such as #!/usr/bin/env python3.0 Then you can simply run myscipt.py. The 3.3 installer associates the extension with py.exe, which parses the shebang line. ? ? ---------- no sorry i made a mistake it didnt work. i cd into the?particular python version directory that i named python3.0 and python3.3. sorry that was my mistake. Once i was in the correct directory i used the command: python filename.py in cmd and the correct version was opened. Since installing 3.3 my .py files have lost their python icon,?like when there is no?default?program to open it, looks like this: ? http://www.google.co.uk/imgres?imgurl=http://filext.com/images/icon_unknownassociation.gif&imgrefurl=http://filext.com/faq/remove_filext_get_cknow.php&h=48&w=39&sz=2&tbnid=ARzowXfVVRzKFM:&tbnh=48&tbnw=39&zoom=1&usg=__aeaxTXEytmXEPgmJ-92PpGRrYho=&docid=YuYbltBMCbahiM&sa=X&ei=21s1UbLjE8i0PLXqgXg&ved=0CFMQ9QEwAw&dur=2179 ? ?im not sure what to do because on double click they still open and work fine, so the right program is still opening them. ? ? Also can i ask, only if you have tried both cherrypy and bottle. I know which i choose doesnt matter, and i will probably randomly select one, but i would like to hear an opinion of someone who has used the 2. since i will eventually go to django, the lighter one out of the two is the one i would favour.?? -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Tue Mar 5 04:06:41 2013 From: davea at davea.name (Dave Angel) Date: Mon, 04 Mar 2013 22:06:41 -0500 Subject: [Tutor] some web and python version questions In-Reply-To: <1362451749.73424.YahooMailNeo@web121104.mail.ne1.yahoo.com> References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> <5134D9F7.7010407@davea.name> <1362427096.33527.YahooMailNeo@web121102.mail.ne1.yahoo.com> <1362451749.73424.YahooMailNeo@web121104.mail.ne1.yahoo.com> Message-ID: <51356141.30900@davea.name> (Please get the quoting right in your messages. Either you've got a brain-dead mail program, or you're trying to bypass it's methods. On your last message you attributed Eryksun's comments as though they were your own.) On 03/04/2013 09:49 PM, Lolo Lolo wrote: > no sorry i made a mistake it didnt work. > > im not sure what to do because on double click they still open and work fine, so the right program is still opening them. > No idea what you mean by work fine. You mean that it runs 3.0 for some scripts when you right click on the script, and 3.3 on other scripts when you right click on them? In that case, you must have the py.exe associated with the .py directory, and you must have shebang lines in your scripts. So you should be able to simply name the script on the command line: Instead of python myscript.py Just say myscript.py -- DaveA From losermeloser at yahoo.com Tue Mar 5 04:54:27 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Mon, 4 Mar 2013 19:54:27 -0800 (PST) Subject: [Tutor] some web and python version questions In-Reply-To: <51356141.30900@davea.name> References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> <5134D9F7.7010407@davea.name> <1362427096.33527.YahooMailNeo@web121102.mail.ne1.yahoo.com> <1362451749.73424.YahooMailNeo@web121104.mail.ne1.yahoo.com> <51356141.30900@davea.name> Message-ID: <1362455667.73075.YahooMailNeo@web121105.mail.ne1.yahoo.com> > (Please get the quoting right in your messages.? Either you've got a brain-dead mail program, or you're trying to bypass it's methods.? > On your last message you attributed Eryksun's comments as though they were your own.) ? sorry this is yahoo's fault, i have to manually insert the ">" in every message i reply to. i forgot to do it in my last message. > No idea what you mean by work fine.? You mean that it runs 3.0 for some scripts when you right click on the script, and 3.3 on other? > scripts when you right click on them?? In that case, you must have the py.exe associated with the .py directory, and you must have > shebang lines in your scripts.? ? no if i double click the .py file, Python 3.3 opens all of my python 3 files. A lot of 3.0 files won't run but that's okay. Now on my command line if i enter?the correct version's directory,?and use: python myfile.py then the correct version's .exe opens the file. When i said "it works fine", i was just suprised why my files lost their python icon but are still opened by python when i double click them -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Tue Mar 5 05:57:02 2013 From: eryksun at gmail.com (eryksun) Date: Mon, 4 Mar 2013 23:57:02 -0500 Subject: [Tutor] some web and python version questions In-Reply-To: <1362455667.73075.YahooMailNeo@web121105.mail.ne1.yahoo.com> References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> <5134D9F7.7010407@davea.name> <1362427096.33527.YahooMailNeo@web121102.mail.ne1.yahoo.com> <1362451749.73424.YahooMailNeo@web121104.mail.ne1.yahoo.com> <51356141.30900@davea.name> <1362455667.73075.YahooMailNeo@web121105.mail.ne1.yahoo.com> Message-ID: On Mon, Mar 4, 2013 at 10:54 PM, Lolo Lolo wrote: > no if i double click the .py file, Python 3.3 opens all of my python 3 > files. A lot of 3.0 files won't run but that's okay. Now on my command line > if i enter the correct version's directory, and use: python myfile.py then > the correct version's .exe opens the file. When i said "it works fine", i > was just suprised why my files lost their python icon but are still opened > by python when i double click them Installing 3.3 associated .py files with %windir%\py.exe, but it seems the icon cache wasn't refreshed. You can trigger a refresh by setting any default in the "Default Programs" control panel applet. If that fails, you can manually delete the cache from the cmd shell: del /a %localappdata%\IconCache.db It will be rebuilt at your next login. From davea at davea.name Tue Mar 5 06:14:47 2013 From: davea at davea.name (Dave Angel) Date: Tue, 05 Mar 2013 00:14:47 -0500 Subject: [Tutor] some web and python version questions In-Reply-To: References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> <5134D9F7.7010407@davea.name> <1362427096.33527.YahooMailNeo@web121102.mail.ne1.yahoo.com> <1362451749.73424.YahooMailNeo@web121104.mail.ne1.yahoo.com> <51356141.30900@davea.name> <1362455667.73075.YahooMailNeo@web121105.mail.ne1.yahoo.com> Message-ID: <51357F47.3080606@davea.name> On 03/04/2013 11:57 PM, eryksun wrote: > On Mon, Mar 4, 2013 at 10:54 PM, Lolo Lolo wrote: >> no if i double click the .py file, Python 3.3 opens all of my python 3 >> files. A lot of 3.0 files won't run but that's okay. Now on my command line >> if i enter the correct version's directory, and use: python myfile.py then >> the correct version's .exe opens the file. When i said "it works fine", i >> was just suprised why my files lost their python icon but are still opened >> by python when i double click them > > Installing 3.3 associated .py files with %windir%\py.exe, Lolo - Assuming eryksun is correct, all you need is to add shebang lines to the files that you want to run 3.0 The line must be the very first line in the file, and it consists of the characters "#!" followed by the path to the executable. Try: #!c:\python3.3\python.exe (or wherever the installation directory actually is) or what Eryksun suggested: #!/usr/bin/env python3.0 I can't tell which would be right, since I don't run Windows. Any more. -- DaveA From eryksun at gmail.com Tue Mar 5 06:25:54 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 5 Mar 2013 00:25:54 -0500 Subject: [Tutor] some web and python version questions In-Reply-To: <51357F47.3080606@davea.name> References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> <5134D9F7.7010407@davea.name> <1362427096.33527.YahooMailNeo@web121102.mail.ne1.yahoo.com> <1362451749.73424.YahooMailNeo@web121104.mail.ne1.yahoo.com> <51356141.30900@davea.name> <1362455667.73075.YahooMailNeo@web121105.mail.ne1.yahoo.com> <51357F47.3080606@davea.name> Message-ID: On Tue, Mar 5, 2013 at 12:14 AM, Dave Angel wrote: > > #!c:\python3.3\python.exe (or wherever the installation directory > actually is) > > or what Eryksun suggested: > > #!/usr/bin/env python3.0 > > I can't tell which would be right, since I don't run Windows. Any more. Both forms work. The /usr paths are virtual, of course. You can also add custom commands to %localappdata%\py.ini in the [commands] section (e.g. to use PyPy or Jython). From losermeloser at yahoo.com Tue Mar 5 08:43:39 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Mon, 4 Mar 2013 23:43:39 -0800 (PST) Subject: [Tutor] some web and python version questions In-Reply-To: References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> <5134D9F7.7010407@davea.name> <1362427096.33527.YahooMailNeo@web121102.mail.ne1.yahoo.com> <1362451749.73424.YahooMailNeo@web121104.mail.ne1.yahoo.com> <51356141.30900@davea.name> <1362455667.73075.YahooMailNeo@web121105.mail.ne1.yahoo.com> Message-ID: <1362469419.63445.YahooMailNeo@web121106.mail.ne1.yahoo.com> >Installing 3.3 associated .py files with %windir%\py.exe, but it seems >the icon cache wasn't refreshed. You can trigger a refresh by setting >any default in the "Default Programs" control panel applet. If that >fails, you can manually delete the cache from the cmd shell: >? ? del /a %localappdata%\IconCache.db >It will be rebuilt at your next login. that last command returns "The system cannot find the path specified." Any ideas which directory i should do that in? -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Tue Mar 5 08:59:27 2013 From: davea at davea.name (Dave Angel) Date: Tue, 05 Mar 2013 02:59:27 -0500 Subject: [Tutor] some web and python version questions In-Reply-To: <1362469419.63445.YahooMailNeo@web121106.mail.ne1.yahoo.com> References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> <5134D9F7.7010407@davea.name> <1362427096.33527.YahooMailNeo@web121102.mail.ne1.yahoo.com> <1362451749.73424.YahooMailNeo@web121104.mail.ne1.yahoo.com> <51356141.30900@davea.name> <1362455667.73075.YahooMailNeo@web121105.mail.ne1.yahoo.com> <1362469419.63445.YahooMailNeo@web121106.mail.ne1.yahoo.com> Message-ID: <5135A5DF.3010703@davea.name> On 03/05/2013 02:43 AM, Lolo Lolo wrote: > > >> Installing 3.3 associated .py files with %windir%\py.exe, but it seems >> the icon cache wasn't refreshed. You can trigger a refresh by setting >> any default in the "Default Programs" control panel applet. If that >> fails, you can manually delete the cache from the cmd shell: > >> del /a %localappdata%\IconCache.db > >> It will be rebuilt at your next login. > > that last command returns "The system cannot find the path specified." Any ideas which directory i should do that in? > > Do you have any familiarity with Windows commandline? Can you look at environment variables, and do you know why I would ask that? Can you search your hard disk for a file? dir /s c:\IconCache.db DIR is the "directory" command. /s is the switch that says search all subdirectories. C:\ is the starting place for your search, and IconCache.db is the file you're looking for. -- DaveA From eryksun at gmail.com Tue Mar 5 09:03:33 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 5 Mar 2013 03:03:33 -0500 Subject: [Tutor] some web and python version questions In-Reply-To: <1362469419.63445.YahooMailNeo@web121106.mail.ne1.yahoo.com> References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> <5134D9F7.7010407@davea.name> <1362427096.33527.YahooMailNeo@web121102.mail.ne1.yahoo.com> <1362451749.73424.YahooMailNeo@web121104.mail.ne1.yahoo.com> <51356141.30900@davea.name> <1362455667.73075.YahooMailNeo@web121105.mail.ne1.yahoo.com> <1362469419.63445.YahooMailNeo@web121106.mail.ne1.yahoo.com> Message-ID: On Tue, Mar 5, 2013 at 2:43 AM, Lolo Lolo wrote: >> del /a %localappdata%\IconCache.db > >>It will be rebuilt at your next login. > > that last command returns "The system cannot find the path specified." Any > ideas which directory i should do that in? Sorry, I haven't used XP (NT 5) in a long time. The environment variable %localappdata% is available in Vista and Windows 7-8 (NT 6). Instead you can use %userprofile%\Local Settings\Application Data\IconCache.db. Here are some step by step instructions: http://www.trishtech.com/winxp/rebuild_icon_cache_in_windows_xp.php From losermeloser at yahoo.com Tue Mar 5 10:04:29 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Tue, 5 Mar 2013 01:04:29 -0800 (PST) Subject: [Tutor] some web and python version questions In-Reply-To: References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> <5134D9F7.7010407@davea.name> <1362427096.33527.YahooMailNeo@web121102.mail.ne1.yahoo.com> <1362451749.73424.YahooMailNeo@web121104.mail.ne1.yahoo.com> <51356141.30900@davea.name> <1362455667.73075.YahooMailNeo@web121105.mail.ne1.yahoo.com> <1362469419.63445.YahooMailNeo@web121106.mail.ne1.yahoo.com> Message-ID: <1362474269.49130.YahooMailNeo@web121104.mail.ne1.yahoo.com> ? due to the last 2 posts i was able to locate and delete the Iconcache.db through cmd.?But after restarting, even though i have the refreshed cache, the icons are still not displaying properly. Will that website http://www.trishtech.com/winxp/rebuild_icon_cache_in_windows_xp.php?provide an alternative solution or are the end results the same? I guess i can live with it, aslong as my scripts still run i dont mind.?I do really appreciate the help you 2 are?giving me. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Tue Mar 5 11:50:46 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 5 Mar 2013 05:50:46 -0500 Subject: [Tutor] some web and python version questions In-Reply-To: <1362474269.49130.YahooMailNeo@web121104.mail.ne1.yahoo.com> References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> <5134D9F7.7010407@davea.name> <1362427096.33527.YahooMailNeo@web121102.mail.ne1.yahoo.com> <1362451749.73424.YahooMailNeo@web121104.mail.ne1.yahoo.com> <51356141.30900@davea.name> <1362455667.73075.YahooMailNeo@web121105.mail.ne1.yahoo.com> <1362469419.63445.YahooMailNeo@web121106.mail.ne1.yahoo.com> <1362474269.49130.YahooMailNeo@web121104.mail.ne1.yahoo.com> Message-ID: On Tue, Mar 5, 2013 at 4:04 AM, Lolo Lolo wrote: > due to the last 2 posts i was able to locate and delete the Iconcache.db > through cmd. But after restarting, even though i have the refreshed cache, > the icons are still not displaying properly. Check the output of the following command: reg query HKLM\Software\Classes\Python.File\DefaultIcon For me the value is "C:\Python33\DLLs\py.ico". From losermeloser at yahoo.com Tue Mar 5 15:03:08 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Tue, 5 Mar 2013 06:03:08 -0800 (PST) Subject: [Tutor] some web and python version questions In-Reply-To: References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> <5134D9F7.7010407@davea.name> <1362427096.33527.YahooMailNeo@web121102.mail.ne1.yahoo.com> <1362451749.73424.YahooMailNeo@web121104.mail.ne1.yahoo.com> <51356141.30900@davea.name> <1362455667.73075.YahooMailNeo@web121105.mail.ne1.yahoo.com> <1362469419.63445.YahooMailNeo@web121106.mail.ne1.yahoo.com> <1362474269.49130.YahooMailNeo@web121104.mail.ne1.yahoo.com> Message-ID: <1362492188.69963.YahooMailNeo@web121101.mail.ne1.yahoo.com> >Check the output of the following command: >??? reg query HKLM\Software\Classes\Python.File\DefaultIcon >For me the value is "C:\Python33\DLLs\py.ico". ? i get:? 'reg' is not recognized as an internal or external command, operable program or batch file. -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Tue Mar 5 15:54:38 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 5 Mar 2013 09:54:38 -0500 Subject: [Tutor] some web and python version questions In-Reply-To: <1362492188.69963.YahooMailNeo@web121101.mail.ne1.yahoo.com> References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> <5134D9F7.7010407@davea.name> <1362427096.33527.YahooMailNeo@web121102.mail.ne1.yahoo.com> <1362451749.73424.YahooMailNeo@web121104.mail.ne1.yahoo.com> <51356141.30900@davea.name> <1362455667.73075.YahooMailNeo@web121105.mail.ne1.yahoo.com> <1362469419.63445.YahooMailNeo@web121106.mail.ne1.yahoo.com> <1362474269.49130.YahooMailNeo@web121104.mail.ne1.yahoo.com> <1362492188.69963.YahooMailNeo@web121101.mail.ne1.yahoo.com> Message-ID: On Tue, Mar 5, 2013 at 9:03 AM, Lolo Lolo wrote: >>Check the output of the following command: > >> reg query HKLM\Software\Classes\Python.File\DefaultIcon > >>For me the value is "C:\Python33\DLLs\py.ico". > > i get: 'reg' is not recognized as an internal or external command, operable > program or batch file. System32 should be on the PATH, and reg.exe should be available in XP. C'est la vie. Try "%windir%\System32\reg.exe" instead of "reg". No rush. It's just an icon. By any chance are you using a 64-bit Windows XP? WoW64 redirection for 32-bit processes might be an issue. e.g., %windir%\System32 -> %windir%\SysWoW64. 32-bit reg.exe run from a 32-bit cmd shell would nominally operate on HKLM\Software\, but really access HKLM\Software\Wow6432Node\. From losermeloser at yahoo.com Tue Mar 5 18:16:49 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Tue, 5 Mar 2013 09:16:49 -0800 (PST) Subject: [Tutor] some web and python version questions In-Reply-To: References: <1362414615.41814.YahooMailNeo@web121106.mail.ne1.yahoo.com> <5134D9F7.7010407@davea.name> <1362427096.33527.YahooMailNeo@web121102.mail.ne1.yahoo.com> <1362451749.73424.YahooMailNeo@web121104.mail.ne1.yahoo.com> <51356141.30900@davea.name> <1362455667.73075.YahooMailNeo@web121105.mail.ne1.yahoo.com> <1362469419.63445.YahooMailNeo@web121106.mail.ne1.yahoo.com> <1362474269.49130.YahooMailNeo@web121104.mail.ne1.yahoo.com> <1362492188.69963.YahooMailNeo@web121101.mail.ne1.yahoo.com> Message-ID: <1362503809.81359.YahooMailNeo@web121102.mail.ne1.yahoo.com> >System32 should be on the PATH, and reg.exe should be available in XP. >C'est la vie. Try "%windir%\System32\reg.exe" instead of "reg". No >rush. It's just an icon. sorry eryksun its my fault i havent been clear... im actually using windows vista not xp. i mixed your new command with the old but did it directly in the system32 directory. using: ? C:\Windows\System32>%windir%\System32\reg.exe query HKLM\Software\Classes\Python.File\DefaultIcon ? i got this returned: ? HKEY_LOCAL_MACHINE\Software\Classes\Python.File\DefaultIcon ??? (Default)??? REG_SZ??? D:\Data\Program Files Data\Python33\DLLs\py.ico -------------- next part -------------- An HTML attachment was scrubbed... URL: From losermeloser at yahoo.com Wed Mar 6 19:50:46 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Wed, 6 Mar 2013 10:50:46 -0800 (PST) Subject: [Tutor] mysqlite Message-ID: <1362595846.26704.YahooMailNeo@web121103.mail.ne1.yahoo.com> im working through alan's sql tutorial. i have a few questions from there but 1st i wanted to try out an example in Core python's sql example. >>> import sqlite3 >>> cxn = sqlite3.connect('sqlite_test/test') >>> cur = cxn.cursor() after this i created a table called users and inserted some data. then i did: >>> cur.execute('SELECT * from users') >>> for user in cur.fetchall(): ??????????? print(user) i got the results of all data i gave the table. then did >>> cur.close() >>> cxn.commit() >>> cxn.close() i then closed this?interactive IDLE session. i reopened another?session and simply did >>> import sqlite3 >>> cxn = sqlite3.connect('sqlite_test/test') >>> cur = cxn.cursor() >>> for user in cur.fetchall(): ??????????? print(user) >>> but this time no data was printed back to me, even though the database file 'test' already existed from the previous session. Why did this happen, cant i just connect and my data is still intact? or do i have to always re enter data from the previously saved session? My questions about http://www.alan-g.me.uk/tutor/tutdbms.htm?is to open a database it uses the command line directly and doesnt creat cursor() or connect() objects e.g. ? E:\PROJECTS\SQL> sqlite3 employee.db sqlite> create table Employee ?? ...> (EmpID,Name,HireDate,Grade,ManagerID); sqlite> insert into Employee (EmpID, Name, HireDate, Grade, ManagerID) ?? ...> values ('1020304','John Brown','20030623','Foreman','1020311'); ? i tried this in my command line but got : python.exe: can't open file 'sqlite': [Errno 2] No ?such file or directory ? i tried creating the a folder called test and doing:? test employee.db but no test.db was created. ? my main questions?are it possible to use the command line without cursor() and connect() in python 3 or is it only for python 2. is it better from the command line or in a .py file. And also?my previous question i had about having to re enter previously stored data????????? From fomcl at yahoo.com Wed Mar 6 21:55:17 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 6 Mar 2013 12:55:17 -0800 (PST) Subject: [Tutor] Fwd: findall() returns tuples or string? In-Reply-To: References: Message-ID: <1362603317.56563.YahooMailNeo@web163801.mail.gq1.yahoo.com> >> I have some confusion regarding when findall returns a list of strings >> and when it returns a list of tuples. >> Would appreciate an explanation. > >re is not my strongest suite but I'll have a go. > >My understanding of how findall works is that it returns a list of matches. If groups are used in the pattern each match will be a tuple containing the groups (if there is only one group in the pattern it will be a tuple of only one element) One nice trick/feature that I recently discovered is that it's possible to "turn off" groups by using "?:" >>> import re >>> re.findall("(python(?:ic)?)", "python")? ['python'] >>> re.search("(python(?:ic)?)", "python").group(2) Traceback (most recent call last): ? File "", line 1, in ??? re.search("(python(?:ic)?)", "python").group(2) IndexError: no such group >>> re.findall("(python(ic)?)", "python") [('python', '')] >>> re.findall("(python(ic)?)", "pythonic") [('pythonic', 'ic')] Thought it'd be nice to share this. ;-) Regards, Albert-Jan From joel.goldstick at gmail.com Wed Mar 6 22:47:08 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 6 Mar 2013 16:47:08 -0500 Subject: [Tutor] mysqlite In-Reply-To: <1362595846.26704.YahooMailNeo@web121103.mail.ne1.yahoo.com> References: <1362595846.26704.YahooMailNeo@web121103.mail.ne1.yahoo.com> Message-ID: On Wed, Mar 6, 2013 at 1:50 PM, Lolo Lolo wrote: > im working through alan's sql tutorial. i have a few questions from there > but 1st i wanted to try out an example in Core python's sql example. > > >>> import sqlite3 > >>> cxn = sqlite3.connect('sqlite_test/test') > >>> cur = cxn.cursor() > > after this i created a table called users and inserted some data. then i > did: > > >>> cur.execute('SELECT * from users') > >>> for user in cur.fetchall(): > print(user) > > i got the results of all data i gave the table. then did > > >>> cur.close() > >>> cxn.commit() > >>> cxn.close() > > i then closed this interactive IDLE session. i reopened another session > and simply did > > >>> import sqlite3 > >>> cxn = sqlite3.connect('sqlite_test/test') > >>> cur = cxn.cursor() > >>> for user in cur.fetchall(): > print(user) > > >>> > but this time no data was printed back to me, even though the database > file 'test' already existed from the previous session. Why did this happen, > cant i just connect and my data is still intact? or do i have to always re > enter data from the previously saved session? > Are you sure you are in same directory each time? > > My questions about http://www.alan-g.me.uk/tutor/tutdbms.htm is to open a > database it uses the command line directly and doesnt creat cursor() or > connect() objects e.g. > > E:\PROJECTS\SQL> sqlite3 employee.db > sqlite> create table Employee > ...> (EmpID,Name,HireDate,Grade,ManagerID); > sqlite> insert into Employee (EmpID, Name, HireDate, Grade, ManagerID) > ...> values ('1020304','John Brown','20030623','Foreman','1020311'); > > i tried this in my command line but got : > python.exe: can't open file 'sqlite': [Errno 2] No > such file or directory > > i tried creating the a folder called test and doing: test employee.db > but no test.db was created. > > my main questions are it possible to use the command line without cursor() > and connect() in python 3 or is it only for python 2. is it better from the > command line or in a .py file. And also my previous question i had about > having to re enter previously stored data > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From paradox at pobox.com Wed Mar 6 23:16:01 2013 From: paradox at pobox.com (Paradox) Date: Thu, 07 Mar 2013 06:16:01 +0800 Subject: [Tutor] mysqlite :p: In-Reply-To: <1362595846.26704.YahooMailNeo@web121103.mail.ne1.yahoo.com> References: <1362595846.26704.YahooMailNeo@web121103.mail.ne1.yahoo.com> Message-ID: <5137C021.9010807@pobox.com> On 03/07/2013 02:50 AM, Lolo Lolo wrote: > im working through alan's sql tutorial. i have a few questions from there but 1st i wanted to try out an example in Core python's sql example. > >>>> import sqlite3 >>>> cxn = sqlite3.connect('sqlite_test/test') >>>> cur = cxn.cursor() > after this i created a table called users and inserted some data. then i did: > >>>> cur.execute('SELECT * from users') >>>> for user in cur.fetchall(): > print(user) > > i got the results of all data i gave the table. then did > >>>> cur.close() >>>> cxn.commit() >>>> cxn.close() > i then closed this interactive IDLE session. i reopened another session and simply did > >>>> import sqlite3 >>>> cxn = sqlite3.connect('sqlite_test/test') >>>> cur = cxn.cursor() >>>> for user in cur.fetchall(): > print(user) I normally use sqlalchemy for manipulating sqlite databases but I think you need to do a select command or something before trying to do a fetchall method. It looks like you are doing a fetchall on a cursor object rather than a query object. > but this time no data was printed back to me, even though the database file 'test' already existed from the previous session. Why did this happen, cant i just connect and my data is still intact? or do i have to always re enter data from the previously saved session? > > My questions about http://www.alan-g.me.uk/tutor/tutdbms.htm is to open a database it uses the command line directly and doesnt creat cursor() or connect() objects e.g. > > E:\PROJECTS\SQL> sqlite3 employee.db > sqlite> create table Employee > ...> (EmpID,Name,HireDate,Grade,ManagerID); > sqlite> insert into Employee (EmpID, Name, HireDate, Grade, ManagerID) > ...> values ('1020304','John Brown','20030623','Foreman','1020311'); > > i tried this in my command line but got : > python.exe: can't open file 'sqlite': [Errno 2] No > such file or directory > Are you trying to do this from the command line or from within python? It looks like python is complaining but if you are using the regular commandline interface to sqlite3, python shouldn't be invoked at all and thus never complain. Incidentally (and I haven't gone through Allan's tutorial on sql) I love the -column and -headers commands when invoking sqlite from the command line. Put them like this: sqlite3 -column -header employee.db Makes the data much easier to read when you do a select command (at least for me). > i tried creating the a folder called test and doing: test employee.db > but no test.db was created. > > my main questions are it possible to use the command line without cursor() and connect() in python 3 or is it only for python 2. is it better from the command line or in a .py file. And also my previous question i had about having to re enter previously stored data > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > . > thomas From jf_byrnes at comcast.net Wed Mar 6 23:29:48 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Wed, 06 Mar 2013 16:29:48 -0600 Subject: [Tutor] mysqlite In-Reply-To: References: <1362595846.26704.YahooMailNeo@web121103.mail.ne1.yahoo.com> Message-ID: On 03/06/2013 03:47 PM, Joel Goldstick wrote: > On Wed, Mar 6, 2013 at 1:50 PM, Lolo Lolo wrote: > >> im working through alan's sql tutorial. i have a few questions from there >> but 1st i wanted to try out an example in Core python's sql example. >> >>>>> import sqlite3 >>>>> cxn = sqlite3.connect('sqlite_test/test') >>>>> cur = cxn.cursor() >> >> after this i created a table called users and inserted some data. then i >> did: >> >>>>> cur.execute('SELECT * from users') >>>>> for user in cur.fetchall(): >> print(user) >> >> i got the results of all data i gave the table. then did >> >>>>> cur.close() >>>>> cxn.commit() >>>>> cxn.close() I've only used sqlite and Python together a couple of times but I don't remember seeing that sequence of commands used. Don't use cur.close() and see if that helps. Regards, Jim >> i then closed this interactive IDLE session. i reopened another session >> and simply did >> >>>>> import sqlite3 >>>>> cxn = sqlite3.connect('sqlite_test/test') >>>>> cur = cxn.cursor() >>>>> for user in cur.fetchall(): >> print(user) >> >>>>> >> but this time no data was printed back to me, even though the database >> file 'test' already existed from the previous session. Why did this happen, >> cant i just connect and my data is still intact? or do i have to always re >> enter data from the previously saved session? >> > > Are you sure you are in same directory each time? > >> >> My questions about http://www.alan-g.me.uk/tutor/tutdbms.htm is to open a >> database it uses the command line directly and doesnt creat cursor() or >> connect() objects e.g. >> >> E:\PROJECTS\SQL> sqlite3 employee.db >> sqlite> create table Employee >> ...> (EmpID,Name,HireDate,Grade,ManagerID); >> sqlite> insert into Employee (EmpID, Name, HireDate, Grade, ManagerID) >> ...> values ('1020304','John Brown','20030623','Foreman','1020311'); >> >> i tried this in my command line but got : >> python.exe: can't open file 'sqlite': [Errno 2] No >> such file or directory >> >> i tried creating the a folder called test and doing: test employee.db >> but no test.db was created. >> >> my main questions are it possible to use the command line without cursor() >> and connect() in python 3 or is it only for python 2. is it better from the >> command line or in a .py file. And also my previous question i had about >> having to re enter previously stored data >> _______________________________________________ >> 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 bgailer at gmail.com Thu Mar 7 00:02:53 2013 From: bgailer at gmail.com (bob gailer) Date: Wed, 06 Mar 2013 18:02:53 -0500 Subject: [Tutor] mysqlite In-Reply-To: <1362595846.26704.YahooMailNeo@web121103.mail.ne1.yahoo.com> References: <1362595846.26704.YahooMailNeo@web121103.mail.ne1.yahoo.com> Message-ID: <5137CB1D.1080302@gmail.com> On 3/6/2013 1:50 PM, Lolo Lolo wrote: > im working through alan's sql tutorial. i have a few questions from there but 1st i wanted to try out an example in Core python's sql example. > >>>> import sqlite3 >>>> cxn = sqlite3.connect('sqlite_test/test') >>>> cur = cxn.cursor() > after this i created a table called users and inserted some data. then i did: > >>>> cur.execute('SELECT * from users') >>>> for user in cur.fetchall(): > print(user) > > i got the results of all data i gave the table. then did > >>>> cur.close() >>>> cxn.commit() >>>> cxn.close() > i then closed this interactive IDLE session. i reopened another session and simply did > >>>> import sqlite3 >>>> cxn = sqlite3.connect('sqlite_test/test') >>>> cur = cxn.cursor() You are missing cur.execute('SELECT * from users') >>>> for user in cur.fetchall(): > print(user) > -- Bob Gailer 919-636-4239 Chapel Hill NC From losermeloser at yahoo.com Thu Mar 7 00:25:15 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Wed, 6 Mar 2013 15:25:15 -0800 (PST) Subject: [Tutor] mysqlite In-Reply-To: <5137CB1D.1080302@gmail.com> References: <1362595846.26704.YahooMailNeo@web121103.mail.ne1.yahoo.com> <5137CB1D.1080302@gmail.com> Message-ID: <1362612315.5561.YahooMailNeo@web121103.mail.ne1.yahoo.com> > You are missing cur.execute('SELECT * from users') thanks:) this has fixed the 1st issue. ? ?guys i still cant use the command line. but i guess i dont really mind as i can just make a .py file... i am having a lot of fun reading through alan's tutorial, everything is becoming very clear but can someone please explain this to me. ? update Employee set ManagerID = (Select EmpID ???????????????? from Employee ?? where Name = 'John Brown') where Name = 'Fred Smith' OR ????? Name = 'Anne Jones'; ? ? this is saying set the managerID of 'Fred Smith' or 'Jane Brown'?to the ID returned in the nested select statement? ? and this: ? drop table author; create table author ( ID Integer PRIMARY KEY, Name String NOT NULL ); drop table book; create table book ( ID Integer PRIMARY KEY, Title String NOT NULL ); drop table book_author; create table book_author ( bookID Integer NOT NULL, authorID Integer NOT NULL ); ? sqlite> SELECT title from book, book_author ...> where book_author.bookID = book.ID ...> and book_author.authorID = (select ID from author ...> where name = "Jane Austin"); ? maybe its simple but because its more complex im finding it hard to read. we want a title from book, which is the field that will be returned, but why is book_author also in the select statement when it isnt being returned? or are we actually returning every single field from book author? ? so if the author.bookID is equal to book.ID, also check that this ID from author matches the authorID from book_author.authorID ? after comprehending this im lost in my thoughts. can someone tell me how these are linked. so the whole output is really dependent on the answer from the 2nd condition after the and?: ...> and book_author.authorID = (select ID from author where name = "Jane Austin"); From alan.gauld at btinternet.com Thu Mar 7 00:44:24 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 06 Mar 2013 23:44:24 +0000 Subject: [Tutor] mysqlite In-Reply-To: <1362595846.26704.YahooMailNeo@web121103.mail.ne1.yahoo.com> References: <1362595846.26704.YahooMailNeo@web121103.mail.ne1.yahoo.com> Message-ID: On 06/03/13 18:50, Lolo Lolo wrote: > i then closed this interactive IDLE session. i reopened another session and simply did > >>>> import sqlite3 >>>> cxn = sqlite3.connect('sqlite_test/test') This gets you a connection to the data base >>>> cur = cxn.cursor() and this sets up a storage area for any results >>>> for user in cur.fetchall(): > print(user) But at this point the cursor is empty, you haven't read anything from the database. You need to execute some kind of SELECT statement to populate the cursor from the database. > My questions about http://www.alan-g.me.uk/tutor/tutdbms.htm is to > open a database it uses the command line directly > and doesnt creat cursor() or connect() objects e.g. Thats becsause the connection and cursor mechanism is how Python interacts with SQLite. When you use the SQLite prompt you don't need them SQLite connects itself automatically. AS you read further in the tutorial page you'll see the section where we jump from direct SQL command line into using Python and there you will see connect/cursor. > E:\PROJECTS\SQL> sqlite3 employee.db > sqlite> create table Employee > ...> (EmpID,Name,HireDate,Grade,ManagerID); > sqlite> insert into Employee (EmpID, Name, HireDate, Grade, ManagerID) > ...> values ('1020304','John Brown','20030623','Foreman','1020311'); > > i tried this in my command line but got : > python.exe: can't open file 'sqlite': [Errno 2] No > such file or directory I'm not running it from Python I'm running it from the OS command line. You need to open a CMD shell window and cd to your SQL database folder (E:\PROJECTS\SQL in the example above) and then run sqlite3. > i tried creating the a folder called test and doing: test employee.db > but no test.db was created. You need to change into the test directory. Then run sqlite3 employee.db and when you are done a new employee.db file should exist. > my main questions are it possible to use the command line > without cursor() and connect() in python 3 No only from the sqlite command line. The great thing about command lines is there are so many to choose from: The OS SQLite Python and then from within Python you can use: the debugger the help system and, if you are really perverse, you can even use Tcl from within Tkinter!! such choice! ...such confusion... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Mar 7 01:05:56 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 07 Mar 2013 00:05:56 +0000 Subject: [Tutor] mysqlite In-Reply-To: <1362612315.5561.YahooMailNeo@web121103.mail.ne1.yahoo.com> References: <1362595846.26704.YahooMailNeo@web121103.mail.ne1.yahoo.com> <5137CB1D.1080302@gmail.com> <1362612315.5561.YahooMailNeo@web121103.mail.ne1.yahoo.com> Message-ID: On 06/03/13 23:25, Lolo Lolo wrote: > can someone please explain this to me. > > update Employee > set ManagerID = (Select EmpID > from Employee > where Name = 'John Brown') > where Name = 'Fred Smith' OR > Name = 'Anne Jones'; > > > this is saying set the managerID of 'Fred Smith' or > 'Jane Brown' to the ID returned in the nested select statement? Almost. Its saying set the Manager of both Fred and Anne to John. The OR selects both entries and then applies the update to them. We can logically split it like this (so you can test it at the command prompt :-): SELECT * FROM Employee where Name = 'Fred Smith' OR Name = 'Anne Jones'; That will get you two rows. Select EmpID from Employee where Name = 'John Brown' That will get you one ID, lets call it JohnsID and putting them together: update Employee set ManagerID = JohnsID where Name = 'Fred Smith' OR Name = 'Anne Jones'; Hopefully that clarifies it a bit. > and this: > > drop table author; > create table author ( > > drop table book; > create table book ( > > drop table book_author; > create table book_author ( sqlite> SELECT title from book, book_author ...> where book_author.bookID = book.ID ...> and book_author.authorID = (select ID from author ...> where name = "Jane Austin"); > maybe its simple but because its more complex im finding it hard to read. Yes, its where SQL starts to get more difficult when you start joining tables together. We are basically extracting data from the author table (Jane Austins ID) to use as a filter in the book_author table to get the IDs of all the books in our database written by Jane Austin. We then use this list of IDs to filter the Books table to get the names of those books. The whole thing could be simplified ifg we didn't use IDs but just used the names directly. But that leads to other problems (discussed in the tutorial) when names change etc (not so likely with books but very common with real people!). So using IDs, even though it adds complexity, is usually a worthwhile habit to get into. > ... why is book_author > also in the select statement when it isn't > being returned? Because we are using it in the query (the where clause) we need to include it in the list of tables. You can think of the SELECT statement as a mini program and the tables list as a list of all the objects used in the program. Its not just for the values being returned. > or are we actually returning every single field from book author? No, only the set of IDs corresponding to Jane Austin's ID. The thing to remember about book_author is that it only contains IDs it has no "real" data of its own. It's purely there to facilitate a multi way join between books and authors. The good news is that once you wrap your brain around this construct most SQL queries you will come across will be comprehensible to you. HTH, if not, just keep firing in the questions. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From losermeloser at yahoo.com Thu Mar 7 01:35:39 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Wed, 6 Mar 2013 16:35:39 -0800 (PST) Subject: [Tutor] mysqlite In-Reply-To: References: <1362595846.26704.YahooMailNeo@web121103.mail.ne1.yahoo.com> Message-ID: <1362616539.78332.YahooMailNeo@web121102.mail.ne1.yahoo.com> >I'm not running it from Python I'm running it from the OS command line. >You need to open a CMD shell window and cd to your SQL database folder >(E:\PROJECTS\SQL in the example above) and then run sqlite3. thanks ill give this a try. ? >We can logically split it like this ? >and putting them together: >update Employee >set ManagerID = JohnsID >where Name = 'Fred Smith' OR >Name = 'Anne Jones'; >Hopefully that clarifies it a bit. ? ok this is very clear now. i totally understand it ? im starting to see the last one and how the filtering is working. i will go over it a few more times to 100% get it. I'll ask more questions if i get stuck along the way:) ? Because i find following your tutorials very easy i have looked at the other topics you have on your site. i notice they are not available in Python 3 but doesnt this matter? or would i need to wait for a python 3 version? Also which could i read next network programming or writing?web applications? or out of eevrything under Applications(excluding databases), which would be the easiest subject for a new programmer to understand ? From doanviettrung at gmail.com Thu Mar 7 03:05:52 2013 From: doanviettrung at gmail.com (DoanVietTrungAtGmail) Date: Thu, 7 Mar 2013 13:05:52 +1100 Subject: [Tutor] A CSV field is a list of integers - how to read it as such? In-Reply-To: <5134A09F.1090907@davea.name> References: <51341128.7070902@davea.name> <5134A09F.1090907@davea.name> Message-ID: > Once a csv file has been read by a csv reader (such as DictReader), it's > no longer a csv file. That was an "Aha!" moment for me. The file is on disk, each row of it is in memory as a list or dict, and it's the list or dict that matters. It's so obvious now. Thanks Dave. > a namedtuple is probably exactly what you want. I read this as meaning that while tuples themselves are immutable, to effectively modify it I simply delete it and replace it with a new tuple with new values. Another 'Aha!' Trung -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Thu Mar 7 04:33:39 2013 From: davea at davea.name (Dave Angel) Date: Wed, 06 Mar 2013 22:33:39 -0500 Subject: [Tutor] A CSV field is a list of integers - how to read it as such? In-Reply-To: References: <51341128.7070902@davea.name> <5134A09F.1090907@davea.name> Message-ID: <51380A93.7000205@davea.name> On 03/06/2013 09:05 PM, DoanVietTrungAtGmail wrote: >> Once a csv file has been read by a csv reader (such as DictReader), it's >> no longer a csv file. > > > That was an "Aha!" moment for me. The file is on disk, each row of it is in > memory as a list or dict, and it's the list or dict that matters. It's so > obvious now. Thanks Dave. > >> > > a namedtuple is probably exactly what you want. > > > I read this as meaning that while tuples themselves are immutable, to > effectively modify it I simply delete it and replace it with a new tuple > with new values. Another 'Aha!' > A collections.namedtuple is not the same as a tuple. The items in it can be addressed either by index, or by name. But each instance of the tuple does *not* waste space duplicating those names. The names are stored once per type of namedtuple http://docs.python.org/2/library/collections.html#collections.namedtuple Look at the example following the comment: """ Named tuples are especially useful for assigning field names to result tuples returned by the csv or sqlite3 modules:" And an instance created through collections.namedtuple has a useful method: somenamedtuple._replace(kwargs) Return a new instance of the named tuple replacing specified fields with new values: -- DaveA From suhasbhairav at hotmail.com Thu Mar 7 06:26:43 2013 From: suhasbhairav at hotmail.com (suhas bhairav) Date: Thu, 7 Mar 2013 10:56:43 +0530 Subject: [Tutor] Fwd: findall() returns tuples or string? In-Reply-To: <1362603317.56563.YahooMailNeo@web163801.mail.gq1.yahoo.com> References: , , , <1362603317.56563.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: Hi Alan, As far as my understanding goes, re.findall without using "()" inside your pattern will return you a list of strings when you search something similar to the one shown below: a="Bangalore, India"re.findall("[\w][\n]*",a) Output:- ['B','a','n','g','a','l','o','r','e','I','n','d','i','a'] So the above output is a list of strings. When you enclose your pattern within "()", it will return you the output as a list of tuples. The member of each tuple is a string. a="Amherst, Massachusetts"re.findall("(Am)(herst)",a)Output:- [('Am','herst')] So the above output is a list of tuples. Let me know if you any questions. RegardsSuhas > Date: Wed, 6 Mar 2013 12:55:17 -0800 > From: fomcl at yahoo.com > To: alan.gauld at btinternet.com; tutor at python.org > Subject: Re: [Tutor] Fwd: findall() returns tuples or string? > > > > >> I have some confusion regarding when findall returns a list of strings > >> and when it returns a list of tuples. > >> Would appreciate an explanation. > > > >re is not my strongest suite but I'll have a go. > > > >My understanding of how findall works is that it returns a list of matches. If groups are used in the pattern each match will be a tuple containing the groups (if there is only one group in the pattern it will be a tuple of only one element) > > One nice trick/feature that I recently discovered is that it's possible to "turn off" groups by using "?:" > > >>> import re > > >>> re.findall("(python(?:ic)?)", "python") > ['python'] > > >>> re.search("(python(?:ic)?)", "python").group(2) > > Traceback (most recent call last): > File "", line 1, in > re.search("(python(?:ic)?)", "python").group(2) > IndexError: no such group > >>> re.findall("(python(ic)?)", "python") > [('python', '')] > >>> re.findall("(python(ic)?)", "pythonic") > [('pythonic', 'ic')] > > > Thought it'd be nice to share this. ;-) > > > Regards, > Albert-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 eryksun at gmail.com Thu Mar 7 07:35:44 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 7 Mar 2013 01:35:44 -0500 Subject: [Tutor] Fwd: findall() returns tuples or string? In-Reply-To: References: <1362603317.56563.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: On Thu, Mar 7, 2013 at 12:26 AM, suhas bhairav wrote: > As far as my understanding goes, re.findall without using "()" inside your > pattern will return you a list of strings when you search something similar > to the one shown below: > > a="Bangalore, India" > re.findall("[\w][\n]*",a) With respect to using groups with findall, there are 3 cases discussed in the docs: http://docs.python.org/2/library/re#re.findall >>> a = "Bangalore, India\n\n\n" >>> re.findall(r'\w+\s*', a) # no groups ['Bangalore', 'India\n\n\n'] >>> re.findall(r'(\w+)\s*', a) # 1 group ['Bangalore', 'India'] >>> re.findall(r'(\w+)(\s*)', a) # 2+ groups [('Bangalore', ''), ('India', '\n\n\n')] CPython 2.7.3, _sre.c, pattern_findall (see 2089-2116): http://hg.python.org/cpython/file/70274d53c1dd/Modules/_sre.c#l2088 From alan.gauld at btinternet.com Thu Mar 7 10:43:30 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 07 Mar 2013 09:43:30 +0000 Subject: [Tutor] mysqlite In-Reply-To: <1362616539.78332.YahooMailNeo@web121102.mail.ne1.yahoo.com> References: <1362595846.26704.YahooMailNeo@web121103.mail.ne1.yahoo.com> <1362616539.78332.YahooMailNeo@web121102.mail.ne1.yahoo.com> Message-ID: On 07/03/13 00:35, Lolo Lolo wrote: > Because i find following your tutorials very easy i have looked > at the other topics you have on your site. > i notice they are not available in Python 3 Not yet, I'm still working on them. :-) I have been very busy at work the last 2-3 years so made little progress but last month I took voluntary redundancy and plan on taking a 6 month sabbatical so hopefully I will have time to complete the v3 tutor. > but doesnt this matter? or would i need to wait for a python 3 version? You should be able to translate the v2 to v3 fairly easily. > Also which could i read next network programming or writing web applications? The web apps bit is very thin, even in v2, it needs a lot of work so I'd say networking or OS are a better bet for now. The networking topic really works best if you read the 3 topics in order: OS, IPC, Networking because they build on each other. If you are familiar with computing concepts like processes, pipes and so on you could reads them separately but otherwise I'd follow through in order. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From charles.leviton at gmail.com Thu Mar 7 16:29:12 2013 From: charles.leviton at gmail.com (Charles Leviton) Date: Thu, 7 Mar 2013 10:29:12 -0500 Subject: [Tutor] Fwd: findall() returns tuples or string? In-Reply-To: References: Message-ID: Thanks Devin. now I have a better understanding of what happens. Let me explore finditer- hearing for the first time. On Mon, Mar 4, 2013 at 8:47 PM, Devin Jeanpierre wrote: > On Mon, Mar 4, 2013 at 8:22 PM, Charles Leviton > wrote: > > I have some confusion regarding when findall returns a list of strings > and > > when it returns a list of tuples. > > Would appreciate an explanation. > > If there are no groups, it returns a list of strings, where the > strings are the whole match. > > If there is one group, it returns a list of strings, where the strings > are the content of the group. > > Otherwise, it returns a list of tuples of strings, where the tuples > contain the group contents (the same as if an individual match had its > groups() method called). > > If you want consistency, use finditer instead of findall. > http://docs.python.org/2/library/re.html#re.finditer > > -- Devin > -------------- next part -------------- An HTML attachment was scrubbed... URL: From johnnyukpo at gmail.com Thu Mar 7 21:23:43 2013 From: johnnyukpo at gmail.com (akuma ukpo) Date: Thu, 7 Mar 2013 15:23:43 -0500 Subject: [Tutor] Need help with function coding. Message-ID: I have a python lab to do but for some reason i can't understand. (a) Write a function which converts from gallons to cups2 (b) Now we?d like to be able to convert from cups to milliliters, since metric measurements are easier to convert between. Implement a function which does this. (c) We?d also like to be able to easily convert gallons into milliliters, so implement a function which does this -- *Akuma* -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Thu Mar 7 21:40:38 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 7 Mar 2013 15:40:38 -0500 Subject: [Tutor] Need help with function coding. In-Reply-To: References: Message-ID: On Thu, Mar 7, 2013 at 3:23 PM, akuma ukpo wrote: > I have a python lab to do but for some reason i can't understand. > > > (a) Write a function which converts from gallons to cups2 > (b) Now we?d like to be able to convert from cups to milliliters, since > metric measurements > are easier to convert between. Implement a function which does this. > (c) We?d also like to be able to easily convert gallons into milliliters, > so implement a > function which does this > > Do you know how to define a function? Do you know how your function can return a value? Do you know the formula for converting gallons to cups. Hint: there are 8 ounces in a cup and 128 ounces in a gallon. There are a thousand milliliters in a liter. I'm sure you can google how many liters in a gallon. So write what you have tried so far > -- > *Akuma* > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Thu Mar 7 21:41:15 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 7 Mar 2013 13:41:15 -0700 Subject: [Tutor] Need help with function coding. In-Reply-To: References: Message-ID: > (a) Write a function which converts from gallons to cups2 Do you know how to write functions? Can you write a function that takes a number and returns twice that number, for example? Show us what you have seen already, and we may be able to start from there. The question you are asking does not tell us anything useful, unfortunately. More specifically, it doesn't tell us where you are getting confused. Since we can't just solve the problem for you, the best thing you can do is to help us see where you are getting stuck. From breamoreboy at yahoo.co.uk Thu Mar 7 21:56:39 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 07 Mar 2013 20:56:39 +0000 Subject: [Tutor] Need help with function coding. In-Reply-To: References: Message-ID: On 07/03/2013 20:23, akuma ukpo wrote: > I have a python lab to do but for some reason i can't understand. > > > (a) Write a function which converts from gallons to cups2 > (b) Now we?d like to be able to convert from cups to milliliters, since > metric measurements > are easier to convert between. Implement a function which does this. > (c) We?d also like to be able to easily convert gallons into > milliliters, so implement a > function which does this > > -- > /Akuma/ > I'll assume that you don't know how a cup is defined so please read this http://gwydir.demon.co.uk/jo/units/volume.htm#small. Then write some code, test it and if you have problems please get back to us. -- Cheers. Mark Lawrence From dyoo at hashcollision.org Thu Mar 7 22:14:51 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 7 Mar 2013 14:14:51 -0700 Subject: [Tutor] Need help with function coding. In-Reply-To: References: Message-ID: On Thu, Mar 7, 2013 at 1:55 PM, akuma ukpo wrote: > i don't know how to write functions. so i guess that is where i'm stuck. i > was following a tutorial on my lab document but i still did not understand > what to do. i will attach the pdf and python files as well. I am CCing the rest of the Python tutor mailing list. Please use reply-to-all when responding to messages on Tutor. I'm omitting the attachments you sent me, as they're not that useful to me. Since you do not know how to write functions yet, I would strongly focus on solving that confusion first. If you don't know how to write any functions, then you will have difficulty with your problem set. Has your instructor given you any information on how to write a function? For example, http://www.learnpython.org/page/Functions From johnnyukpo at gmail.com Thu Mar 7 22:28:06 2013 From: johnnyukpo at gmail.com (akuma ukpo) Date: Thu, 7 Mar 2013 16:28:06 -0500 Subject: [Tutor] Need help with function coding. In-Reply-To: References: Message-ID: i now know how to define functions. My problem is i don't know what particular function that converts gallons directly to cups. However, i derived a function that converts celsius to fahrenheit (9/5 * temperature + 32) tested it using python and it passed the test. I need a function for gallons to cups in a similar format. On Thu, Mar 7, 2013 at 4:14 PM, Danny Yoo wrote: > On Thu, Mar 7, 2013 at 1:55 PM, akuma ukpo wrote: > > i don't know how to write functions. so i guess that is where i'm stuck. > i > > was following a tutorial on my lab document but i still did not > understand > > what to do. i will attach the pdf and python files as well. > > I am CCing the rest of the Python tutor mailing list. Please use > reply-to-all when responding to messages on Tutor. I'm omitting the > attachments you sent me, as they're not that useful to me. > > > Since you do not know how to write functions yet, I would strongly > focus on solving that confusion first. If you don't know how to write > any functions, then you will have difficulty with your problem set. > > > Has your instructor given you any information on how to write a > function? For example, > > http://www.learnpython.org/page/Functions > -- *Akuma* -------------- next part -------------- An HTML attachment was scrubbed... URL: From johnnyukpo at gmail.com Thu Mar 7 22:36:58 2013 From: johnnyukpo at gmail.com (akuma ukpo) Date: Thu, 7 Mar 2013 16:36:58 -0500 Subject: [Tutor] Need help with function coding. In-Reply-To: References: Message-ID: I am defining the function in one .py file and testing the function in another .py file. this is my code for the test: def test_quantity_convert(self): self.assertEqual(gallons_to_cups(0), 16) self.assertEqual(gallons_to_cups(100), 1600) this is my code for the defined function: def gallons_to_cups(quant): """ Takes quantity 'quant' in Gallons and computes and returns the equivalent Cup quantity """ return 16 * quant + 0 what am i doing wrong? On Thu, Mar 7, 2013 at 4:28 PM, akuma ukpo wrote: > i now know how to define functions. > > My problem is i don't know what particular function that converts gallons > directly to cups. > > However, i derived a function that converts celsius to fahrenheit (9/5 * > temperature + 32) tested it using python and it passed the test. > > I need a function for gallons to cups in a similar format. > > On Thu, Mar 7, 2013 at 4:14 PM, Danny Yoo wrote: > >> On Thu, Mar 7, 2013 at 1:55 PM, akuma ukpo wrote: >> > i don't know how to write functions. so i guess that is where i'm >> stuck. i >> > was following a tutorial on my lab document but i still did not >> understand >> > what to do. i will attach the pdf and python files as well. >> >> I am CCing the rest of the Python tutor mailing list. Please use >> reply-to-all when responding to messages on Tutor. I'm omitting the >> attachments you sent me, as they're not that useful to me. >> >> >> Since you do not know how to write functions yet, I would strongly >> focus on solving that confusion first. If you don't know how to write >> any functions, then you will have difficulty with your problem set. >> >> >> Has your instructor given you any information on how to write a >> function? For example, >> >> http://www.learnpython.org/page/Functions >> > > > > -- > *Akuma* > -- *Akuma* -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Thu Mar 7 22:44:37 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 7 Mar 2013 16:44:37 -0500 Subject: [Tutor] Need help with function coding. In-Reply-To: References: Message-ID: On Thu, Mar 7, 2013 at 4:36 PM, akuma ukpo wrote: > I am defining the function in one .py file and testing the function in > another .py file. > > this is my code for the test: > > def test_quantity_convert(self): > self.assertEqual(gallons_to_cups(0), 16) > self.assertEqual(gallons_to_cups(100), 1600) > > this is my code for the defined function: > > def gallons_to_cups(quant): > """ > Takes quantity 'quant' in Gallons and computes and > returns the equivalent Cup quantity > """ > return 16 * quant + 0 > > > what am i doing wrong? > > > On Thu, Mar 7, 2013 at 4:28 PM, akuma ukpo wrote: > >> i now know how to define functions. >> >> My problem is i don't know what particular function that converts gallons >> directly to cups. >> > Knowing how many cups in a gallon is a google search away. I think its 128/8 but you should check http://lmgtfy.com/?q=how+many+cups+in+a+gallon >> However, i derived a function that converts celsius to fahrenheit (9/5 * >> temperature + 32) tested it using python and it passed the test. >> >> I need a function for gallons to cups in a similar format. >> >> On Thu, Mar 7, 2013 at 4:14 PM, Danny Yoo wrote: >> >>> On Thu, Mar 7, 2013 at 1:55 PM, akuma ukpo wrote: >>> > i don't know how to write functions. so i guess that is where i'm >>> stuck. i >>> > was following a tutorial on my lab document but i still did not >>> understand >>> > what to do. i will attach the pdf and python files as well. >>> >>> I am CCing the rest of the Python tutor mailing list. Please use >>> reply-to-all when responding to messages on Tutor. I'm omitting the >>> attachments you sent me, as they're not that useful to me. >>> >>> >>> Since you do not know how to write functions yet, I would strongly >>> focus on solving that confusion first. If you don't know how to write >>> any functions, then you will have difficulty with your problem set. >>> >>> >>> Has your instructor given you any information on how to write a >>> function? For example, >>> >>> http://www.learnpython.org/page/Functions >>> >> >> >> >> -- >> *Akuma* >> > > > > -- > *Akuma* > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Thu Mar 7 23:56:28 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 7 Mar 2013 15:56:28 -0700 Subject: [Tutor] Need help with function coding. In-Reply-To: References: Message-ID: On Thu, Mar 7, 2013 at 2:36 PM, akuma ukpo wrote: > I am defining the function in one .py file and testing the function in > another .py file. > > this is my code for the test: > > def test_quantity_convert(self): > self.assertEqual(gallons_to_cups(0), 16) Good, thanks for showing us how you're testing this. I disagree with this specific test. If I don't have any gallons, how can that become sixteen cups? From __peter__ at web.de Fri Mar 8 00:00:51 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 08 Mar 2013 00:00:51 +0100 Subject: [Tutor] Need help with function coding. References: Message-ID: akuma ukpo wrote: > I am defining the function in one .py file and testing the function in > another .py file. > > this is my code for the test: > > def test_quantity_convert(self): > self.assertEqual(gallons_to_cups(0), 16) > self.assertEqual(gallons_to_cups(100), 1600) > > this is my code for the defined function: > > def gallons_to_cups(quant): > """ > Takes quantity 'quant' in Gallons and computes and > returns the equivalent Cup quantity > """ > return 16 * quant + 0 > > > what am i doing wrong? This line in your test code is wrong: > self.assertEqual(gallons_to_cups(0), 16) By the way, adding 0 does not change the result here: > return 16 * quant + 0 From cpe.list at gmail.com Fri Mar 8 04:14:14 2013 From: cpe.list at gmail.com (Christopher Emery) Date: Thu, 7 Mar 2013 22:14:14 -0500 Subject: [Tutor] New Programmer - Designing Message-ID: Hello All, I am new to this email list as can see from subject, my name is Christopher. I am trying to learn how to design a program but I seem not to find any resource online that will teach how to design the program before you start programming. I would like to create a program that will filter a file and put the information into two database (text based for now) So how would I start the process of designing such a application? Also because this is a part of a bigger application that will have many user interfaces, phone, web, mobile I want to learn how to keep code apart from UI. For example if a program was created to take a person information how would that look? I tried to think of basic process. so in this example I know the following would need be done: user would pick option on UI to Add, Update, Delete, if add picked then grab information from UI as varibles (I am assuming) then process would check varibles types are correct and existing then process would either give error or continue to storing the information So how would one go about designing this module? Would this be the right name to call this part of a bigger program? Thank you for your assistance, please don't mind my writing I am not a good writer. Sincerely in Christ, Christopher -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Mar 8 09:59:18 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 08 Mar 2013 08:59:18 +0000 Subject: [Tutor] New Programmer - Designing In-Reply-To: References: Message-ID: On 08/03/13 03:14, Christopher Emery wrote: > I am new to this email list as can see from subject, my name is > Christopher. Hi, welcome. > I am trying to learn how to design a program but I seem > not to find any resource online that will teach how to design the > program before you start programming. There are lots of techniques, but mostly aimed at bigger problems. There is a shortage of information on designing at the smaller scale level. One excellent site is the How To Design Programs book which is aimed at Lisp/Scheme programmers but is largely applicable to Python etc too. (Except you have to convert recursion into loops): http://www.htdp.org The other important thing to grasp is the general principle of algorithm design which is a branch of math. There are a few web pages and books dedicated to that too. Finally you can use design tools like UML (which I introduce in the OOP topic of my tutorial) which can be useful on bigger projects, especially if using classes/objects. > I would like to create a program that will filter a file and put the > information into two database (text based for now) > So how would I start the process of designing such a application? At this level of design I normally just use pseudo code. Start with a high level plain English (or whatever your first language is!) description of what you want to do - the algorithm. Refine it into a structured form that looks somewhat like your programming language of choice. Make those your comments. Now for each comment write the code that does that part of the algorithm. > user interfaces, phone, web, mobile I want to learn how to keep code > apart from UI. For example if a program was created to take a person > information how would that look? I tried to think of basic process. so > in this example I know the following would need be done: > > user would pick option on UI to Add, Update, Delete, if add picked then > grab information from UI as varibles (I am assuming) > then process would check varibles types are correct and existing > then process would either give error or continue to storing the information In general all of the above except the storage would be UI code. If the validation required complex logic or access to other data then it might be outside the UI too. As a general rule anything that reads or displays data is UI. Lightweight data validation (eg type and range checking) is usually UI too. Any data processing, transmission, storage should be in the logic part of the code. > So how would one go about designing this module? Would this be the > right name to call this part of a bigger program? I'm not sure what name you are referring to? HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jitu.icfai at gmail.com Fri Mar 8 13:38:15 2013 From: jitu.icfai at gmail.com (jitendra gupta) Date: Fri, 8 Mar 2013 18:08:15 +0530 Subject: [Tutor] Unit test cases for Object intraction using mox/unittest Message-ID: Hi I need to write the unit test cases for similary kind of sitution. I need to write the unit test case for Foo.testCall. for both case true or false. I am unalbe to do that. kindly please help me on this. as function is not returning any thing. from google i got mox is good for this case. but i did not found any solution for this case ****************** Enter.py ******************** from run import RunComp def enter(): runC = RunComp("ComName", "~/pathToHome") """ This is based on some database condition we are passing name true or false """ foo = Foo(true) foo.testCall(runC) if __name__ == "__main__": enter() ************************************************** ***************** foo.py************************ Class Foo(): def __init__(self, found): self.found = found def testCall(self, SomeClassObject): if self.found: RunCompObject.call_run("codeRun -s " + self.found) else: RunCompObject.call_run("codeRun") ************************************************* ************** run.py ************************** from subprocess import call class RunComp(object): def __init__(self, com, home): self.comp = comp self.home = home def call_and_raise(*args, **kwargs): if call(*args, **kwargs): raise RuntimeError("LDF command failed!") def call_run(self, command): if self.comp: command = " ".join((command,myldfrc)) call(command, cwd=self.home) ************************************************* Thanks & Regards Jitu -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Fri Mar 8 14:00:58 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 08 Mar 2013 13:00:58 +0000 Subject: [Tutor] Unit test cases for Object intraction using mox/unittest In-Reply-To: References: Message-ID: On 08/03/2013 12:38, jitendra gupta wrote: > Hi > > I need to write the unit test cases for similary kind of sitution. > > I need to write the unit test case for Foo.testCall. for both case true > or false. I am unalbe to do that. > What Python version and OS, what did you try and what went wrong? Would you also be kind enough not to post the same question two minutes apart on two different Python mailing lists. -- Cheers. Mark Lawrence From breamoreboy at yahoo.co.uk Fri Mar 8 14:02:38 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 08 Mar 2013 13:02:38 +0000 Subject: [Tutor] Unit test cases for Object intraction using mox/unittest In-Reply-To: References: Message-ID: On 08/03/2013 12:38, jitendra gupta wrote: The self same question has been asked on the tutor mailing, I suggest we all answer over there rather than scattering seeds to the wind. -- Cheers. Mark Lawrence From losermeloser at yahoo.com Fri Mar 8 15:29:03 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Fri, 8 Mar 2013 06:29:03 -0800 (PST) Subject: [Tutor] mysqlite In-Reply-To: References: <1362595846.26704.YahooMailNeo@web121103.mail.ne1.yahoo.com> Message-ID: <1362752943.5429.YahooMailNeo@web121101.mail.ne1.yahoo.com> I finished the tutorial and must say i am very happy. Ill probably go over it again while writing some test dbs. The SQL command line still troubles me ? >I'm not running it from Python I'm running it from the OS command line. >You need to open a CMD shell window and cd to your SQL database folder >(E:\PROJECTS\SQL in the example above) and then run sqlite3. >sqlite3 employee.db >> my main questions are it possible to use the command line >> without cursor() and connect() in python 3 >No only from the sqlite command line. ? I can only find an sqlite3 folder in my Python installation folder. Python\Lib\sqlite3 ? the command line command doesnt work from inside this folder, but i am guessing this isnt where im supposed to do it from. Is there a sqlite program i am supposed to install that is separate from the one that came with Python? Its the only reason i can come up with for my cmd not "recognizing sqlite3 as a command, operable program or batch file", but i don't know which SQL package?to download/install. From alan.gauld at btinternet.com Fri Mar 8 17:59:32 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Fri, 8 Mar 2013 16:59:32 +0000 (GMT) Subject: [Tutor] mysqlite In-Reply-To: <1362752943.5429.YahooMailNeo@web121101.mail.ne1.yahoo.com> References: <1362595846.26704.YahooMailNeo@web121103.mail.ne1.yahoo.com> <1362752943.5429.YahooMailNeo@web121101.mail.ne1.yahoo.com> Message-ID: <1362761972.43363.YahooMailNeo@web186003.mail.ir2.yahoo.com> >>No only from the sqlite command line. >? >I can only find an sqlite3 folder in my Python installation folder. Python\Lib\sqlite3 >? That's because you are using the default SQLite ?that comes with Python? which is only the library for connecting from Python. I'll need to clarify that in the tutor. You need to download and install the full Sqlite3? package from the SQLIte web site to get the command line tools. This is well worth? doing though because it makes quick 'n dirty queries and data loads much easier? than having to write a full Python program to do it.?You can create a file of pure? SQL and run that directly.? Alan G. From 3n2solutions at gmail.com Fri Mar 8 19:37:43 2013 From: 3n2solutions at gmail.com (3n2 Solutions) Date: Fri, 8 Mar 2013 10:37:43 -0800 Subject: [Tutor] Running EXE file with arguments Message-ID: Below is the shell command that works fine if ran as is: C:\FinalTest>fix.exe -com 17 -baud 38400 -setconfig base.dat I'm trying to automate it using the following python command but it gives me an error: "....returned non-zero exit status 1" subprocess.check_call(['c:/FinalTest/fix.exe', '-com 17','-baud 38400', '-setconfig base.dat']) Where is the problem? Thank You! Tim From jguadamuz at gmail.com Fri Mar 8 19:44:24 2013 From: jguadamuz at gmail.com (=?ISO-8859-1?Q?Jonat=E1n_Guadamuz_Espinoza?=) Date: Fri, 8 Mar 2013 12:44:24 -0600 Subject: [Tutor] Running EXE file with arguments In-Reply-To: References: Message-ID: El viernes, 8 de marzo de 2013, 3n2 Solutions <3n2solutions at gmail.com> escribi?: > Below is the shell command that works fine if ran as is: > C:\FinalTest>fix.exe -com 17 -baud 38400 -setconfig base.dat > > I'm trying to automate it using the following python command but it > gives me an error: "....returned non-zero exit status 1" > > subprocess.check_call(['c:/FinalTest/fix.exe', '-com 17','-baud > 38400', '-setconfig base.dat']) > > Where is the problem? > Maybe you could try to give the full path for base.dat as you did with fix.exe -- Sent from Gmail Mobile -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Sat Mar 9 02:25:59 2013 From: eryksun at gmail.com (eryksun) Date: Fri, 8 Mar 2013 20:25:59 -0500 Subject: [Tutor] Running EXE file with arguments In-Reply-To: References: Message-ID: On Fri, Mar 8, 2013 at 1:37 PM, 3n2 Solutions <3n2solutions at gmail.com> wrote: > subprocess.check_call(['c:/FinalTest/fix.exe', '-com 17','-baud > 38400', '-setconfig base.dat']) You can use a single string for the command on Windows. subprocess will create one anyway, but let's stick with a list, split on the spaces in the string. Since the command works in the shell from the exe directory, try setting the current working directory (cwd) to C:\FinalTest: import sys import os import subprocess exepath = 'c:\\FinalTest' exefile = 'fix.exe' cfgfile = 'base.dat' exe = os.path.join(exepath, exefile) cmd = [exe, '-com', '17', '-baud', '38400', '-setconfig', cfgfile] try: subprocess.check_call(cmd, cwd=exepath) except subprocess.CalledProcessError as e: # exit, logging, etc sys.exit(str(e)) From leamhall at gmail.com Sat Mar 9 18:24:12 2013 From: leamhall at gmail.com (Leam Hall) Date: Sat, 09 Mar 2013 12:24:12 -0500 Subject: [Tutor] SMTP('my.smtpserver.com') hangs Message-ID: <513B703C.4070900@gmail.com> Python 2.6.6 on CentOS 6 I'm in section 3.4.12 of Wesley Chun's "Core Python Applications Programming". The POP3 stuff works but I can't seem to get the SMTP to connect, it just hangs and then times out. Running it in IDLE gets the same thing. Have also tried with the port # set, as well. Thoughts? Leam #### #!/usr/bin/env python from smtplib import SMTP from poplib import POP3 from time import sleep SMTPSVR = 'my.smtpserver.com' POP3SVR = 'my.smtpserver.com' who = 'me at smtpserver.com' user = 'me+smtpserver.com' pass_ = 'my_super_secret' body = '''\ From: %(who)s To: %(who)s Subject: test e-mail Hello world! ''' % {'who' : who } send_svr = SMTP(SMTPSVR) errs = send_svr.sendmail(who, [who], body) send_svr.quit() assert len(errs) == 0, errs print "Starting sleep" sleep(10) recv_svr = POP3(POPSVR) recv_svr.user(user) recv_svr.pass_(pass_) rsp, msg, siz = recv-svr.retr(recv_svr.stat()[0]) recv_svr.quit() sep = msg.index('') recv_body = msg[sep+1:] recv_svr.quit() assert body == recv_body From jsf80238 at gmail.com Sat Mar 9 19:23:30 2013 From: jsf80238 at gmail.com (Jason Friedman) Date: Sat, 9 Mar 2013 11:23:30 -0700 Subject: [Tutor] Need help with function coding. Message-ID: You might look at this: https://chrome.google.com/webstore/detail/converter/elogiihmdefhdcainoihdcfpnfbimpnd?hl=en-US&utm_source=chrome-ntp-launcher From joel.goldstick at gmail.com Sat Mar 9 19:35:14 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 9 Mar 2013 13:35:14 -0500 Subject: [Tutor] SMTP('my.smtpserver.com') hangs In-Reply-To: <513B703C.4070900@gmail.com> References: <513B703C.4070900@gmail.com> Message-ID: On Sat, Mar 9, 2013 at 12:24 PM, Leam Hall wrote: > Python 2.6.6 on CentOS 6 > > I'm in section 3.4.12 of Wesley Chun's "Core Python Applications > Programming". The POP3 stuff works but I can't seem to get the SMTP to > connect, it just hangs and then times out. Running it in IDLE gets the same > thing. Have also tried with the port # set, as well. > > Thoughts? > > Leam > > #### > > #!/usr/bin/env python > > from smtplib import SMTP > from poplib import POP3 > from time import sleep > > SMTPSVR = 'my.smtpserver.com' > POP3SVR = 'my.smtpserver.com' > > who = 'me at smtpserver.com' > > > The line below looks suspect. > user = 'me+smtpserver.com' > pass_ = 'my_super_secret' > > body = '''\ > From: %(who)s > To: %(who)s > Subject: test e-mail > > Hello world! > ''' % {'who' : who } > > send_svr = SMTP(SMTPSVR) > errs = send_svr.sendmail(who, [who], body) > send_svr.quit() > > assert len(errs) == 0, errs > > print "Starting sleep" > > sleep(10) > > recv_svr = POP3(POPSVR) > recv_svr.user(user) > recv_svr.pass_(pass_) > rsp, msg, siz = recv-svr.retr(recv_svr.stat()[**0]) > recv_svr.quit() > sep = msg.index('') > recv_body = msg[sep+1:] > recv_svr.quit() > assert body == recv_body > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From mlybrand at gmail.com Sun Mar 10 02:39:28 2013 From: mlybrand at gmail.com (Mark Lybrand) Date: Sat, 9 Mar 2013 17:39:28 -0800 Subject: [Tutor] Bar Operator ?? Message-ID: I am working through the Django tutorial and I have come across some syntax I am unfamiliar with. From the context it makes perfect sense what it does, but I haven't seen it before and was wondering if it is documented anywhere (BTW I see other examples in the Django documentation, like date formatting for example). So what is this "|pluralize" syntax? Thanks in andvance

{{ poll.question }}

    {% for choice in poll.choice_set.all %}
  • {{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}
  • {% endfor %}
Vote again? -- Mark :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From msirenef at lightbird.net Sun Mar 10 02:48:59 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Sat, 09 Mar 2013 20:48:59 -0500 Subject: [Tutor] Bar Operator ?? In-Reply-To: References: Message-ID: <513BE68B.9050303@lightbird.net> On 03/09/2013 08:39 PM, Mark Lybrand wrote: > I am working through the Django tutorial and I have come across some syntax I am unfamiliar with. From the context it makes perfect sense what it does, but I haven't seen it before and was wondering if it is documented anywhere (BTW I see other examples in the Django documentation, like date formatting for example). > > So what is this "|pluralize" syntax? Thanks in andvance > >

{{ poll.question }}

> >
    > {% for choice in poll.choice_set.all %} >
  • {{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}
  • > {% endfor %} >
> > Vote again? > > > > -- > Mark :) > > It's a filter: https://docs.djangoproject.com/en/1.5/ref/templates/builtins/ -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Whosoever is delighted in solitude is either a wild beast or a god. Sir Francis Bacon From mathieu.poag at outlook.com Sun Mar 10 02:53:38 2013 From: mathieu.poag at outlook.com (Mathieu Poag) Date: Sat, 9 Mar 2013 19:53:38 -0600 Subject: [Tutor] Bar Operator ?? In-Reply-To: <513BE68B.9050303@lightbird.net> References: <513BE68B.9050303@lightbird.net> Message-ID: I need some advice. I have been searching throughout the internet for the beginner's guide to learning Python. I am a little lost. Any help or a point in the right direction would be great. Mathieu Sent from my iPad On Mar 9, 2013, at 7:51 PM, "Mitya Sirenef" wrote: > On 03/09/2013 08:39 PM, Mark Lybrand wrote: >> I am working through the Django tutorial and I have come across some syntax I am unfamiliar with. From > the context it makes perfect sense what it does, but I haven't seen it before and was wondering if it is documented anywhere (BTW I see other examples in the Django documentation, like date formatting for example). > > > > So what is this "|pluralize" syntax? Thanks in andvance > > > >

{{ poll.question }}

> > > >
    > > {% for choice in poll.choice_set.all %} > >
  • {{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}
  • > > {% endfor %} > >
> > > > Vote again? > > > > > > > > -- > > Mark :) > > > > > > > It's a filter: > > https://docs.djangoproject.com/en/1.5/ref/templates/builtins/ > > > -- > Lark's Tongue Guide to Python: http://lightbird.net/larks/ > > Whosoever is delighted in solitude is either a wild beast or a god. > Sir Francis Bacon > > _______________________________________________ > 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 Mar 10 09:45:31 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 10 Mar 2013 08:45:31 +0000 Subject: [Tutor] Bar Operator ?? In-Reply-To: References: <513BE68B.9050303@lightbird.net> Message-ID: On 10/03/13 01:53, Mathieu Poag wrote: > I need some advice. I have been searching throughout the internet > for the beginner's guide to learning Python. I am a little lost. So what did you find? In what way are you lost? The Python web site has two pages for beginners. One for people who can already program in another language and another for people who have never programmed before. Which category are you in and did you find those pages? If so did you try any of the tutorials to which they link? http://www.python.org/about/gettingstarted/ -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From vincentbalmori at yahoo.com Sun Mar 10 09:57:16 2013 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Sun, 10 Mar 2013 00:57:16 -0800 (PST) Subject: [Tutor] Use __str__ method for int values Message-ID: <1362905836.72302.YahooMailNeo@web164905.mail.bf1.yahoo.com> I am trying to use a __str__ method to display the values of attribute mood = self.hunger + self. boredom. When I try to execute I get this error: Traceback (most recent call last): ? File "C:/Users/Vincent/Documents/Programming Tutorials/Python Programming for the Absolute Beginner - Project Files/source/chapter08/critter_caretaker_vpb3.py", line 105, in ? ? main() ? File "C:/Users/Vincent/Documents/Programming Tutorials/Python Programming for the Absolute Beginner - Project Files/source/chapter08/critter_caretaker_vpb3.py", line 99, in main ? ? print(crit) TypeError: __str__ returned non-string (type int) This is the code: # Critter Caretaker # A virtual pet to care for import random class Critter(object): ? ? """A virtual pet""" ? ? def __init__(self, name, hunger = 0, boredom = 0): ? ? ? ? self.name = name ? ? ? ? self.hunger = hunger ? ? ? ? self.boredom = boredom ? ? def __pass_time(self): ? ? ? ? self.hunger += 1 ? ? ? ? self.boredom += 1 ? ? def __str__(self): ? ? ? ? mood = self.boredom + self.hunger ? ? ? ? return mood ? ? @property ? ? def mood(self): ? ? ? ? unhappiness = self.hunger + self.boredom ? ? ? ? if unhappiness < 5: ? ? ? ? ? ? m = "happy" ? ? ? ? elif 5 <= unhappiness <= 10: ? ? ? ? ? ? m = "okay" ? ? ? ? elif 11 <= unhappiness <= 15: ? ? ? ? ? ? m = "frustrated" ? ? ? ? else: ? ? ? ? ? ? m = "mad" ? ? ? ? return m ? ?? ? ? def talk(self): ? ? ? ? print("I'm", self.name, "and I feel", self.mood, "now.\n") ? ? ? ? self.__pass_time() ? ?? ? ? def eat(self, food = 4): ? ? ? ? food = int(input("How much do you want to feed?: ")) ? ? ? ? while food > 5: ? ? ? ? ? ? food = int(input("That's too much! How much do you want to feed?: ")) ? ? ? ? print("Brruppp. ?Thank you.") ? ? ? ? self.hunger -= food ? ? ? ? self.boredom += int(food * random.randint(0,3)) ? ? ? ? if self.hunger < 0: ? ? ? ? ? ? self.hunger = 0 ? ? ? ? self.__pass_time() ? ? def play(self, fun = 4): ? ? ? ? fun = int(input("How long do you want to play?: ")) ? ? ? ? while fun > 5: ? ? ? ? ? ? fun = int(input("That's too long! How long do you want to play?: ")) ? ? ? ? print("Wheee!") ? ? ? ? self.boredom -= fun ? ? ? ? self.hunger += int(fun * random.randint(0,3)) ? ? ? ? if self.boredom < 0: ? ? ? ? ? ? self.boredom = 0 ? ? ? ? self.__pass_time() def main(): ? ? crit_name = input("What do you want to name your critter?: ") ? ? crit = Critter(crit_name) ? ? choice = None ? ? ? while choice != "0": ? ? ? ? print \ ? ? ? ? (""" ? ? ? ? Critter Caretaker ? ?? ? ? ? ? 0 - Quit ? ? ? ? 1 - Listen to your critter ? ? ? ? 2 - Feed your critter ? ? ? ? 3 - Play with your critter ? ? ? ? """) ? ?? ? ? ? ? choice = input("Choice: ") ? ? ? ? print() ? ? ? ? # exit ? ? ? ? if choice == "0": ? ? ? ? ? ? print("Good-bye.") ? ? ? ? # listen to your critter ? ? ? ? elif choice == "1": ? ? ? ? ? ? crit.talk() ? ? ? ?? ? ? ? ? # feed your critter ? ? ? ? elif choice == "2": ? ? ? ? ? ? crit.eat() ? ? ? ? ? ? ? ? ? # play with your critter ? ? ? ? elif choice == "3": ? ? ? ? ? ? crit.play() ? ? ? ? ? ? ?? ? ? ? ? # play with your critter ? ? ? ? elif choice == "4": ? ? ? ? ? ? print(crit) ? ? ? ? # some unknown choice ? ? ? ? else: ? ? ? ? ? ? print("\nSorry, but", choice, "isn't a valid choice.") main() ("\n\nPress the enter key to exit.")? -------------- next part -------------- An HTML attachment was scrubbed... URL: From timomlists at gmail.com Sun Mar 10 11:23:10 2013 From: timomlists at gmail.com (Timo) Date: Sun, 10 Mar 2013 11:23:10 +0100 Subject: [Tutor] Use __str__ method for int values In-Reply-To: <1362905836.72302.YahooMailNeo@web164905.mail.bf1.yahoo.com> References: <1362905836.72302.YahooMailNeo@web164905.mail.bf1.yahoo.com> Message-ID: <513C5F0E.8000809@gmail.com> Op 10-03-13 09:57, Vincent Balmori schreef: > I am trying to use a __str__ method to display the values of attribute > mood = self.hunger + self. boredom. > When I try to execute I get this error: > > Traceback (most recent call last): > File "C:/Users/Vincent/Documents/Programming Tutorials/Python > Programming for the Absolute Beginner - Project > Files/source/chapter08/critter_caretaker_vpb3.py", line 105, in > main() > File "C:/Users/Vincent/Documents/Programming Tutorials/Python > Programming for the Absolute Beginner - Project > Files/source/chapter08/critter_caretaker_vpb3.py", line 99, in main > print(crit) > TypeError: __str__ returned non-string (type int) Then return a str instead of int. > > > This is the code: > > > # Critter Caretaker > # A virtual pet to care for > > import random > > class Critter(object): > > """A virtual pet""" > def __init__(self, name, hunger = 0, boredom = 0): > self.name = name > self.hunger = hunger > self.boredom = boredom > > def __pass_time(self): > self.hunger += 1 > self.boredom += 1 > > def __str__(self): > mood = self.boredom + self.hunger > return mood Change to: return str(mood) Cheers, Timo From steve at pearwood.info Sun Mar 10 11:26:19 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 10 Mar 2013 21:26:19 +1100 Subject: [Tutor] Use __str__ method for int values In-Reply-To: <1362905836.72302.YahooMailNeo@web164905.mail.bf1.yahoo.com> References: <1362905836.72302.YahooMailNeo@web164905.mail.bf1.yahoo.com> Message-ID: <513C5FCB.5040408@pearwood.info> On 10/03/13 19:57, Vincent Balmori wrote: > I am trying to use a __str__ method to display the values of attribute mood = self.hunger + self. boredom. > When I try to execute I get this error: > > Traceback (most recent call last): > File "C:/Users/Vincent/Documents/Programming Tutorials/Python Programming for the Absolute Beginner - Project Files/source/chapter08/critter_caretaker_vpb3.py", line 105, in > main() > File "C:/Users/Vincent/Documents/Programming Tutorials/Python Programming for the Absolute Beginner - Project Files/source/chapter08/critter_caretaker_vpb3.py", line 99, in main > print(crit) > TypeError: __str__ returned non-string (type int) > > > This is the code: [snip code] You haven't actually asked a question here, so I don't understand what is giving you trouble. I'll try to guess, but please pardon me if I guess wrongly. Have you read the error message Python gives? __str__ returned non-string (type int) This tells you that if __str__ returns something which is not a string, Python will treat it as an error. To fix that, change your __str__ method to return a string. Use the str() function to convert a non-string value into a string. Is the error message not clear enough? If not, can you suggest an improvement? Your __str__ method looks like this: > def __str__(self): > mood = self.boredom + self.hunger > return mood This is not a very good design for a __str__ function. str(some_critter) should return something that indicates to the reader that it is a Critter, not an integer. That is, something like one of these might be appropriate: Critter(name="Fred", boredom=7, hunger=5) or similar, rather than: 12 which does not look like a Critter nor give the reader any hint at all that what they are seeing is a Critter. -- Steven From eryksun at gmail.com Sun Mar 10 11:29:34 2013 From: eryksun at gmail.com (eryksun) Date: Sun, 10 Mar 2013 06:29:34 -0400 Subject: [Tutor] Use __str__ method for int values In-Reply-To: <1362905836.72302.YahooMailNeo@web164905.mail.bf1.yahoo.com> References: <1362905836.72302.YahooMailNeo@web164905.mail.bf1.yahoo.com> Message-ID: On Sun, Mar 10, 2013 at 4:57 AM, Vincent Balmori wrote: > I am trying to use a __str__ method to display the values of attribute mood > = self.hunger + self. boredom. __str__ has to return a string: http://docs.python.org/3/reference/datamodel.html#object.__str__ Bookmark the "_" index of the docs as a quick reference for special methods: http://docs.python.org/3/genindex-_.html For the basic descriptions, follow the "(object method)" links. From steve at pearwood.info Sun Mar 10 16:35:44 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 11 Mar 2013 02:35:44 +1100 Subject: [Tutor] Need help with function coding. In-Reply-To: References: Message-ID: <513CA850.3010309@pearwood.info> On 10/03/13 05:23, Jason Friedman wrote: > You might look at this: > > https://chrome.google.com/webstore/ [...] Why would I do that? If you have a question, please ask it. Don't post a link to something that looks like spam with no explanation at all. Oh, and if you think I'm being rude, consider that the alternative was that I just ignored you completely. -- Steven From joel.goldstick at gmail.com Sun Mar 10 17:09:40 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 10 Mar 2013 12:09:40 -0400 Subject: [Tutor] Need help with function coding. In-Reply-To: <513CA850.3010309@pearwood.info> References: <513CA850.3010309@pearwood.info> Message-ID: On Sun, Mar 10, 2013 at 11:35 AM, Steven D'Aprano wrote: > On 10/03/13 05:23, Jason Friedman wrote: > >> You might look at this: >> >> https://chrome.google.com/**webstore/[...] >> > > > Why would I do that? > > If you have a question, please ask it. Don't post a link to something that > looks like spam with no explanation at all. > > Oh, and if you think I'm being rude, consider that the alternative was > that I just ignored you completely. > > I believe this is a response to the person who wanted help with homework that involved converting from gallons to milliliters. Somehow it got disconnected from the original question thread. > > > -- > Steven > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Mar 10 17:18:31 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 11 Mar 2013 03:18:31 +1100 Subject: [Tutor] Need help with function coding. In-Reply-To: References: <513CA850.3010309@pearwood.info> Message-ID: <513CB257.3070200@pearwood.info> On 11/03/13 03:09, Joel Goldstick wrote: > On Sun, Mar 10, 2013 at 11:35 AM, Steven D'Aprano wrote: > >> On 10/03/13 05:23, Jason Friedman wrote: >> >>> You might look at this: >>> >>> https://chrome.google.com/**webstore/[...] >>> >> >> >> Why would I do that? >> >> If you have a question, please ask it. Don't post a link to something that >> looks like spam with no explanation at all. >> >> Oh, and if you think I'm being rude, consider that the alternative was >> that I just ignored you completely. >> > I believe this is a response to the person who wanted help with homework > that involved converting from gallons to milliliters. Somehow it got > disconnected from the original question thread. Thanks Joel. A good lesson: when replying to an email, always leave enough of the previous email to establish context. Otherwise readers may have no idea what you are talking about. -- Steven From akleider at sonic.net Sun Mar 10 17:56:26 2013 From: akleider at sonic.net (akleider at sonic.net) Date: Sun, 10 Mar 2013 09:56:26 -0700 Subject: [Tutor] subprocess module: when to _NOT_ use shell=True Message-ID: I've not found anywhere a clear explanation of when not to set shell=True. If the command line must be interpreted by the shell then clearly this must be set. So the question that comes up is why not set it always? In an effort to investigate, I came up with the following script that indicates that the shell looks at only the first string in the array if the first parameter is an array rather than a string. Switching between cmd being a string vs an array and shell being set or not set gives 4 possibilities. Any comments? #!/usr/bin/env python # file : test.py (Python 2.7, NOT Python 3) # Running on Linux platform (Ubuntu.) print 'Running "tes.py"' import subprocess cmd = ["ls", "-l"] # cmd = "ls -l" p = subprocess.Popen(cmd, # shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (s_out, s_err) = p.communicate() print "Std_out returns:\n%s\nStd_err returns:\n%s\n"%\ (s_out, s_err, ) From bgailer at gmail.com Sun Mar 10 19:03:40 2013 From: bgailer at gmail.com (bob gailer) Date: Sun, 10 Mar 2013 14:03:40 -0400 Subject: [Tutor] Problem with Fibonacci example In-Reply-To: <513C30F1.4090703@gmail.com> References: <51317AC6.7090905@gmail.com> <5132AC00.4010808@gmail.com> <5132CAE8.7040204@gmail.com> <51333A1B.8000400@gmail.com> <5133A405.2050804@gmail.com> <51348C06.5050805@gmail.com> <5134DDA5.4070506@gmail.com> <51371900.1070609@gmail.com> <513775DD.2030402@gmail.com> <513874F5.5040501@gmail.com> <5138B68A.4050301@gmail.com> <513C30F1.4090703@gmail.com> Message-ID: <513CCAFC.5040405@gmail.com> On 3/10/2013 3:06 AM, bessenkphilip wrote: > Hello Bob, > Hi. When you have a Python question that is not related to Python Pipelines I suggest you send it to the tutor group.I and others will see it and you will get faster help. > While trying one Fibonacci example in tutorial, i'm having some > doubts. The program is as below > >>> a, b = 0, 1 > >>> while b < 10: > ... print b > ... a, b = b, a+b > > Here i tried the last line as separate lines as: > a = b > b = a + b > > but it returned an error in the first line itself( a = b) Always post the traceback. I can't help you here without that. Also show the program, or sequence of statements entered at >>>. > From the c programs, i think we use a variable "c" for assigning such > that "a = b" and "b =c" where 'c' is the sum of (a+b). > > In the python example, the line .. a, b = b, a+b > i interpreted this as "a = b" and "b = a + b" but as the c programs, > won't 'a' already got b's value first.? if that then the line " b =a > +b" will be like 'b= b + b" (as a already got b's value) Python evaluates what's on the right side of the = first. b, a+b is an expression list. The result (the first time) is a tuple (1, 0+1) which is (1, 1). Then it evaluates the assignment (=). SInce the target is 2 variables it "unpacks" the tuple. The result is a = 1 b = 1 -- Bob Gailer 919-636-4239 Chapel Hill NC From jsf80238 at gmail.com Sun Mar 10 21:31:17 2013 From: jsf80238 at gmail.com (Jason Friedman) Date: Sun, 10 Mar 2013 14:31:17 -0600 Subject: [Tutor] Use __str__ method for int values In-Reply-To: <1362905836.72302.YahooMailNeo@web164905.mail.bf1.yahoo.com> References: <1362905836.72302.YahooMailNeo@web164905.mail.bf1.yahoo.com> Message-ID: > I am trying to use a __str__ method to display the values of attribute mood > = self.hunger + self. boredom. > When I try to execute I get this error: > > Traceback (most recent call last): > File "C:/Users/Vincent/Documents/Programming Tutorials/Python Programming > for the Absolute Beginner - Project > Files/source/chapter08/critter_caretaker_vpb3.py", line 105, in > main() > File "C:/Users/Vincent/Documents/Programming Tutorials/Python Programming > for the Absolute Beginner - Project > Files/source/chapter08/critter_caretaker_vpb3.py", line 99, in main > print(crit) > TypeError: __str__ returned non-string (type int) > def __str__(self): > mood = self.boredom + self.hunger > return mood I believe the problem is that your __str__ method returns an int rather than a string. Try: mood = str(self.boredom + self.hunger) From bfishbein79 at gmail.com Sun Mar 10 22:42:59 2013 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Sun, 10 Mar 2013 16:42:59 -0500 Subject: [Tutor] python on ipad Message-ID: <315460BC-0389-4E18-B7EF-0C4E1D7CA47E@gmail.com> Hello. I wrote some python programs for my small business that I run on my computer...macbook air. I'm planning to backpack around Mexico and perhaps south america. I'll still be working though. Basically my computer does all the work, I just need to have internet connections and run the programs, and periodically click here and there. I don't want to take my macbook with me because I'd have anxiety that it'd get stolen and I wouldn't have any fun. So I'm debating if I should get a cheap computer for a couple hundred bucks and run the python scripts on it. I think this is possible because I hear the code is the same whether it's mac or PC or whatever. Or I might take my ipad with me. Or just run it on my iphone. Do you know if it's possible to run python scripts on a ipad/iphone, and if so how to do it? Thanks, Ben From svenito at gmail.com Sun Mar 10 23:18:25 2013 From: svenito at gmail.com (Sven) Date: Sun, 10 Mar 2013 22:18:25 +0000 Subject: [Tutor] python on ipad In-Reply-To: <315460BC-0389-4E18-B7EF-0C4E1D7CA47E@gmail.com> References: <315460BC-0389-4E18-B7EF-0C4E1D7CA47E@gmail.com> Message-ID: On 10 March 2013 21:42, Benjamin Fishbein wrote: > Hello. I wrote some python programs for my small business that I run on my > computer...macbook air. I'm planning to backpack around Mexico and perhaps > south america. I'll still be working though. Basically my computer does all > the work, I just need to have internet connections and run the programs, > and periodically click here and there. > I don't want to take my macbook with me because I'd have anxiety that it'd > get stolen and I wouldn't have any fun. > So I'm debating if I should get a cheap computer for a couple hundred > bucks and run the python scripts on it. I think this is possible because I > hear the code is the same whether it's mac or PC or whatever. > Or I might take my ipad with me. Or just run it on my iphone. > Do you know if it's possible to run python scripts on a ipad/iphone, and > if so how to do it? > > Do these scripts have GUIs or are they just CLI scripts? If they are CLI scripts then you can certainly run them on a jailbroken device http://www.rioleo.org/python-on-the-ipad.php or if you don't want to jailbreak http://omz-software.com/pythonista/ although I have no idea how featured that is. Hope that helps -- ./Sven -------------- next part -------------- An HTML attachment was scrubbed... URL: From fsalamero at gmail.com Sun Mar 10 23:52:34 2013 From: fsalamero at gmail.com (Fernando Salamero) Date: Sun, 10 Mar 2013 23:52:34 +0100 Subject: [Tutor] python on ipad In-Reply-To: References: Message-ID: Sure. Pythonista is a must have. https://itunes.apple.com/es/app/pythonista/id528579881?mt=8 > Date: Sun, 10 Mar 2013 16:42:59 -0500 > From: Benjamin Fishbein > To: *tutor python > Subject: [Tutor] python on ipad > Message-ID: <315460BC-0389-4E18-B7EF-0C4E1D7CA47E at gmail.com> > Content-Type: text/plain; charset=us-ascii > > Hello. I wrote some python programs for my small business that I run on my computer...macbook air. I'm planning to backpack around Mexico and perhaps south america. I'll still be working though. Basically my computer does all the work, I just need to have internet connections and run the programs, and periodically click here and there. > I don't want to take my macbook with me because I'd have anxiety that it'd get stolen and I wouldn't have any fun. > So I'm debating if I should get a cheap computer for a couple hundred bucks and run the python scripts on it. I think this is possible because I hear the code is the same whether it's mac or PC or whatever. > Or I might take my ipad with me. Or just run it on my iphone. > Do you know if it's possible to run python scripts on a ipad/iphone, and if so how to do it? > Thanks, > Ben From wrw at mac.com Mon Mar 11 00:07:32 2013 From: wrw at mac.com (William Ray Wing) Date: Sun, 10 Mar 2013 19:07:32 -0400 Subject: [Tutor] python on ipad In-Reply-To: References: <315460BC-0389-4E18-B7EF-0C4E1D7CA47E@gmail.com> Message-ID: <3B32D5FA-77C1-4F3E-9DFB-DA2225BB3B28@mac.com> On Mar 10, 2013, at 6:18 PM, Sven wrote: > On 10 March 2013 21:42, Benjamin Fishbein wrote: > Hello. I wrote some python programs for my small business that I run on my computer...macbook air. I'm planning to backpack around Mexico and perhaps south america. I'll still be working though. Basically my computer does all the work, I just need to have internet connections and run the programs, and periodically click here and there. > I don't want to take my macbook with me because I'd have anxiety that it'd get stolen and I wouldn't have any fun. > So I'm debating if I should get a cheap computer for a couple hundred bucks and run the python scripts on it. I think this is possible because I hear the code is the same whether it's mac or PC or whatever. > Or I might take my ipad with me. Or just run it on my iphone. > Do you know if it's possible to run python scripts on a ipad/iphone, and if so how to do it? > > > Do these scripts have GUIs or are they just CLI scripts? > > If they are CLI scripts then you can certainly run them on a jailbroken device > http://www.rioleo.org/python-on-the-ipad.php > > or if you don't want to jailbreak http://omz-software.com/pythonista/ > > although I have no idea how featured that is. > I have Pythonista on my iPad, and it seems to be a pretty complete implementation of Python and the standard libraries. It doesn't have Tkinter or ttk, but does have a "scene" library that supports GUI interfaces and games. It has a fairly active discussion forum and if you Google Pythonista you will get hits to several reviews - all positive. At $6.95, it would be worth checking out. Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Mon Mar 11 00:15:01 2013 From: eryksun at gmail.com (eryksun) Date: Sun, 10 Mar 2013 19:15:01 -0400 Subject: [Tutor] subprocess module: when to _NOT_ use shell=True In-Reply-To: References: Message-ID: On Sun, Mar 10, 2013 at 12:56 PM, wrote: > I've not found anywhere a clear explanation of when not to > set shell=True. If the command line must be interpreted by > the shell then clearly this must be set. So the question > that comes up is why not set it always? Using the shell can be a security risk for untrusted commands, as described in the 3.3 docs for shlex.quote: http://docs.python.org/3/library/shlex#shlex.quote > I came up with the following script that indicates that > the shell looks at only the first string in the array if > the first parameter is an array rather than a string. > Switching between cmd being a string vs an array and shell > being set or not set gives 4 possibilities. > > cmd = ["ls", "-l"] > # cmd = "ls -l" On a POSIX system, when you use an ags string instead of a list with Popen, it just adds the string to a list, which varies depending on the "shell" argument. Starting a new process using fork/exec hasn't fundamentally changed since the early Unix systems in the 1970s. A child process is forked and executes a new process image, with the given arguments in an array of pointers to strings. Popen uses uses os.fork and os.execvp (or os.execvpe if you supply an environment). http://docs.python.org/2/library/os#os.fork http://docs.python.org/2/library/os#os.execvp http://en.wikipedia.org/wiki/Exec_%28operating_system%29 If shell=False, use the args list ["ls", "-l"]. Otherwise, if you use an args string, Popen creates the list ["ls -l"], and execvp will look for a file named "ls -l". Here's a silly example: >>> import os >>> from subprocess import Popen >>> os.environ['PATH'] += ':.' >>> open('ls -l', 'w').write('''\ ... #!/bin/bash ... echo silliness''') >>> os.chmod('ls -l', 0700) >>> p = Popen('ls -l') >>> silliness If shell=True and the command is the string "ls -l", Popen uses the args list ["/bin/sh", "-c", "ls -l"]. This is equivalent to running the following: /bin/sh -c 'ls -l' This will work as expected. If you instead use the list ["ls", "-l"], Popen uses the args list ["/bin/sh", "-c", "ls", "-l"], which is equivalent to running the following: /bin/sh -c ls -l You can verify that the above doesn't work (the '-l' option isn't passed to ls). Here's an example to echo the parameters: >>> open('tmp.sh', 'w').write(''' ... #!/bin/bash ... echo $0, $1, $2''') >>> os.chmod('tmp.sh', 0700) >>> env = {'PATH':'.'} >>> p = Popen('tmp.sh p1 p2', shell=True, env=env) >>> ./tmp.sh, p1, p2 That worked fine, but this fails: >>> p = Popen(['tmp.sh','p1','p2'], shell=True, env=env) >>> ./tmp.sh, , From eike.welk.lists1 at gmx.de Mon Mar 11 00:27:39 2013 From: eike.welk.lists1 at gmx.de (Eike Welk) Date: Mon, 11 Mar 2013 00:27:39 +0100 Subject: [Tutor] subprocess module: when to _NOT_ use shell=True In-Reply-To: References: Message-ID: <2781446.FQqPdLVjh9@lixie> On Sunday 10.03.2013 09:56:26 akleider at sonic.net wrote: > I've not found anywhere a clear explanation of when not to set shell=True. > If the command line must be interpreted by the shell then clearly this > must be set. So the question that comes up is why not set it always? Because ``shell=True`` is a security problem. It it is also not portable. Someone might want to run your code on windows, which has no Bash. The security problem arises when the command contains any user input. The user could enter a bit of carefully crafted text, that tricks Bash into doing something that you don't want. The technique is called "shell code injection". The nicest example is the "Bobby tables" episode from XKCD, that covers a similar situation with SQL injection: http://www.explainxkcd.com/wiki/index.php?title=327:_Exploits_of_a_Mom And on Wikipedia: http://en.wikipedia.org/wiki/Code_injection#Shell_injection -- Eike. From steevoyang at gmail.com Mon Mar 11 00:30:07 2013 From: steevoyang at gmail.com (Stephen Yang) Date: Sun, 10 Mar 2013 19:30:07 -0400 Subject: [Tutor] Tutor Digest, Vol 109, Issue 29 In-Reply-To: References: Message-ID: please unsubscribe On Sun, Mar 10, 2013 at 7:27 PM, 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: python on ipad (Sven) > 2. Re: python on ipad (Fernando Salamero) > 3. Re: python on ipad (William Ray Wing) > 4. Re: subprocess module: when to _NOT_ use shell=True (eryksun) > 5. Re: subprocess module: when to _NOT_ use shell=True (Eike Welk) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sun, 10 Mar 2013 22:18:25 +0000 > From: Sven > To: Benjamin Fishbein > Cc: *tutor python > Subject: Re: [Tutor] python on ipad > Message-ID: > ZWw at mail.gmail.com> > Content-Type: text/plain; charset="iso-8859-1" > > On 10 March 2013 21:42, Benjamin Fishbein wrote: > > > Hello. I wrote some python programs for my small business that I run on > my > > computer...macbook air. I'm planning to backpack around Mexico and > perhaps > > south america. I'll still be working though. Basically my computer does > all > > the work, I just need to have internet connections and run the programs, > > and periodically click here and there. > > I don't want to take my macbook with me because I'd have anxiety that > it'd > > get stolen and I wouldn't have any fun. > > So I'm debating if I should get a cheap computer for a couple hundred > > bucks and run the python scripts on it. I think this is possible because > I > > hear the code is the same whether it's mac or PC or whatever. > > Or I might take my ipad with me. Or just run it on my iphone. > > Do you know if it's possible to run python scripts on a ipad/iphone, and > > if so how to do it? > > > > > Do these scripts have GUIs or are they just CLI scripts? > > If they are CLI scripts then you can certainly run them on a jailbroken > device > http://www.rioleo.org/python-on-the-ipad.php > > or if you don't want to jailbreak http://omz-software.com/pythonista/ > > although I have no idea how featured that is. > > Hope that helps > > -- > ./Sven > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20130310/cde6716d/attachment-0001.html > > > > ------------------------------ > > Message: 2 > Date: Sun, 10 Mar 2013 23:52:34 +0100 > From: Fernando Salamero > To: "tutor at python.org" > Subject: Re: [Tutor] python on ipad > Message-ID: > Content-Type: text/plain; charset=us-ascii > > Sure. Pythonista is a must have. > > > https://itunes.apple.com/es/app/pythonista/id528579881?mt=8 > > > > Date: Sun, 10 Mar 2013 16:42:59 -0500 > > From: Benjamin Fishbein > > To: *tutor python > > Subject: [Tutor] python on ipad > > Message-ID: <315460BC-0389-4E18-B7EF-0C4E1D7CA47E at gmail.com> > > Content-Type: text/plain; charset=us-ascii > > > > Hello. I wrote some python programs for my small business that I run on > my computer...macbook air. I'm planning to backpack around Mexico and > perhaps south america. I'll still be working though. Basically my computer > does all the work, I just need to have internet connections and run the > programs, and periodically click here and there. > > I don't want to take my macbook with me because I'd have anxiety that > it'd get stolen and I wouldn't have any fun. > > So I'm debating if I should get a cheap computer for a couple hundred > bucks and run the python scripts on it. I think this is possible because I > hear the code is the same whether it's mac or PC or whatever. > > Or I might take my ipad with me. Or just run it on my iphone. > > Do you know if it's possible to run python scripts on a ipad/iphone, and > if so how to do it? > > Thanks, > > Ben > > > ------------------------------ > > Message: 3 > Date: Sun, 10 Mar 2013 19:07:32 -0400 > From: William Ray Wing > To: Sven > Cc: *tutor python , William Ray Wing > Subject: Re: [Tutor] python on ipad > Message-ID: <3B32D5FA-77C1-4F3E-9DFB-DA2225BB3B28 at mac.com> > Content-Type: text/plain; charset="iso-8859-1" > > On Mar 10, 2013, at 6:18 PM, Sven wrote: > > > On 10 March 2013 21:42, Benjamin Fishbein wrote: > > Hello. I wrote some python programs for my small business that I run on > my computer...macbook air. I'm planning to backpack around Mexico and > perhaps south america. I'll still be working though. Basically my computer > does all the work, I just need to have internet connections and run the > programs, and periodically click here and there. > > I don't want to take my macbook with me because I'd have anxiety that > it'd get stolen and I wouldn't have any fun. > > So I'm debating if I should get a cheap computer for a couple hundred > bucks and run the python scripts on it. I think this is possible because I > hear the code is the same whether it's mac or PC or whatever. > > Or I might take my ipad with me. Or just run it on my iphone. > > Do you know if it's possible to run python scripts on a ipad/iphone, and > if so how to do it? > > > > > > Do these scripts have GUIs or are they just CLI scripts? > > > > If they are CLI scripts then you can certainly run them on a jailbroken > device > > http://www.rioleo.org/python-on-the-ipad.php > > > > or if you don't want to jailbreak http://omz-software.com/pythonista/ > > > > although I have no idea how featured that is. > > > > I have Pythonista on my iPad, and it seems to be a pretty complete > implementation of Python and the standard libraries. It doesn't have > Tkinter or ttk, but does have a "scene" library that supports GUI > interfaces and games. It has a fairly active discussion forum and if you > Google Pythonista you will get hits to several reviews - all positive. At > $6.95, it would be worth checking out. > > Bill > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20130310/1ebffe26/attachment-0001.html > > > > ------------------------------ > > Message: 4 > Date: Sun, 10 Mar 2013 19:15:01 -0400 > From: eryksun > To: akleider at sonic.net > Cc: tutor at python.org > Subject: Re: [Tutor] subprocess module: when to _NOT_ use shell=True > Message-ID: > mN6w at mail.gmail.com> > Content-Type: text/plain; charset=UTF-8 > > On Sun, Mar 10, 2013 at 12:56 PM, wrote: > > I've not found anywhere a clear explanation of when not to > > set shell=True. If the command line must be interpreted by > > the shell then clearly this must be set. So the question > > that comes up is why not set it always? > > Using the shell can be a security risk for untrusted commands, as > described in the 3.3 docs for shlex.quote: > > http://docs.python.org/3/library/shlex#shlex.quote > > > I came up with the following script that indicates that > > the shell looks at only the first string in the array if > > the first parameter is an array rather than a string. > > Switching between cmd being a string vs an array and shell > > being set or not set gives 4 possibilities. > > > > cmd = ["ls", "-l"] > > # cmd = "ls -l" > > On a POSIX system, when you use an ags string instead of a list with > Popen, it just adds the string to a list, which varies depending on > the "shell" argument. > > Starting a new process using fork/exec hasn't fundamentally changed > since the early Unix systems in the 1970s. A child process is forked > and executes a new process image, with the given arguments in an array > of pointers to strings. Popen uses uses os.fork and os.execvp (or > os.execvpe if you supply an environment). > > http://docs.python.org/2/library/os#os.fork > http://docs.python.org/2/library/os#os.execvp > > http://en.wikipedia.org/wiki/Exec_%28operating_system%29 > > If shell=False, use the args list ["ls", "-l"]. Otherwise, if you use > an args string, Popen creates the list ["ls -l"], and execvp will look > for a file named "ls -l". Here's a silly example: > > >>> import os > >>> from subprocess import Popen > > >>> os.environ['PATH'] += ':.' > >>> open('ls -l', 'w').write('''\ > ... #!/bin/bash > ... echo silliness''') > >>> os.chmod('ls -l', 0700) > >>> p = Popen('ls -l') > >>> silliness > > If shell=True and the command is the string "ls -l", Popen uses the > args list ["/bin/sh", "-c", "ls -l"]. This is equivalent to running > the following: > > /bin/sh -c 'ls -l' > > This will work as expected. If you instead use the list ["ls", "-l"], > Popen uses the args list ["/bin/sh", "-c", "ls", "-l"], which is > equivalent to running the following: > > /bin/sh -c ls -l > > You can verify that the above doesn't work (the '-l' option isn't > passed to ls). Here's an example to echo the parameters: > > >>> open('tmp.sh', 'w').write(''' > ... #!/bin/bash > ... echo $0, $1, $2''') > >>> os.chmod('tmp.sh', 0700) > >>> env = {'PATH':'.'} > > >>> p = Popen('tmp.sh p1 p2', shell=True, env=env) > >>> ./tmp.sh, p1, p2 > > That worked fine, but this fails: > > >>> p = Popen(['tmp.sh','p1','p2'], shell=True, env=env) > >>> ./tmp.sh, , > > > ------------------------------ > > Message: 5 > Date: Mon, 11 Mar 2013 00:27:39 +0100 > From: Eike Welk > To: tutor at python.org > Subject: Re: [Tutor] subprocess module: when to _NOT_ use shell=True > Message-ID: <2781446.FQqPdLVjh9 at lixie> > Content-Type: text/plain; charset="us-ascii" > > On Sunday 10.03.2013 09:56:26 akleider at sonic.net wrote: > > I've not found anywhere a clear explanation of when not to set > shell=True. > > If the command line must be interpreted by the shell then clearly this > > must be set. So the question that comes up is why not set it always? > > Because ``shell=True`` is a security problem. It it is also not portable. > Someone might want to run your code on windows, which has no Bash. > > The security problem arises when the command contains any user input. The > user > could enter a bit of carefully crafted text, that tricks Bash into doing > something that you don't want. The technique is called "shell code > injection". > > The nicest example is the "Bobby tables" episode from XKCD, that covers a > similar situation with SQL injection: > > http://www.explainxkcd.com/wiki/index.php?title=327:_Exploits_of_a_Mom > > And on Wikipedia: > > http://en.wikipedia.org/wiki/Code_injection#Shell_injection > > > -- > Eike. > > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 109, Issue 29 > ************************************** > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jsf80238 at gmail.com Mon Mar 11 00:44:58 2013 From: jsf80238 at gmail.com (Jason Friedman) Date: Sun, 10 Mar 2013 17:44:58 -0600 Subject: [Tutor] Use __str__ method for int values In-Reply-To: <1362956526.36806.YahooMailNeo@web164903.mail.bf1.yahoo.com> References: <1362905836.72302.YahooMailNeo@web164905.mail.bf1.yahoo.com> <1362956526.36806.YahooMailNeo@web164903.mail.bf1.yahoo.com> Message-ID: > Thank you for the response! I next modified the __str__ so it will also > include the values self. boredom and self. hunger. I am getting a bit > confused with how to set up strings from within a method. It is set up like > this: > > def __str__(self): > attrs = "Hunger: ", self.hunger, "Boredom: ", self.boredom, "Mood: > ", self.boredom + self.hunger > return attrs > > When I try to execute I get this: > > Traceback (most recent call last): > File "C:\Users\Vincent\Documents\Programming Tutorials\Python Programming > for the Absolute Beginner - Project > Files\source\chapter08\critter_caretaker_vpb3.py", line 105, in > main() > File "C:\Users\Vincent\Documents\Programming Tutorials\Python Programming > for the Absolute Beginner - Project > Files\source\chapter08\critter_caretaker_vpb3.py", line 99, in main > print(crit) > TypeError: __str__ returned non-string (type tuple) The print statement (at least in 2.7) accepts arguments separated by commas, but ordinary assignment gives a different result: >>> a = "str", "ing" >>> a ('str', 'ing') So, you probably want something like: attrs = "Hunger: %s Boredom: %s Mood: %s" % (self.hunger, self.boredom, self.boredom + self.hunger) From bfishbein79 at gmail.com Mon Mar 11 01:02:46 2013 From: bfishbein79 at gmail.com (Ben Fishbein) Date: Sun, 10 Mar 2013 19:02:46 -0500 Subject: [Tutor] python on ipad In-Reply-To: <3B32D5FA-77C1-4F3E-9DFB-DA2225BB3B28@mac.com> References: <315460BC-0389-4E18-B7EF-0C4E1D7CA47E@gmail.com> <3B32D5FA-77C1-4F3E-9DFB-DA2225BB3B28@mac.com> Message-ID: <7EB64E6A-D6AC-4F7D-87DF-FACDB171F409@gmail.com> Thanks. Pythonista looks good. Do you know if it can use any module? Besides the standard libraries that come with python I also use selenium. I'm not sure if it would work with pythonista. In my mac selenium needs at least python 2.7. I wasn't able to get selenium to work for a while and it turned out it was because I was using python 2.5. I also need read from and write to txt files as part of the algorithm. Do I need another app that does txt files? Sent from my iPad On Mar 10, 2013, at 6:07 PM, William Ray Wing wrote: > On Mar 10, 2013, at 6:18 PM, Sven wrote: > >> On 10 March 2013 21:42, Benjamin Fishbein wrote: >>> Hello. I wrote some python programs for my small business that I run on my computer...macbook air. I'm planning to backpack around Mexico and perhaps south america. I'll still be working though. Basically my computer does all the work, I just need to have internet connections and run the programs, and periodically click here and there. >>> I don't want to take my macbook with me because I'd have anxiety that it'd get stolen and I wouldn't have any fun. >>> So I'm debating if I should get a cheap computer for a couple hundred bucks and run the python scripts on it. I think this is possible because I hear the code is the same whether it's mac or PC or whatever. >>> Or I might take my ipad with me. Or just run it on my iphone. >>> Do you know if it's possible to run python scripts on a ipad/iphone, and if so how to do it? >> >> Do these scripts have GUIs or are they just CLI scripts? >> >> If they are CLI scripts then you can certainly run them on a jailbroken device >> http://www.rioleo.org/python-on-the-ipad.php >> >> or if you don't want to jailbreak http://omz-software.com/pythonista/ >> >> although I have no idea how featured that is. > > I have Pythonista on my iPad, and it seems to be a pretty complete implementation of Python and the standard libraries. It doesn't have Tkinter or ttk, but does have a "scene" library that supports GUI interfaces and games. It has a fairly active discussion forum and if you Google Pythonista you will get hits to several reviews - all positive. At $6.95, it would be worth checking out. > > Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From bfishbein79 at gmail.com Mon Mar 11 01:03:40 2013 From: bfishbein79 at gmail.com (Ben Fishbein) Date: Sun, 10 Mar 2013 19:03:40 -0500 Subject: [Tutor] python on ipad In-Reply-To: <3B32D5FA-77C1-4F3E-9DFB-DA2225BB3B28@mac.com> References: <315460BC-0389-4E18-B7EF-0C4E1D7CA47E@gmail.com> <3B32D5FA-77C1-4F3E-9DFB-DA2225BB3B28@mac.com> Message-ID: <04D526B7-E91C-481F-ADB4-5DE4C5993BC3@gmail.com> Btw I don't have any GUI so that's not an issue. Sent from my iPad On Mar 10, 2013, at 6:07 PM, William Ray Wing wrote: > On Mar 10, 2013, at 6:18 PM, Sven wrote: > >> On 10 March 2013 21:42, Benjamin Fishbein wrote: >>> Hello. I wrote some python programs for my small business that I run on my computer...macbook air. I'm planning to backpack around Mexico and perhaps south america. I'll still be working though. Basically my computer does all the work, I just need to have internet connections and run the programs, and periodically click here and there. >>> I don't want to take my macbook with me because I'd have anxiety that it'd get stolen and I wouldn't have any fun. >>> So I'm debating if I should get a cheap computer for a couple hundred bucks and run the python scripts on it. I think this is possible because I hear the code is the same whether it's mac or PC or whatever. >>> Or I might take my ipad with me. Or just run it on my iphone. >>> Do you know if it's possible to run python scripts on a ipad/iphone, and if so how to do it? >> >> Do these scripts have GUIs or are they just CLI scripts? >> >> If they are CLI scripts then you can certainly run them on a jailbroken device >> http://www.rioleo.org/python-on-the-ipad.php >> >> or if you don't want to jailbreak http://omz-software.com/pythonista/ >> >> although I have no idea how featured that is. > > I have Pythonista on my iPad, and it seems to be a pretty complete implementation of Python and the standard libraries. It doesn't have Tkinter or ttk, but does have a "scene" library that supports GUI interfaces and games. It has a fairly active discussion forum and if you Google Pythonista you will get hits to several reviews - all positive. At $6.95, it would be worth checking out. > > Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From outta.names at gmail.com Mon Mar 11 01:16:17 2013 From: outta.names at gmail.com (Dave Friedman) Date: Sun, 10 Mar 2013 20:16:17 -0400 Subject: [Tutor] 'Last' in Python? Message-ID: Hi all, I'm teaching myself Python in part with Google's course, and one of the exercises is to sort a list of tuples by the last element. e.g.: a list [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields [(2, 2), (1, 3), (3, 4, 5), (1, 7)]. My answer, after figuring out lambda functions, is def sort_last(tuples): return sorted(tuples, key= lambda t: t[-1]) Google's answer is much more straightforward, except for one part. def sort_last(tuples) return sorted(tuples, key=last) What is 'last', and where can I find a description of it? Searching the web and the python docs hasn't been helpful. (Maybe I'm searching badly?) Insight and pointers appreciated. Thanks, -Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From msirenef at lightbird.net Mon Mar 11 01:30:48 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Sun, 10 Mar 2013 20:30:48 -0400 Subject: [Tutor] 'Last' in Python? In-Reply-To: References: Message-ID: <513D25B8.2000904@lightbird.net> On 03/10/2013 08:16 PM, Dave Friedman wrote: > Hi all, > > I'm teaching myself Python in part with Google's course, and one of the exercises is to sort a list of tuples by the last element. > e.g.: a list [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields [(2, 2), (1, 3), (3, 4, 5), (1, 7)]. > > My answer, after figuring out lambda functions, is > def sort_last(tuples): > return sorted(tuples, key= lambda t: t[-1]) > > Google's answer is much more straightforward, except for one part. > def sort_last(tuples) > return sorted(tuples, key=last) > > What is 'last', and where can I find a description of it? Searching the web and the python docs hasn't been helpful. (Maybe I'm searching badly?) > Insight and pointers appreciated. > > Thanks, > -Dave > There is no such python builtin. I would use operator.itemgetter: from operator import itemgetter return sorted(tuples, key=itemgetter(-1)) -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Oaths are the fossils of piety. George Santayana From breamoreboy at yahoo.co.uk Mon Mar 11 01:38:06 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 11 Mar 2013 00:38:06 +0000 Subject: [Tutor] 'Last' in Python? In-Reply-To: References: Message-ID: On 11/03/2013 00:16, Dave Friedman wrote: > Hi all, > > I'm teaching myself Python in part with Google's course, and one of the > exercises is to sort a list of tuples by the last element. > e.g.: a list [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields [(2, 2), (1, 3), > (3, 4, 5), (1, 7)]. > > My answer, after figuring out lambda functions, is > def sort_last(tuples): > return sorted(tuples, key= lambda t: t[-1]) > > Google's answer is much more straightforward, except for one part. > def sort_last(tuples) > return sorted(tuples, key=last) > > What is 'last', and where can I find a description of it? Searching the > web and the python docs hasn't been helpful. (Maybe I'm searching badly?) > Insight and pointers appreciated. > > Thanks, > -Dave > > 'last' is a user defined function that does exactly the same as your lamdba function as shown here https://github.com/megantaylor/Google-Python-Exercises/blob/master/list1.py -- Cheers. Mark Lawrence From alan.gauld at btinternet.com Mon Mar 11 02:31:23 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Mar 2013 01:31:23 +0000 Subject: [Tutor] python on ipad In-Reply-To: <315460BC-0389-4E18-B7EF-0C4E1D7CA47E@gmail.com> References: <315460BC-0389-4E18-B7EF-0C4E1D7CA47E@gmail.com> Message-ID: On 10/03/13 21:42, Benjamin Fishbein wrote: > Hello. I wrote some python programs for my small business that I run on my computer...macbook > ...I should get a cheap computer for a couple hundred bucks and run the python scripts on it. > I think this is possible because I hear the code is the same whether it's mac or PC or whatever. It depends, most code is portable but some things, especially OS related, are not. If you stick with Apple or Linux you will probably be OK but Windows might cause problems. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Mar 11 02:32:40 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Mar 2013 01:32:40 +0000 Subject: [Tutor] Tutor Digest, Vol 109, Issue 29 In-Reply-To: References: Message-ID: On 10/03/13 23:30, Stephen Yang wrote: > please unsubscribe > Nope, I like it here. But you can unsubscribe by following the instructions in the message you sent... > > 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 > -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From hgfernan at gmail.com Mon Mar 11 03:25:45 2013 From: hgfernan at gmail.com (Hilton Fernandes) Date: Sun, 10 Mar 2013 23:25:45 -0300 Subject: [Tutor] python on ipad In-Reply-To: <315460BC-0389-4E18-B7EF-0C4E1D7CA47E@gmail.com> References: <315460BC-0389-4E18-B7EF-0C4E1D7CA47E@gmail.com> Message-ID: Hi ! If you don't mind, a non technical recommendation: maybe you should consider a cheaper, low end Android smartphone. An iPad will attract the attention of robbers everywhere: it's small, it's expansive and it's fancy. The training 'Developing Android Apps completely in Python', at https://ep2013.europython.eu/conference/talks/developing-android-apps-completely-in-python seems to be a good starting point on using Python under Android. All the best, hilton On Sun, Mar 10, 2013 at 6:42 PM, Benjamin Fishbein wrote: > Hello. I wrote some python programs for my small business that I run on my > computer...macbook air. I'm planning to backpack around Mexico and perhaps > south america. I'll still be working though. Basically my computer does all > the work, I just need to have internet connections and run the programs, > and periodically click here and there. > I don't want to take my macbook with me because I'd have anxiety that it'd > get stolen and I wouldn't have any fun. > So I'm debating if I should get a cheap computer for a couple hundred > bucks and run the python scripts on it. I think this is possible because I > hear the code is the same whether it's mac or PC or whatever. > Or I might take my ipad with me. Or just run it on my iphone. > Do you know if it's possible to run python scripts on a ipad/iphone, and > if so how to do it? > Thanks, > Ben > > _______________________________________________ > 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 steve at pearwood.info Mon Mar 11 07:14:06 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 11 Mar 2013 17:14:06 +1100 Subject: [Tutor] Tutor Digest, Vol 109, Issue 29 In-Reply-To: References: Message-ID: <513D762E.4090304@pearwood.info> On 11/03/13 10:30, Stephen Yang wrote: > please unsubscribe You subscribed yourself. You can unsubscribe yourself by following the instructions here: >> 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 -- Steven From dyoo at hashcollision.org Mon Mar 11 07:33:52 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Sun, 10 Mar 2013 23:33:52 -0700 Subject: [Tutor] Bar Operator ?? In-Reply-To: <513BE68B.9050303@lightbird.net> References: <513BE68B.9050303@lightbird.net> Message-ID: > > It's a filter: > > https://docs.djangoproject.com/en/1.5/ref/templates/builtins/ And to be explicit about Mitya's point: it's technically not Python. It's part of Django's template language. If it were Python, it'd be interpreted as the "or" bitwise operator, http://docs.python.org/3/reference/expressions.html#binary-bitwise-operations but that's definitely not what's happening here. In your context, as part of a Django template document, interpret "|" as notation for the filtering operation. From mlybrand at gmail.com Mon Mar 11 08:23:35 2013 From: mlybrand at gmail.com (Mark Lybrand) Date: Mon, 11 Mar 2013 00:23:35 -0700 Subject: [Tutor] Bar Operator ?? In-Reply-To: References: <513BE68B.9050303@lightbird.net> Message-ID: Thanks. I think I kind of get it. It probably will take a while for the nuances of the filter to sink. Some things are filters that don't seem like they should be, but that seems like my problem. Mark :) On Sun, Mar 10, 2013 at 11:33 PM, Danny Yoo wrote: > > > > It's a filter: > > > > https://docs.djangoproject.com/en/1.5/ref/templates/builtins/ > > And to be explicit about Mitya's point: it's technically not Python. > It's part of Django's template language. If it were Python, it'd be > interpreted as the "or" bitwise operator, > > > http://docs.python.org/3/reference/expressions.html#binary-bitwise-operations > > but that's definitely not what's happening here. In your context, as > part of a Django template document, interpret "|" as notation for the > filtering operation. > -- Mark :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From phil_lor at bigpond.com Mon Mar 11 09:24:09 2013 From: phil_lor at bigpond.com (Phil) Date: Mon, 11 Mar 2013 18:24:09 +1000 Subject: [Tutor] Print to file Message-ID: <513D94A9.5090500@bigpond.com> The usage of print to file is much like the Arduino print to serial device and it's got me curious to know what the correct syntax is. Neither of the following is correct, but the second one seems closer to the mark. >>> print("test", file="/home/phil/Python/words") Traceback (most recent call last): File "", line 1, in AttributeError: 'str' object has no attribute 'write' >>> f = open("/home/phil/Python/words", 'w') >>> print("test", file=f I've used the "with" statement to write and read files but print to file could be handy some time. -- Regards, Phil From hugo.yoshi at gmail.com Mon Mar 11 09:35:18 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Mon, 11 Mar 2013 09:35:18 +0100 Subject: [Tutor] Print to file In-Reply-To: <513D94A9.5090500@bigpond.com> References: <513D94A9.5090500@bigpond.com> Message-ID: On Mon, Mar 11, 2013 at 9:24 AM, Phil wrote: > The usage of print to file is much like the Arduino print to serial device > and it's got me curious to know what the correct syntax is. Neither of the > following is correct, but the second one seems closer to the mark. > > >>> print("test", file="/home/phil/Python/words"**) > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'str' object has no attribute 'write' > > >>> f = open("/home/phil/Python/words"**, 'w') > >>> print("test", file=f > > I've used the "with" statement to write and read files but print to file > could be handy some time. The second one should be correct, if you add the closing parenthesis of print. Closing the file afterwards is not strictly required, I think, though it is good practice. Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Mar 11 10:44:33 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 11 Mar 2013 09:44:33 +0000 Subject: [Tutor] Print to file In-Reply-To: <513D94A9.5090500@bigpond.com> References: <513D94A9.5090500@bigpond.com> Message-ID: On 11/03/13 08:24, Phil wrote: > Neither of the following is correct, but the second one seems closer to > the mark. > > >>> print("test", file="/home/phil/Python/words") > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'str' object has no attribute 'write' So this is obviously wrong, it reports an error. > >>> f = open("/home/phil/Python/words", 'w') > >>> print("test", file=f > But apart from the lack of a closing paren what makes you think this is wrong? What happened? > I've used the "with" statement to write and read files but print to file > could be handy some time. with is about opening files regardless of what you do to them so you could use with here too... with open(("/home/phil/Python/words", 'w') as f: print( "test", file=f) I'm not sure what you think the problem is? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From hugo.yoshi at gmail.com Mon Mar 11 11:38:40 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Mon, 11 Mar 2013 11:38:40 +0100 Subject: [Tutor] Print to file In-Reply-To: <513DA610.6020400@bigpond.com> References: <513D94A9.5090500@bigpond.com> <513DA610.6020400@bigpond.com> Message-ID: On Mon, Mar 11, 2013 at 10:38 AM, Phil wrote: > On 11/03/13 18:35, Hugo Arts wrote: > >> On Mon, Mar 11, 2013 at 9:24 AM, Phil > > wrote: >> >> The usage of print to file is much like the Arduino print to serial >> device and it's got me curious to know what the correct syntax is. >> Neither of the following is correct, but the second one seems closer >> to the mark. >> >> >>> print("test", file="/home/phil/Python/words"**__) >> >> Traceback (most recent call last): >> File "", line 1, in >> AttributeError: 'str' object has no attribute 'write' >> >> >>> f = open("/home/phil/Python/words"**__, 'w') >> >> >>> print("test", file=f >> >> I've used the "with" statement to write and read files but print to >> file could be handy some time. >> >> >> The second one should be correct, if you add the closing parenthesis of >> print. Closing the file afterwards is not strictly required, I think, >> though it is good practice. >> >> > Thanks Hugo, > > I did forget the closing parenthesis but even so the text file "words" was > created but it's empty. Make sure you "reply all" so the rest of the mailing list also gets your response. Did you exit the interpreter before checking the file contents? If not, the string you printed might still be in a buffer, waiting to be printed until the buffer is flushed. Buffers are usually flushed when they are full, when flush() is called on the buffered object, or when the object is garbage collected. Try calling f.flush() or f.close() after you print, and see if that works. Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From akleider at sonic.net Mon Mar 11 19:03:33 2013 From: akleider at sonic.net (akleider at sonic.net) Date: Mon, 11 Mar 2013 11:03:33 -0700 Subject: [Tutor] subprocess module: when to _NOT_ use shell=True In-Reply-To: References: Message-ID: Thank you "Eryksun" and "EikeWek" for your responses. It is this sort of thing that begins to pull one out of the newbie into the intermediate category. I'm grateful. alex > I've not found anywhere a clear explanation of when not to set shell=True. > If the command line must be interpreted by the shell then clearly this > must be set. So the question that comes up is why not set it always? > In an effort to investigate, I came up with the following script that > indicates that the shell looks at only the first string in the array if > the first parameter is an array rather than a string. Switching between > cmd being a string vs an array and shell being set or not set gives 4 > possibilities. > Any comments? > > #!/usr/bin/env python > > # file : test.py (Python 2.7, NOT Python 3) > # Running on Linux platform (Ubuntu.) > print 'Running "tes.py"' > > import subprocess > > cmd = ["ls", "-l"] > # cmd = "ls -l" > p = subprocess.Popen(cmd, > # shell=True, > stdout=subprocess.PIPE, > stderr=subprocess.PIPE) > (s_out, s_err) = p.communicate() > print "Std_out returns:\n%s\nStd_err returns:\n%s\n"%\ > (s_out, s_err, ) > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > From johnnyukpo at gmail.com Tue Mar 12 04:59:13 2013 From: johnnyukpo at gmail.com (akuma ukpo) Date: Mon, 11 Mar 2013 23:59:13 -0400 Subject: [Tutor] Need help with python keyboard press/navigation commands Message-ID: This is the problem Implement a function called get_direction which, on a particular character , gives the direction corresponding to that character. The correspondences are as follows:  The character ?w? corresponds to the direction ?North?  The character ?a? corresponds to the direction ?West?  The character ?s? corresponds to the direction ?South?  The character ?d? corresponds to the direction ?East? I am having difficulty coming up with a function and testing it as well. I have tried def get_direction(self): """ whenever a key is pressed the character moves to the direction corresponding to the key """ 'North':w 'South': s 'East' : d 'West' : a but it didn't work...please help. -- *Akuma* -------------- next part -------------- An HTML attachment was scrubbed... URL: From ewing.rj at gmail.com Tue Mar 12 06:57:41 2013 From: ewing.rj at gmail.com (RJ Ewing) Date: Mon, 11 Mar 2013 22:57:41 -0700 Subject: [Tutor] implementing rot 13 problems Message-ID: I am trying to implement rot 13 and am having troubles. My code is as follows: class Rot_13(webapp2.RequestHandler): def write_form(self, user=""): self.response.out.write(rot_form % user) def get(self): self.write_form() def post(self): user = self.request.get("text") s = self.rot_text(user) print s s = "".join(s) self.escape_html(s) self.write_form(s) def rot_text(self, s): ls = [i for i in s] for i in ls: if i.isalpha(): if i.isupper(): if i <= 'M': x = ls.index(i) ls[ls.index(i)] = chr(ord(i) + 13) else: x = ls.index(i) ls[ls.index(i)] = chr(ord(i) - 13) elif i.islower(): if i <= 'm': x = ls.index(i) ls[x] = chr(ord(i) + 13) elif i > 'm': x = ls.index(i) ls[x] = chr(ord(i) - 13) return ls def escape_html(self, s): return cgi.escape(s, quote = True) Now if I enter abc, I get nop. But if I enter abcdefghijklmnop, I get abcqrstuvwxyznop. I have included print statements to check if ls[x] is changing and it is, but something is going wrong when I return the ls, and I am not quite sure what it is. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Tue Mar 12 07:04:56 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 11 Mar 2013 23:04:56 -0700 Subject: [Tutor] Need help with python keyboard press/navigation commands In-Reply-To: References: Message-ID: On Mon, Mar 11, 2013 at 8:59 PM, akuma ukpo wrote: > This is the problem > > Implement a function called get_direction which, on a particular character > , gives the > direction corresponding to that character. Do you know how to write a test case for this function? You had test cases for one of the previous problems you sent the list earlier. Can you do the same thing for this problem? From dyoo at hashcollision.org Tue Mar 12 07:20:27 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 11 Mar 2013 23:20:27 -0700 Subject: [Tutor] implementing rot 13 problems In-Reply-To: References: Message-ID: The use of index() here to find the target place where the translation is going to occur is very fragile. Consider: we conceptually already should know where in the list we want the target to be, since we're walking across the characters in the list. We know that we're looking first at ls[0], transforming it, then ls[2], then ls[3], then... The fact that we're using index() here, to try to recompute that target position, is doing "extra" work: we're searching for something that we should have already known. And it turns out that not only is it superfluous, but it's broken: there may be several places in the list that qualify, not just the one that you're considering. From joskerc at gmail.com Tue Mar 12 07:21:37 2013 From: joskerc at gmail.com (Jos Kerc) Date: Tue, 12 Mar 2013 07:21:37 +0100 Subject: [Tutor] implementing rot 13 problems In-Reply-To: References: Message-ID: On Tue, Mar 12, 2013 at 6:57 AM, RJ Ewing wrote: > I am trying to implement rot 13 and am having troubles. My code is as > follows: > > class Rot_13(webapp2.RequestHandler): > def write_form(self, user=""): > self.response.out.write(rot_form % user) > def get(self): > self.write_form() > def post(self): > user = self.request.get("text") > s = self.rot_text(user) > print s > s = "".join(s) > self.escape_html(s) > self.write_form(s) > You might want to read up on the translate() method. > def rot_text(self, s): > ls = [i for i in s] > for i in ls: > if i.isalpha(): > if i.isupper(): > if i <= 'M': > x = ls.index(i) > ls[ls.index(i)] = chr(ord(i) + 13) > else: > x = ls.index(i) > ls[ls.index(i)] = chr(ord(i) - 13) > elif i.islower(): > if i <= 'm': > x = ls.index(i) > ls[x] = chr(ord(i) + 13) > elif i > 'm': > x = ls.index(i) > ls[x] = chr(ord(i) - 13) > return ls > > def escape_html(self, s): > return cgi.escape(s, quote = True) > > Now if I enter abc, I get nop. But if I enter abcdefghijklmnop, I > get abcqrstuvwxyznop. I have included print statements to check if ls[x] is > changing and it is, but something is going wrong when I return the ls, and > I am not quite sure what it is. > > Me neither, how are you calling /returning it? > 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 alan.gauld at btinternet.com Tue Mar 12 10:33:02 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 12 Mar 2013 09:33:02 +0000 Subject: [Tutor] Need help with python keyboard press/navigation commands In-Reply-To: References: Message-ID: On 12/03/13 03:59, akuma ukpo wrote: > I have tried > > def get_direction(self): > """ > whenever a key is pressed the character moves to > the direction corresponding to the key > """ > 'North':w > 'South': s > 'East' : d > 'West' : a What did you think that would do? There is no control structure and no return value. Nothing is assigned to anything. And none of the names are defined anywhere. It makes no sense to me looking at it and it certainly doesn't make sense to Python trying to execute it. If you want to respond to keys you are going to have to either pass in the keystroke to the function or read the keystroke inside the function. How you do that depends on whether you are using a GUI, and if so which. Whether you are using PyGame. Or if a CLI program which OS you are using. Finally, from a user experience point of view, it might be more logical to make the keys w,a,s,z North, West,East and South respectively since its a more logical correspondence to the compass points (assuming a standard QWERTY keyboard layout). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Mar 12 10:54:18 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 12 Mar 2013 09:54:18 +0000 Subject: [Tutor] implementing rot 13 problems In-Reply-To: References: Message-ID: On 12/03/13 05:57, RJ Ewing wrote: > I am trying to implement rot 13 and am having troubles. My code is as > follows: There are better ways to do what you are doing but assuming this is a learning exercise rather than a serious project I'll make some comments: > def rot_text(self, s): > ls = [i for i in s] > for i in ls: You could have looped directly over s and built a new list to return. Just a thought. > if i.isalpha(): > if i.isupper(): Since the code in the upper and lower sections are nearly identical you can avoid the repetition by assigning the test char (M or m) here and then using a single block to do the conversion. test = 'M' else: # must be lower test = 'm' Or more concisely test = 'M' if i.isupper() else 'm' if i <= test: x = ls.index(i) ls[x] = chr(ord(i) + 13) elif i > test: x = ls.index(i) ls[x] = chr(ord(i) - 13) The elif could just as well be an else... You never used x originally, but then here you do.... but it would have been easier to get it at the start of the loop with: for index, char in enumerate(ls): And that would be more readable names too... However, given the relatively small character set and fixed target a simple mapping table would be easier to implement as suggested by another poster. > Now if I enter abc, I get nop. But if I enter abcdefghijklmnop, I > get abcqrstuvwxyznop. No idea what is going on there. But you are returning ls - the list. I would have thought you'd want to return the string version of the list? return ''.join(ls) maybe? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Tue Mar 12 11:58:56 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 12 Mar 2013 21:58:56 +1100 Subject: [Tutor] implementing rot 13 problems In-Reply-To: References: Message-ID: <513F0A70.1030402@pearwood.info> On 12/03/13 16:57, RJ Ewing wrote: > I am trying to implement rot 13 and am having troubles. My code is as > follows: A few comments follow. > def rot_text(self, s): > ls = [i for i in s] > for i in ls: > if i.isalpha(): > if i.isupper(): > if i <= 'M': > x = ls.index(i) > ls[ls.index(i)] = chr(ord(i) + 13) This is unnecessarily verbose and complicated. First problem, you use the name "i" to represent a character. Generally you should avoid single character names, and prefer meaningful names that explain what the variable represents. If you must use a single character, then the conventional names include: x, y, z: numbers, particularly floats x: (rarely) an arbitrary value of no particular type i, j, k: integer loop variables (rare in Python) n, m: other integers s: string c: character Notice that "c for character" makes much more sense than "i for character". You can, and should, create a list from the string using the list() function, rather than a list comprehension that just walks over the characters: ls = [c for c in s] # No, too verbose. ls = list(s) # Much better. You then loop over the list, again using "i for character". You can combine all those multiple if statements into a single clause: for i in ls: if i.isalpha() and i.isupper() and i <= 'M': But wait! The call to isalpha() is not necessary, because if a character is *not* alphabetical, isupper() will always return False: py> '9'.isupper() False So we can throw out the call to isalpha(). Your code to rot13 the letter is, sadly, broken: x = ls.index(i) ls[ls.index(i)] = chr(ord(i) + 13) This might make more sense if I re-write it using more meaningful names: position = ls.index(char) # This variable never gets used :-( ls[ls.index(char)] = chr(ord(char) + 13) The bit with chr() and ord() is fine. But what you do with it is wrong. The problem is that index always returns the position of the *first* copy of the item. So if your string is: 'ABA' the first time around the loop, your character is 'A'. ls.index('A') will return 0, and the rot13ed version, 'N', will be shoved into position 0. The second time around the loop, the character is 'B' and the rot13ed version gets shoved into position 1. But the third time, the character is 'A' again, index() will return 0 again, and the rot13ed version gets shoved into position 0 instead of position 2, giving you: 'NOA' The best way to fix this is to ignore index, and instead count which character we're at each time: position = -1 for char in ls: position = position + 1 # Advance the count. ... blah blah blah ls[position] = chr(ord(char) + 13) But wait! Python has a function to do exactly this for us: for position, char in enumerate(ls): ... blah blah blah ls[position] = chr(ord(char) + 13) Have a go with that, and see how far you get. -- Steven From kliateni at gmail.com Tue Mar 12 12:11:39 2013 From: kliateni at gmail.com (Karim) Date: Tue, 12 Mar 2013 12:11:39 +0100 Subject: [Tutor] implementing rot 13 problems In-Reply-To: <513F0A70.1030402@pearwood.info> References: <513F0A70.1030402@pearwood.info> Message-ID: <513F0D6B.3070409@gmail.com> What can be said after this detailed lesson...Bravo! On 12/03/2013 11:58, Steven D'Aprano wrote: > On 12/03/13 16:57, RJ Ewing wrote: >> I am trying to implement rot 13 and am having troubles. My code is as >> follows: > > A few comments follow. > > >> def rot_text(self, s): >> ls = [i for i in s] >> for i in ls: >> if i.isalpha(): >> if i.isupper(): >> if i <= 'M': >> x = ls.index(i) >> ls[ls.index(i)] = chr(ord(i) + 13) > > > This is unnecessarily verbose and complicated. > > First problem, you use the name "i" to represent a character. > Generally you should avoid single character names, and prefer > meaningful names that explain what the variable represents. If you > must use a single character, then the conventional names include: > > x, y, z: numbers, particularly floats > x: (rarely) an arbitrary value of no particular type > i, j, k: integer loop variables (rare in Python) > n, m: other integers > s: string > c: character > > Notice that "c for character" makes much more sense than "i for > character". > > > You can, and should, create a list from the string using the list() > function, rather than a list comprehension that just walks over the > characters: > > ls = [c for c in s] # No, too verbose. > ls = list(s) # Much better. > > > You then loop over the list, again using "i for character". You can > combine all those multiple if statements into a single clause: > > for i in ls: > if i.isalpha() and i.isupper() and i <= 'M': > > But wait! The call to isalpha() is not necessary, because if a > character is *not* alphabetical, isupper() will always return False: > > py> '9'.isupper() > False > > So we can throw out the call to isalpha(). > > Your code to rot13 the letter is, sadly, broken: > > x = ls.index(i) > ls[ls.index(i)] = chr(ord(i) + 13) > > > This might make more sense if I re-write it using more meaningful names: > > position = ls.index(char) # This variable never gets used :-( > ls[ls.index(char)] = chr(ord(char) + 13) > > The bit with chr() and ord() is fine. But what you do with it is > wrong. The problem is that index always returns the position of the > *first* copy of the item. So if your string is: > > 'ABA' > > the first time around the loop, your character is 'A'. ls.index('A') > will return 0, and the rot13ed version, 'N', will be shoved into > position 0. The second time around the loop, the character is 'B' and > the rot13ed version gets shoved into position 1. But the third time, > the character is 'A' again, index() will return 0 again, and the > rot13ed version gets shoved into position 0 instead of position 2, > giving you: > > 'NOA' > > > The best way to fix this is to ignore index, and instead count which > character we're at each time: > > > position = -1 > for char in ls: > position = position + 1 # Advance the count. > ... blah blah blah > ls[position] = chr(ord(char) + 13) > > > But wait! Python has a function to do exactly this for us: > > > for position, char in enumerate(ls): > ... blah blah blah > ls[position] = chr(ord(char) + 13) > > > > > Have a go with that, and see how far you get. > > > > From kevin.khan27 at gmail.com Tue Mar 12 15:10:23 2013 From: kevin.khan27 at gmail.com (Kevin Khan) Date: Tue, 12 Mar 2013 10:10:23 -0400 Subject: [Tutor] Matplotlib Slider Widget and changing colorbar threshold Message-ID: I am currently trying to work on a program that will allow the user to display their dataset in the form of a colormap and through the use of sliders, it will also allow the user to adjust the threshold of the colormap and thus update the colormap accordingly. The best to describe this would be through the use of a picture: [1]: http://i.stack.imgur.com/1T9Qp.png This image shows how the colorbar should look before (the image on the left) and after (the image on the right) the adjustment. As the threshold values of the colrobar are changed, the colormap would be updated accordingly. Now I am mainly using matplotlib and I found that matplotlib does support some widgets, such as a slider. However the area I need help in is devising a piece of code which will update the colorbar and colormap (like the way shown in the picture above) when the slider is adjusted. I was wondering if anyone has done this before and might have a piece of code they would be willing to share and might have pointers as to how this can be achieved. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mnickey at gmail.com Tue Mar 12 15:20:22 2013 From: mnickey at gmail.com (Mike Nickey) Date: Tue, 12 Mar 2013 07:20:22 -0700 Subject: [Tutor] Python version 2.7 or 3.0 Message-ID: Hey all, I'm used to python 2.7 but I'm seeing and hearing a lot about 3.0 and wanted to ask a few questions. I'm seeing on StackOverflow that 2.7 is the standard for those that have libraries that haven't been ported to 3.1.2 yet. Does this mean that 2.7 is dead or dying? Is this just a well managed marketing campaign? If these can be simplified into layman's terms I'd really appreciate your advice & input. -- ~MEN -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Mar 12 16:44:35 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 12 Mar 2013 15:44:35 +0000 Subject: [Tutor] Matplotlib Slider Widget and changing colorbar threshold In-Reply-To: References: Message-ID: On 12/03/13 14:10, Kevin Khan wrote: > I am currently trying to work on a program that will allow the user to > display their dataset in the form of a colormap and through the use of > sliders, it will also allow the user to adjust the threshold of the > colormap and thus update the colormap accordingly. > Now I am mainly using matplotlib and I found that matplotlib does > support some widgets, such as a slider. However the area I need help in > is devising a piece of code which will update the colorbar and colormap Matplotlib usually just reflects the underlying data so you need to adjust the data values that control the colours and matplotlib will change the display (you may need to force a refresh). I've not done exactly what you are asking but I have done conceptually similar things with network maps where nodes change color depending on the numbers of alarms they have generated (usually, red, amber, green). HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Mar 12 16:47:54 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 12 Mar 2013 15:47:54 +0000 Subject: [Tutor] Python version 2.7 or 3.0 In-Reply-To: References: Message-ID: On 12/03/13 14:20, Mike Nickey wrote: > I'm seeing on StackOverflow that 2.7 is the standard for those that have > libraries that haven't been ported to 3.1.2 yet. Does this mean that 2.7 > is dead or dying? Is this just a well managed marketing campaign? Like any software the latest version will eventually predominate. But since many libraries have not been ported to v3 yet 2.7 is still very much alive and still being supported. I seem to recall it being stated that 2.7 is the last of the v2 Python family but that it will be receiving updates/fixes for some time yet. It's not a marketing campaign but the normal process of migrating from one version to a newer, incompatible, version. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ewing.rj at gmail.com Tue Mar 12 17:00:01 2013 From: ewing.rj at gmail.com (RJ Ewing) Date: Tue, 12 Mar 2013 09:00:01 -0700 Subject: [Tutor] implementing rot 13 problems In-Reply-To: <513F0D6B.3070409@gmail.com> References: <513F0A70.1030402@pearwood.info> <513F0D6B.3070409@gmail.com> Message-ID: Thank you all for the help. I really appreciated the suggestions. Some of the things you pointed out, I originally used, but started changing thing when it wasn't working. I got it to work, but if you could let me know if there is anything I should do to make this code more pythonesque that would be great. def rot_text(self, s): ls = list(s) for position, char in enumerate(ls): if char.isupper() or char.islower(): test = 'M' if char.isupper() else 'm' if char <= test: ls[position] = chr(ord(char) + 13) else: ls[position] = chr(ord(char) - 13) return "".join(ls) On Tue, Mar 12, 2013 at 4:11 AM, Karim wrote: > > What can be said after this detailed lesson...Bravo! > > > On 12/03/2013 11:58, Steven D'Aprano wrote: > >> On 12/03/13 16:57, RJ Ewing wrote: >> >>> I am trying to implement rot 13 and am having troubles. My code is as >>> follows: >>> >> >> A few comments follow. >> >> >> def rot_text(self, s): >>> ls = [i for i in s] >>> for i in ls: >>> if i.isalpha(): >>> if i.isupper(): >>> if i <= 'M': >>> x = ls.index(i) >>> ls[ls.index(i)] = chr(ord(i) + 13) >>> >> >> >> This is unnecessarily verbose and complicated. >> >> First problem, you use the name "i" to represent a character. Generally >> you should avoid single character names, and prefer meaningful names that >> explain what the variable represents. If you must use a single character, >> then the conventional names include: >> >> x, y, z: numbers, particularly floats >> x: (rarely) an arbitrary value of no particular type >> i, j, k: integer loop variables (rare in Python) >> n, m: other integers >> s: string >> c: character >> >> Notice that "c for character" makes much more sense than "i for >> character". >> >> >> You can, and should, create a list from the string using the list() >> function, rather than a list comprehension that just walks over the >> characters: >> >> ls = [c for c in s] # No, too verbose. >> ls = list(s) # Much better. >> >> >> You then loop over the list, again using "i for character". You can >> combine all those multiple if statements into a single clause: >> >> for i in ls: >> if i.isalpha() and i.isupper() and i <= 'M': >> >> But wait! The call to isalpha() is not necessary, because if a character >> is *not* alphabetical, isupper() will always return False: >> >> py> '9'.isupper() >> False >> >> So we can throw out the call to isalpha(). >> >> Your code to rot13 the letter is, sadly, broken: >> >> x = ls.index(i) >> ls[ls.index(i)] = chr(ord(i) + 13) >> >> >> This might make more sense if I re-write it using more meaningful names: >> >> position = ls.index(char) # This variable never gets used :-( >> ls[ls.index(char)] = chr(ord(char) + 13) >> >> The bit with chr() and ord() is fine. But what you do with it is wrong. >> The problem is that index always returns the position of the *first* copy >> of the item. So if your string is: >> >> 'ABA' >> >> the first time around the loop, your character is 'A'. ls.index('A') will >> return 0, and the rot13ed version, 'N', will be shoved into position 0. The >> second time around the loop, the character is 'B' and the rot13ed version >> gets shoved into position 1. But the third time, the character is 'A' >> again, index() will return 0 again, and the rot13ed version gets shoved >> into position 0 instead of position 2, giving you: >> >> 'NOA' >> >> >> The best way to fix this is to ignore index, and instead count which >> character we're at each time: >> >> >> position = -1 >> for char in ls: >> position = position + 1 # Advance the count. >> ... blah blah blah >> ls[position] = chr(ord(char) + 13) >> >> >> But wait! Python has a function to do exactly this for us: >> >> >> for position, char in enumerate(ls): >> ... blah blah blah >> ls[position] = chr(ord(char) + 13) >> >> >> >> >> Have a go with that, and see how far you get. >> >> >> >> >> > ______________________________**_________________ > 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 Tue Mar 12 17:53:21 2013 From: __peter__ at web.de (Peter Otten) Date: Tue, 12 Mar 2013 17:53:21 +0100 Subject: [Tutor] implementing rot 13 problems References: <513F0A70.1030402@pearwood.info> <513F0D6B.3070409@gmail.com> Message-ID: RJ Ewing wrote: > Thank you all for the help. I really appreciated the suggestions. Some of > the things you pointed out, I originally used, but started changing thing > when it wasn't working. I got it to work, but if you could let me know if > there is anything I should do to make this code more pythonesque that > would be great. > > def rot_text(self, s): > ls = list(s) > for position, char in enumerate(ls): > if char.isupper() or char.islower(): > test = 'M' if char.isupper() else 'm' > if char <= test: > ls[position] = chr(ord(char) + 13) > else: > ls[position] = chr(ord(char) - 13) > return "".join(ls) If you are interested in a different perspective on the same problem have a look into the "this" module of your python distribution. You can find the location of that file on your system by typing import this print this.__file__.rstrip("co") into the interactive interpreter. Be sure to read the text that is printed out before proceeding to read the module that produced it. From robert.sjoblom at gmail.com Tue Mar 12 18:01:00 2013 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Tue, 12 Mar 2013 18:01:00 +0100 Subject: [Tutor] Need help with python keyboard press/navigation commands In-Reply-To: References: Message-ID: > Finally, from a user experience point of view, it might be more logical to > make the keys w,a,s,z North, West,East and South respectively since its a > more logical correspondence to the compass points (assuming a standard > QWERTY keyboard layout). Most games use WASD, so user experience would be in favour of it compared to WASZ. There are a couple of reasons for this: if you're moving forward you're not moving backward, and if you're moving backward you're not moving forward, so the finger you use for W can be used for S. So finger position is W(S) A and D; three fingers that can handle moving at an angle (NW, NE by keys WA or WD, SW and SE by keys SA or SD) or in one direction. Compare with WASZ, moving NW is still WA, but NE would be WS, which are keys that are very close together. Moving backwards (south) would be even worse. Finally, WASD has the same layout as the arrow keys, but is located elsewhere on the keyboard (so you can map other keys to other functions in the games; your pinky is close to both shift and ctrl, thumb to space and C, E, R, F, V and Q, and 1-5 are all within close range -- compare to the arrow keys, where you get four keys (shift, ctrl, 1 and 0) nearby). Some people like to use the number keys (8456 for WASD) instead, as they too are relatively close to more keys, but overall I think that WASD is the standard. At least that's what I suspect. -- best regards, Robert S. From alan.gauld at btinternet.com Tue Mar 12 19:59:36 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 12 Mar 2013 18:59:36 +0000 (GMT) Subject: [Tutor] Need help with python keyboard press/navigation commands In-Reply-To: References: Message-ID: <1363114776.2953.YahooMailNeo@web186003.mail.ir2.yahoo.com> >> Finally, from a user experience point of view, it might be more logical to >> make the keys w,a,s,z North, West,East and South respectively? > >Most games use WASD, so user experience would be in favour of it >compared to WASZ. There are a couple of reasons for this:? > >You live and learn! :-) You can probably also deduce that I'm more of a touch typist than? I am a gamer... or does solitaire count? Moving backwards (south) would be even worse. Finally, WASD has the >same layout as the arrow keys,?Arrow keys? What are they?? hjkl in vim and C-n,C-p,C-f,C-b in emacs.... Thanks for the education. Alan G -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Tue Mar 12 20:05:23 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 12 Mar 2013 12:05:23 -0700 Subject: [Tutor] implementing rot 13 problems In-Reply-To: References: <513F0A70.1030402@pearwood.info> <513F0D6B.3070409@gmail.com> Message-ID: On Tue, Mar 12, 2013 at 9:00 AM, RJ Ewing wrote: > Thank you all for the help. I really appreciated the suggestions. Some of > the things you pointed out, I originally used, but started changing thing > when it wasn't working. I got it to work, but if you could let me know if > there is anything I should do to make this code more pythonesque that would > be great. Two suggestions: 1. Since rot_text itself doesn't use any of the state of the object, it makes sense to treat it as a plain function. 2. Explicit array mutation here can be avoided here; it turns out that writing it without mutation is a little easier to read, and is less bug prone. Here's what your code looks like with these two suggestions: ################################## ## rot1: char -> char ## Rotates a single character. def rot1(char): if char.isupper() or char.islower(): test = 'M' if char.isupper() else 'm' if char <= test: return chr(ord(char) + 13) else: return chr(ord(char) - 13) ## rot_string: string -> string ## Rotates all the characters. def rot_string(s): return "".join([rot1(ch) for ch in s]) ################################## I've refactored the heart of the rotation logic into rot1(). Note that it doesn't care about arrays or not: its own concern is the rotation of a single character. Good luck! From dyoo at hashcollision.org Tue Mar 12 20:12:26 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 12 Mar 2013 12:12:26 -0700 Subject: [Tutor] implementing rot 13 problems In-Reply-To: References: <513F0A70.1030402@pearwood.info> <513F0D6B.3070409@gmail.com> Message-ID: > ################################## > ## rot1: char -> char > ## Rotates a single character. > def rot1(char): > if char.isupper() or char.islower(): > test = 'M' if char.isupper() else 'm' > if char <= test: > return chr(ord(char) + 13) > else: > return chr(ord(char) - 13) Also note that I've deliberately left alone a bug in rot1(), to make it easier to show a flaw in the original code that you'll want to fix. The bug is in the definition and use of 'test'. Not only is the variable name somewhat undescriptive, but it's only being defined in only one branch of the conditional. That's a "bad" code smell, and in this case, you'll find an issue here when trying to rotate a non-alphabetic character. From dyoo at hashcollision.org Tue Mar 12 20:18:52 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 12 Mar 2013 12:18:52 -0700 Subject: [Tutor] implementing rot 13 problems In-Reply-To: References: <513F0A70.1030402@pearwood.info> <513F0D6B.3070409@gmail.com> Message-ID: > Also note that I've deliberately left alone a bug in rot1(), to make > it easier to show a flaw in the original code that you'll want to fix. Doh. Never mind. _I'm_ the one who introduced that regression. :( Sorry! Here's a corrected definition for rot1(): ############################# def rot1(char): if char.isupper() or char.islower(): test = 'M' if char.isupper() else 'm' if char <= test: return chr(ord(char) + 13) else: return chr(ord(char) - 13) else: return char ############################# My apologies! From steve at pearwood.info Wed Mar 13 00:23:03 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 13 Mar 2013 10:23:03 +1100 Subject: [Tutor] Python version 2.7 or 3.0 In-Reply-To: References: Message-ID: <513FB8D7.2070400@pearwood.info> On 13/03/13 01:20, Mike Nickey wrote: > Hey all, > > I'm used to python 2.7 but I'm seeing and hearing a lot about 3.0 and > wanted to ask a few questions. > I'm seeing on StackOverflow that 2.7 is the standard for those that have > libraries that haven't been ported to 3.1.2 yet. Does this mean that 2.7 is > dead or dying? Is this just a well managed marketing campaign? Python 2.7 is alive and well and will be supported for quite a few more years yet. But it is a dead end. There will be no Python 2.8. It will continue to get bug fixes for a few more years, and security updates for a few years longer, but no new features. Meanwhile, Python 3.3 and beyond is where the future is at. New features and performance improvements are all aimed at 3.3. The reason for the two parallel "current versions" is that Python 3 introduced a few language changes which broke backward compatibility, and rearranged the standard library to make it more consistent. Since these were big changes, it is tricky (but not impossible!) for a single program to run under both Python 2 and Python 3. Realizing that it would take the big libraries many years to migrate to Python 3, the Python development team committed to keeping 2.7 alive for longer than normal, so as to give people time to migrate. I estimate that we're about half-way into the process. More than half of the big libraries have either started, or completed, migrating to support 3.x. At least one Linux distribution uses Python 3 as their system Python, and most of the others provide it as an optional extra. So, maybe another 4-5 years of life in Python 2.7? If you are just starting out, and have no prerequisites about external libraries, you should stick with Python 3.3. Please do not use Python 3.0, it is slow and buggy and not supported. 3.1 or 3.2 are acceptable, but if you have a choice, go for 3.3. If you need a specific library which does not support Python 3, then 2.7 is acceptable. -- Steven From leamhall at gmail.com Wed Mar 13 01:03:43 2013 From: leamhall at gmail.com (Leam Hall) Date: Tue, 12 Mar 2013 20:03:43 -0400 Subject: [Tutor] Python version 2.7 or 3.0 In-Reply-To: References: Message-ID: <513FC25F.9000403@gmail.com> On 03/12/2013 11:47 AM, Alan Gauld wrote: > On 12/03/13 14:20, Mike Nickey wrote: > >> I'm seeing on StackOverflow that 2.7 is the standard for those that have >> libraries that haven't been ported to 3.1.2 yet. Does this mean that 2.7 >> is dead or dying? Is this just a well managed marketing campaign? > > Like any software the latest version will eventually predominate. But > since many libraries have not been ported to v3 yet 2.7 is still very > much alive and still being supported. I seem to recall it being stated > that 2.7 is the last of the v2 Python family but that it will be > receiving updates/fixes for some time yet. > > It's not a marketing campaign but the normal process of migrating from > one version to a newer, incompatible, version. It also depends on what platform you're developing for. On Red Hat boxes 2.6.6 is the "standard" for RHEL 6. From what I understand, RHEL 7 will not be Python 3 yet, either. If you don't have any platform restrictions, then 3.3 is the way to go. Leam From ysoliman at uncc.edu Wed Mar 13 01:05:36 2013 From: ysoliman at uncc.edu (Soliman, Yasmin) Date: Wed, 13 Mar 2013 00:05:36 +0000 Subject: [Tutor] BMI calc Message-ID: <211A029E048A2245A6E00BA02FEFF88A581E29CB@BL2PRD0310MB373.namprd03.prod.outlook.com> Hello all, I'm new to python and its been a stuggle so far. I'm attempting to create a BMI calculator in Wing 101 4.1. I keep getting syntax errors: def calc_BMI(weight,height): return (weight/(height*height))*703.0 if bmi <=18.5: print 'underweight' elif bmi >= 18.5 and bmi <=24.9: print 'normal weight' elif bmi >=25 and bmi <=29.9: print 'overweight' elif bmi >=30: print 'obese' Also, height should be converted to inches and I have not the slightest clue how to so. Any help would be much appreciated. From breamoreboy at yahoo.co.uk Wed Mar 13 02:46:10 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 13 Mar 2013 01:46:10 +0000 Subject: [Tutor] BMI calc In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A581E29CB@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A581E29CB@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: On 13/03/2013 00:05, Soliman, Yasmin wrote: > Hello all, > > I'm new to python and its been a stuggle so far. I'm attempting to create a BMI calculator in Wing 101 4.1. I keep getting syntax errors: > > def calc_BMI(weight,height): > return (weight/(height*height))*703.0 > if bmi <=18.5: > print 'underweight' > elif bmi >= 18.5 and bmi <=24.9: > print 'normal weight' > elif bmi >=25 and bmi <=29.9: > print 'overweight' > elif bmi >=30: > print 'obese' > > Also, height should be converted to inches and I have not the slightest clue how to so. Any help would be much appreciated. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > If you're using Python 3 you'll get syntax errors as print is a function, not a statement as in Python 2. Is this your problem? If not please cut and paste the exact syntax error for us to see. Then we'll sort the rest of the problems :) -- Cheers. Mark Lawrence From davea at davea.name Wed Mar 13 03:08:56 2013 From: davea at davea.name (Dave Angel) Date: Tue, 12 Mar 2013 22:08:56 -0400 Subject: [Tutor] BMI calc In-Reply-To: References: <211A029E048A2245A6E00BA02FEFF88A581E29CB@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: <513FDFB8.7070607@davea.name> On 03/12/2013 09:46 PM, Mark Lawrence wrote: > On 13/03/2013 00:05, Soliman, Yasmin wrote: >> Hello all, >> >> I'm new to python and its been a stuggle so far. I'm attempting to >> create a BMI calculator in Wing 101 4.1. I keep getting syntax errors: >> >> def calc_BMI(weight,height): >> return (weight/(height*height))*703.0 >> if bmi <=18.5: >> print 'underweight' >> elif bmi >= 18.5 and bmi <=24.9: >> print 'normal weight' >> elif bmi >=25 and bmi <=29.9: >> print 'overweight' >> elif bmi >=30: >> print 'obese' >> >> Also, height should be converted to inches and I have not the >> slightest clue how to so. Any help would be much appreciated. >> _ >> > > If you're using Python 3 you'll get syntax errors as print is a > function, not a statement as in Python 2. Is this your problem? If not > please cut and paste the exact syntax error for us to see. Then we'll > sort the rest of the problems :) > As Mark implies, tell us exactly what Python version you're using, and copy/paste the entire error message, including traceback. For example, when I run it on 3.3, I have: davea at think2:~/temppython$ python3.3 soliman.py File "soliman.py", line 6 print 'underweight' ^ SyntaxError: invalid syntax Also, could you tell us your experience level? You've defined a function, but you haven't called it. And yet you're apparently trying to use the results of calling it. As for converting height to inches, that depends on what you started with. Since you're using the English version of the formula, you should already have inches and pounds before calling that function. So perhaps in addition to missing the code for inputting the values (perhaps the raw_input function), you're also missing the conversion from "something" to inches. How are you getting the raw numbers, and what units are they in? If the raw numbers are in meters and kg, then you'd want to remove the multiply by 703. Or you could convert from meters to inches by multiplying by 39.? (look up the exact number). And from kg to pounds by a similar multiply by something like 2.2 -- DaveA From breamoreboy at yahoo.co.uk Wed Mar 13 03:29:58 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 13 Mar 2013 02:29:58 +0000 Subject: [Tutor] BMI calc In-Reply-To: <513FDFB8.7070607@davea.name> References: <211A029E048A2245A6E00BA02FEFF88A581E29CB@BL2PRD0310MB373.namprd03.prod.outlook.com> <513FDFB8.7070607@davea.name> Message-ID: On 13/03/2013 02:08, Dave Angel wrote: > On 03/12/2013 09:46 PM, Mark Lawrence wrote: >> On 13/03/2013 00:05, Soliman, Yasmin wrote: >>> Hello all, >>> >>> I'm new to python and its been a stuggle so far. I'm attempting to >>> create a BMI calculator in Wing 101 4.1. I keep getting syntax errors: >>> >>> def calc_BMI(weight,height): >>> return (weight/(height*height))*703.0 >>> if bmi <=18.5: >>> print 'underweight' >>> elif bmi >= 18.5 and bmi <=24.9: >>> print 'normal weight' >>> elif bmi >=25 and bmi <=29.9: >>> print 'overweight' >>> elif bmi >=30: >>> print 'obese' >>> >>> Also, height should be converted to inches and I have not the >>> slightest clue how to so. Any help would be much appreciated. >>> _ >>> >> >> If you're using Python 3 you'll get syntax errors as print is a >> function, not a statement as in Python 2. Is this your problem? If not >> please cut and paste the exact syntax error for us to see. Then we'll >> sort the rest of the problems :) >> > > As Mark implies, tell us exactly what Python version you're using, and > copy/paste the entire error message, including traceback. > > For example, when I run it on 3.3, I have: > > davea at think2:~/temppython$ python3.3 soliman.py > File "soliman.py", line 6 > print 'underweight' > ^ > SyntaxError: invalid syntax > > > Also, could you tell us your experience level? You've defined a > function, but you haven't called it. And yet you're apparently trying > to use the results of calling it. > > As for converting height to inches, that depends on what you started > with. Since you're using the English version of the formula, you should > already have inches and pounds before calling that function. > > So perhaps in addition to missing the code for inputting the values > (perhaps the raw_input function), you're also missing the conversion > from "something" to inches. How are you getting the raw numbers, and > what units are they in? > > If the raw numbers are in meters and kg, then you'd want to remove the > multiply by 703. Or you could convert from meters to inches by > multiplying by 39.? (look up the exact number). And from kg to pounds > by a similar multiply by something like 2.2 > Of course if you've got the wrong algorithm you're wasting your time anyway, see for example http://www.newscientist.com/article/mg20928030.200-obesity-expert-a-better-fat-measure-than-bmi.html :) -- Cheers. Mark Lawrence From ysoliman at uncc.edu Wed Mar 13 04:07:27 2013 From: ysoliman at uncc.edu (Soliman, Yasmin) Date: Wed, 13 Mar 2013 03:07:27 +0000 Subject: [Tutor] BMI calc In-Reply-To: References: <211A029E048A2245A6E00BA02FEFF88A581E29CB@BL2PRD0310MB373.namprd03.prod.outlook.com> <513FDFB8.7070607@davea.name>, Message-ID: <211A029E048A2245A6E00BA02FEFF88A581E29FB@BL2PRD0310MB373.namprd03.prod.outlook.com> I'm using python 2.7, where exactly does the return statment with the (return (weight/(height*height))*703 calculation get posted in the function? def calc_BMI(weight,height): if bmi <=18.5: return 'underweight' elif bmi >= 18.5 and bmi <=24.9: return 'normal weight' elif bmi >=25 and bmi <=29.9: return 'overweight' elif bmi >=30: return 'obese' The user will need to input height ex) 5'3 and which will need to be split and stripped in order to convert to inches. ________________________________________ From: Tutor [tutor-bounces+ysoliman=uncc.edu at python.org] on behalf of Mark Lawrence [breamoreboy at yahoo.co.uk] Sent: Tuesday, March 12, 2013 10:29 PM To: tutor at python.org Subject: Re: [Tutor] BMI calc On 13/03/2013 02:08, Dave Angel wrote: > On 03/12/2013 09:46 PM, Mark Lawrence wrote: >> On 13/03/2013 00:05, Soliman, Yasmin wrote: >>> Hello all, >>> >>> I'm new to python and its been a stuggle so far. I'm attempting to >>> create a BMI calculator in Wing 101 4.1. I keep getting syntax errors: >>> >>> def calc_BMI(weight,height): >>> return (weight/(height*height))*703.0 >>> if bmi <=18.5: >>> print 'underweight' >>> elif bmi >= 18.5 and bmi <=24.9: >>> print 'normal weight' >>> elif bmi >=25 and bmi <=29.9: >>> print 'overweight' >>> elif bmi >=30: >>> print 'obese' >>> >>> Also, height should be converted to inches and I have not the >>> slightest clue how to so. Any help would be much appreciated. >>> _ >>> >> >> If you're using Python 3 you'll get syntax errors as print is a >> function, not a statement as in Python 2. Is this your problem? If not >> please cut and paste the exact syntax error for us to see. Then we'll >> sort the rest of the problems :) >> > > As Mark implies, tell us exactly what Python version you're using, and > copy/paste the entire error message, including traceback. > > For example, when I run it on 3.3, I have: > > davea at think2:~/temppython$ python3.3 soliman.py > File "soliman.py", line 6 > print 'underweight' > ^ > SyntaxError: invalid syntax > > > Also, could you tell us your experience level? You've defined a > function, but you haven't called it. And yet you're apparently trying > to use the results of calling it. > > As for converting height to inches, that depends on what you started > with. Since you're using the English version of the formula, you should > already have inches and pounds before calling that function. > > So perhaps in addition to missing the code for inputting the values > (perhaps the raw_input function), you're also missing the conversion > from "something" to inches. How are you getting the raw numbers, and > what units are they in? > > If the raw numbers are in meters and kg, then you'd want to remove the > multiply by 703. Or you could convert from meters to inches by > multiplying by 39.? (look up the exact number). And from kg to pounds > by a similar multiply by something like 2.2 > Of course if you've got the wrong algorithm you're wasting your time anyway, see for example http://www.newscientist.com/article/mg20928030.200-obesity-expert-a-better-fat-measure-than-bmi.html :) -- Cheers. Mark Lawrence _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From joskerc at gmail.com Wed Mar 13 07:17:47 2013 From: joskerc at gmail.com (Jos Kerc) Date: Wed, 13 Mar 2013 07:17:47 +0100 Subject: [Tutor] BMI calc In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A581E29FB@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A581E29CB@BL2PRD0310MB373.namprd03.prod.outlook.com> <513FDFB8.7070607@davea.name> <211A029E048A2245A6E00BA02FEFF88A581E29FB@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: Hi, On Wed, Mar 13, 2013 at 4:07 AM, Soliman, Yasmin wrote: > I'm using python 2.7, where exactly does the return statment with the > (return (weight/(height*height))*703 calculation get posted in the function? > > def calc_BMI(weight,height): > if bmi <=18.5: > return 'underweight' > elif bmi >= 18.5 and bmi <=24.9: > return 'normal weight' > elif bmi >=25 and bmi <=29.9: > Following return is out of alignment. Should be at the same place in the line as the oters. > return 'overweight' > elif bmi >=30: > return 'obese' > > The user will need to input height ex) 5'3 and which will need to be split > and stripped in order to convert to inches. > Exactly. Do you have a problem with this? If so what? Dreetz -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Wed Mar 13 08:10:40 2013 From: davea at davea.name (Dave Angel) Date: Wed, 13 Mar 2013 03:10:40 -0400 Subject: [Tutor] BMI calc In-Reply-To: References: <211A029E048A2245A6E00BA02FEFF88A581E29CB@BL2PRD0310MB373.namprd03.prod.outlook.com> <513FDFB8.7070607@davea.name> <211A029E048A2245A6E00BA02FEFF88A581E29FB@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: <51402670.3020000@davea.name> On 03/13/2013 02:17 AM, Jos Kerc wrote: > Hi, > > > On Wed, Mar 13, 2013 at 4:07 AM, Soliman, Yasmin wrote: > >> >> >> def calc_BMI(weight,height): >> if bmi <=18.5: >> return 'underweight' >> elif bmi >= 18.5 and bmi <=24.9: >> return 'normal weight' >> elif bmi >=25 and bmi <=29.9: >> > > Following return is out of alignment. Should be at the same place in the > line as the oters. > > >> return 'overweight' It would certainly look prettier, but it's not a language requirement. Only within a single block do the columns have to line up exactly. > -- DaveA From alan.gauld at btinternet.com Wed Mar 13 09:36:05 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 13 Mar 2013 08:36:05 +0000 Subject: [Tutor] BMI calc In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A581E29FB@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A581E29CB@BL2PRD0310MB373.namprd03.prod.outlook.com> <513FDFB8.7070607@davea.name>, <211A029E048A2245A6E00BA02FEFF88A581E29FB@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: On 13/03/13 03:07, Soliman, Yasmin wrote: > I'm using python 2.7, Then let us see the syntax errors because otherwise we are guessing. > where exactly does the return statment ... get posted in the function? I'm not sure what you mean by 'get posted' It is activated once the function is called. ie def foo(x): return 2 + x does nothing until I call it: result = foo(5) print result > def calc_BMI(weight,height): > if bmi <=18.5: > return 'underweight' Since BMI is a value your function is better as it was, just returning the value. The code to convert that BMI value into a weight assessment is better done outside, again as you had before. (Or inside another function, rateBMI(bmi) maybe) What was missing was some glue that joins those 2 things together: read weight and height call CalcBMI use result to assess weight. > elif bmi >= 18.5 and bmi <=24.9: > return 'normal weight' BTW in Python you can abbreviate the tests slightly with elif 18.5 <= bmi <= 24.9: print 'normal weight' HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sydney.shall at kcl.ac.uk Wed Mar 13 11:44:02 2013 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Wed, 13 Mar 2013 10:44:02 +0000 Subject: [Tutor] BMI calc In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A581E29CB@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A581E29CB@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: <51405872.2030201@kcl.ac.uk> On 13/03/2013 00:05, Soliman, Yasmin wrote: > Hello all, > > I'm new to python and its been a stuggle so far. I'm attempting to create a BMI calculator in Wing 101 4.1. I keep getting syntax errors: > > def calc_BMI(weight,height): > return (weight/(height*height))*703.0 > if bmi <=18.5: > print 'underweight' > elif bmi >= 18.5 and bmi <=24.9: > print 'normal weight' > elif bmi >=25 and bmi <=29.9: > print 'overweight' > elif bmi >=30: > print 'obese' > > Also, height should be converted to inches and I have not the slightest clue how to so. Any help would be much appreciated. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Hi, I am also a newbie, but I wish to learn, so I offer the following corrections. # Note. I do note know what units you are using. # I would use scientific, metric units. So you need to divide both weight and height by a suitable conversion factors. # Then you will not need the number 703.0, and the units in the second and third lines would be Kg/m. [Kilogram/Metre) def calc_BMI(weight,height): bmi = (weight/(height*height))*703.0 print 'Your BMI is : ', BMI 'weight units/height units.' # You need to put the correct text here. if bmi <=18.5: print 'underweight' if 18.5 <= bmi <= 24.9: print 'normal weight' if 25.0 <= bmi <= 29.9: print 'overweight' if bmi >= 30: print 'obese' return I hope that I am halfway correct. With best wishes, Sydney -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: From sydney.shall at kcl.ac.uk Wed Mar 13 11:50:46 2013 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Wed, 13 Mar 2013 10:50:46 +0000 Subject: [Tutor] BMI calc Message-ID: <51405A06.6010303@kcl.ac.uk> On 13/03/2013 00:05, Soliman, Yasmin wrote: > Hello all, > > I'm new to python and its been a stuggle so far. I'm attempting to create a BMI calculator in Wing 101 4.1. I keep getting syntax errors: > > def calc_BMI(weight,height): > return (weight/(height*height))*703.0 > if bmi <=18.5: > print 'underweight' > elif bmi >= 18.5 and bmi <=24.9: > print 'normal weight' > elif bmi >=25 and bmi <=29.9: > print 'overweight' > elif bmi >=30: > print 'obese' > > Also, height should be converted to inches and I have not the slightest clue how to so. Any help would be much appreciated. > _______________________________________________ > Tutor maillist -Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Hi, I am also a newbie, but I wish to learn, so I offer the following corrections. Yes, as someone pointed out, it would be better if several of the print statements were return, as corrected below. # Note. I do note know what units you are using. # I would use scientific, metric units. So you need to divide both weight and height by a suitable conversion factors. # Then you will not need the number 703.0, and the units in the second and third lines would be Kg/m. [Kilogram/Metre) def calc_BMI(weight,height): bmi = (weight/(height*height))*703.0 print 'Your BMI is : ', BMI 'weight units/height units.' # You need to put the correct text here. if bmi <=18.5: return ' You are underweight.' if 18.5 <= bmi <= 24.9: return 'Your weight is in the normal range.' if 25.0 <= bmi <= 29.9: return 'You are overweight.' if bmi >= 30: return 'You are, I regret, obese.' I hope that I am halfway correct. With best wishes, Sydney -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: From altay at sympatico.ca Wed Mar 13 12:48:59 2013 From: altay at sympatico.ca (Altay Aksulu) Date: Wed, 13 Mar 2013 11:48:59 +0000 Subject: [Tutor] BMI calc In-Reply-To: References: Message-ID: Assuming the BMI formula is correct, the following is how I would have done it in Python 3. You can safely ignore the comments. If you want to run it, copy and paste the code into a text editor (you can delete the #comments), save it with a .py extension (e.g. bmi.py) and run it from within a terminal screen by typing at the shell prompt python3 bmi.py (in Windows command line you may not need the 3, I am not sure). If you need further conversions (e.g. converting height from ft-in to in or from ft-in to cms and so on) you can add a few more lines of code to do that. def main(): #it is good practice to modularize your program. Hence, this starts with a main() function. Defined here and called in the last line. w=float(input('Please enter your weight in pounds: ')) #You need to capture weight and height. input() built-in function is used to get the value that will be referenced by the w variable. h=float(input('Please enter your height in inches: ')) # Since input() always returns string type, float() -another built in function- is used to convert it to a real number. calc_BMI(w,h) #Here you call the BMI calculation function you wrote. Note that you are passing w and h values into this function. def calc_BMI(weight,height): #w and h will be assigned to weight and height -in that order- as parameter values. bmi=(weight/(height*height))*703.0 #actual calculation. the result is referenced by the bmi variable. if bmi<18.5: #removed the equal sign here. In your version 18.5 would have fallen into two categories. print('underweight') elif bmi>= 18.5 and bmi <=24.9: print('normal weight') elif bmi >=25 and bmi <=29.9: print('overweight') else: print('obese') main() Haven't tried but it should work. Altay Aksulu. From: tutor-request at python.org Subject: Tutor Digest, Vol 109, Issue 39 To: tutor at python.org Date: Wed, 13 Mar 2013 11:44:10 +0100 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..." --Forwarded Message Attachment-- From: ysoliman at uncc.edu To: breamoreboy at yahoo.co.uk; tutor at python.org Date: Wed, 13 Mar 2013 03:07:27 +0000 Subject: Re: [Tutor] BMI calc I'm using python 2.7, where exactly does the return statment with the (return (weight/(height*height))*703 calculation get posted in the function? def calc_BMI(weight,height): if bmi <=18.5: return 'underweight' elif bmi >= 18.5 and bmi <=24.9: return 'normal weight' elif bmi >=25 and bmi <=29.9: return 'overweight' elif bmi >=30: return 'obese' The user will need to input height ex) 5'3 and which will need to be split and stripped in order to convert to inches. ________________________________________ From: Tutor [tutor-bounces+ysoliman=uncc.edu at python.org] on behalf of Mark Lawrence [breamoreboy at yahoo.co.uk] Sent: Tuesday, March 12, 2013 10:29 PM To: tutor at python.org Subject: Re: [Tutor] BMI calc On 13/03/2013 02:08, Dave Angel wrote: > On 03/12/2013 09:46 PM, Mark Lawrence wrote: >> On 13/03/2013 00:05, Soliman, Yasmin wrote: >>> Hello all, >>> >>> I'm new to python and its been a stuggle so far. I'm attempting to >>> create a BMI calculator in Wing 101 4.1. I keep getting syntax errors: >>> >>> def calc_BMI(weight,height): >>> return (weight/(height*height))*703.0 >>> if bmi <=18.5: >>> print 'underweight' >>> elif bmi >= 18.5 and bmi <=24.9: >>> print 'normal weight' >>> elif bmi >=25 and bmi <=29.9: >>> print 'overweight' >>> elif bmi >=30: >>> print 'obese' >>> >>> Also, height should be converted to inches and I have not the >>> slightest clue how to so. Any help would be much appreciated. >>> _ >>> >> >> If you're using Python 3 you'll get syntax errors as print is a >> function, not a statement as in Python 2. Is this your problem? If not >> please cut and paste the exact syntax error for us to see. Then we'll >> sort the rest of the problems :) >> > > As Mark implies, tell us exactly what Python version you're using, and > copy/paste the entire error message, including traceback. > > For example, when I run it on 3.3, I have: > > davea at think2:~/temppython$ python3.3 soliman.py > File "soliman.py", line 6 > print 'underweight' > ^ > SyntaxError: invalid syntax > > > Also, could you tell us your experience level? You've defined a > function, but you haven't called it. And yet you're apparently trying > to use the results of calling it. > > As for converting height to inches, that depends on what you started > with. Since you're using the English version of the formula, you should > already have inches and pounds before calling that function. > > So perhaps in addition to missing the code for inputting the values > (perhaps the raw_input function), you're also missing the conversion > from "something" to inches. How are you getting the raw numbers, and > what units are they in? > > If the raw numbers are in meters and kg, then you'd want to remove the > multiply by 703. Or you could convert from meters to inches by > multiplying by 39.? (look up the exact number). And from kg to pounds > by a similar multiply by something like 2.2 > Of course if you've got the wrong algorithm you're wasting your time anyway, see for example http://www.newscientist.com/article/mg20928030.200-obesity-expert-a-better-fat-measure-than-bmi.html :) -- Cheers. Mark Lawrence _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor --Forwarded Message Attachment-- From: joskerc at gmail.com CC: breamoreboy at yahoo.co.uk; tutor at python.org To: ysoliman at uncc.edu Date: Wed, 13 Mar 2013 07:17:47 +0100 Subject: Re: [Tutor] BMI calc Hi, On Wed, Mar 13, 2013 at 4:07 AM, Soliman, Yasmin wrote: I'm using python 2.7, where exactly does the return statment with the (return (weight/(height*height))*703 calculation get posted in the function? def calc_BMI(weight,height): if bmi <=18.5: return 'underweight' elif bmi >= 18.5 and bmi <=24.9: return 'normal weight' elif bmi >=25 and bmi <=29.9: Following return is out of alignment. Should be at the same place in the line as the oters. return 'overweight' elif bmi >=30: return 'obese' The user will need to input height ex) 5'3 and which will need to be split and stripped in order to convert to inches. Exactly. Do you have a problem with this? If so what? Dreetz --Forwarded Message Attachment-- From: davea at davea.name To: tutor at python.org Date: Wed, 13 Mar 2013 03:10:40 -0400 Subject: Re: [Tutor] BMI calc On 03/13/2013 02:17 AM, Jos Kerc wrote: > Hi, > > > On Wed, Mar 13, 2013 at 4:07 AM, Soliman, Yasmin wrote: > >> >> >> def calc_BMI(weight,height): >> if bmi <=18.5: >> return 'underweight' >> elif bmi >= 18.5 and bmi <=24.9: >> return 'normal weight' >> elif bmi >=25 and bmi <=29.9: >> > > Following return is out of alignment. Should be at the same place in the > line as the oters. > > >> return 'overweight' It would certainly look prettier, but it's not a language requirement. Only within a single block do the columns have to line up exactly. > -- DaveA --Forwarded Message Attachment-- From: alan.gauld at btinternet.com To: tutor at python.org Date: Wed, 13 Mar 2013 08:36:05 +0000 Subject: Re: [Tutor] BMI calc On 13/03/13 03:07, Soliman, Yasmin wrote: > I'm using python 2.7, Then let us see the syntax errors because otherwise we are guessing. > where exactly does the return statment ... get posted in the function? I'm not sure what you mean by 'get posted' It is activated once the function is called. ie def foo(x): return 2 + x does nothing until I call it: result = foo(5) print result > def calc_BMI(weight,height): > if bmi <=18.5: > return 'underweight' Since BMI is a value your function is better as it was, just returning the value. The code to convert that BMI value into a weight assessment is better done outside, again as you had before. (Or inside another function, rateBMI(bmi) maybe) What was missing was some glue that joins those 2 things together: read weight and height call CalcBMI use result to assess weight. > elif bmi >= 18.5 and bmi <=24.9: > return 'normal weight' BTW in Python you can abbreviate the tests slightly with elif 18.5 <= bmi <= 24.9: print 'normal weight' HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ --Forwarded Message Attachment-- From: sydney.shall at kcl.ac.uk To: tutor at python.org Date: Wed, 13 Mar 2013 10:44:02 +0000 Subject: Re: [Tutor] BMI calc On 13/03/2013 00:05, Soliman, Yasmin wrote: Hello all, I'm new to python and its been a stuggle so far. I'm attempting to create a BMI calculator in Wing 101 4.1. I keep getting syntax errors: def calc_BMI(weight,height): return (weight/(height*height))*703.0 if bmi <=18.5: print 'underweight' elif bmi >= 18.5 and bmi <=24.9: print 'normal weight' elif bmi >=25 and bmi <=29.9: print 'overweight' elif bmi >=30: print 'obese' Also, height should be converted to inches and I have not the slightest clue how to so. Any help would be much appreciated. _______________________________________________ Tutor maillist - Tutor at python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Hi, I am also a newbie, but I wish to learn, so I offer the following corrections. # Note. I do note know what units you are using. # I would use scientific, metric units. So you need to divide both weight and height by a suitable conversion factors. # Then you will not need the number 703.0, and the units in the second and third lines would be Kg/m. [Kilogram/Metre) def calc_BMI(weight,height): bmi = (weight/(height*height))*703.0 print 'Your BMI is : ', BMI 'weight units/height units.' # You need to put the correct text here. if bmi <=18.5: print 'underweight' if 18.5 <= bmi <= 24.9: print 'normal weight' if 25.0 <= bmi <= 29.9: print 'overweight' if bmi >= 30: print 'obese' return I hope that I am halfway correct. With best wishes, Sydney -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Mar 13 13:21:13 2013 From: __peter__ at web.de (Peter Otten) Date: Wed, 13 Mar 2013 13:21:13 +0100 Subject: [Tutor] BMI calc References: <211A029E048A2245A6E00BA02FEFF88A581E29CB@BL2PRD0310MB373.namprd03.prod.outlook.com> <51405872.2030201@kcl.ac.uk> Message-ID: Shall, Sydney wrote: > I am also a newbie, but I wish to learn, so I offer the following > corrections. > # Note. I do note know what units you are using. > # I would use scientific, metric units. So you need to divide both > weight and height by a suitable conversion factors. > # Then you will not need the number 703.0, and the units in the second > and third lines would be Kg/m. [Kilogram/Metre) > > def calc_BMI(weight,height): > bmi = (weight/(height*height))*703.0 > print 'Your BMI is : ', BMI 'weight units/height units.' # You need to put the correct text here. > if bmi <=18.5: > print 'underweight' > if 18.5 <= bmi <= 24.9: > print 'normal weight' > if 25.0 <= bmi <= 29.9: > print 'overweight' > if bmi >= 30: > print 'obese' > return A problem that I have not seen addressed yet: What will this print for the guy who is 75.0 in high and weighs 200.0 lb? His bmi is >>> height = 75.0 >>> weight = 200.0 >>> weight/(height*height)*703.0 24.995555555555555 That's neither normal nor overweight, according to your categorisation. From sydney.shall at kcl.ac.uk Wed Mar 13 15:57:40 2013 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Wed, 13 Mar 2013 14:57:40 +0000 Subject: [Tutor] BMI calc In-Reply-To: References: <211A029E048A2245A6E00BA02FEFF88A581E29CB@BL2PRD0310MB373.namprd03.prod.outlook.com> <51405872.2030201@kcl.ac.uk> Message-ID: <514093E4.6040201@kcl.ac.uk> On 13/03/2013 12:21, Peter Otten wrote: > Shall, Sydney wrote: > >> I am also a newbie, but I wish to learn, so I offer the following >> corrections. >> # Note. I do note know what units you are using. >> # I would use scientific, metric units. So you need to divide both >> weight and height by a suitable conversion factors. >> # Then you will not need the number 703.0, and the units in the second >> and third lines would be Kg/m. [Kilogram/Metre) >> >> def calc_BMI(weight,height): >> bmi = (weight/(height*height))*703.0 >> print 'Your BMI is : ', BMI 'weight units/height units.' # You need > to put the correct text here. >> if bmi <=18.5: >> print 'underweight' >> if 18.5 <= bmi <= 24.9: >> print 'normal weight' >> if 25.0 <= bmi <= 29.9: >> print 'overweight' >> if bmi >= 30: >> print 'obese' >> return > A problem that I have not seen addressed yet: > > What will this print for the guy who is 75.0 in high and weighs 200.0 lb? > > His bmi is > >>>> height = 75.0 >>>> weight = 200.0 >>>> weight/(height*height)*703.0 > 24.995555555555555 > > That's neither normal nor overweight, according to your categorisation. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Yes, you are right, of course. Thanks for reminding me that we are dealing with floats. I should have used approximations, with an (epsilon) error range. I will remember if future, I hope. Sydney -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk From __peter__ at web.de Wed Mar 13 17:36:36 2013 From: __peter__ at web.de (Peter Otten) Date: Wed, 13 Mar 2013 17:36:36 +0100 Subject: [Tutor] BMI calc References: <211A029E048A2245A6E00BA02FEFF88A581E29CB@BL2PRD0310MB373.namprd03.prod.outlook.com> <51405872.2030201@kcl.ac.uk> <514093E4.6040201@kcl.ac.uk> Message-ID: Shall, Sydney wrote: > On 13/03/2013 12:21, Peter Otten wrote: >> Shall, Sydney wrote: >> >>> I am also a newbie, but I wish to learn, so I offer the following >>> corrections. >>> # Note. I do note know what units you are using. >>> # I would use scientific, metric units. So you need to divide both >>> weight and height by a suitable conversion factors. >>> # Then you will not need the number 703.0, and the units in the second >>> and third lines would be Kg/m. [Kilogram/Metre) >>> >>> def calc_BMI(weight,height): >>> bmi = (weight/(height*height))*703.0 >>> print 'Your BMI is : ', BMI 'weight units/height units.' # You >>> need >> to put the correct text here. >>> if bmi <=18.5: >>> print 'underweight' >>> if 18.5 <= bmi <= 24.9: >>> print 'normal weight' >>> if 25.0 <= bmi <= 29.9: >>> print 'overweight' >>> if bmi >= 30: >>> print 'obese' >>> return >> A problem that I have not seen addressed yet: >> >> What will this print for the guy who is 75.0 in high and weighs 200.0 lb? >> >> His bmi is >> >>>>> height = 75.0 >>>>> weight = 200.0 >>>>> weight/(height*height)*703.0 >> 24.995555555555555 >> >> That's neither normal nor overweight, according to your categorisation. > Yes, you are right, of course. > Thanks for reminding me that we are dealing with floats. > I should have used approximations, with an (epsilon) error range. > I will remember if future, I hope. The solution I had in mind is simpler: if bmi < 18.5: print "underweight" elif bmi < 25: print "normal" elif bmi < 30: print "overweight" else: print "obese" These give you effectively half-open intervals 18.5 <= bmi < 25 # normal 25 <= bmi < 30 # overweight but each test relies on the result of the previous ones. From fomcl at yahoo.com Wed Mar 13 18:03:56 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 13 Mar 2013 10:03:56 -0700 (PDT) Subject: [Tutor] BMI calc In-Reply-To: References: <211A029E048A2245A6E00BA02FEFF88A581E29CB@BL2PRD0310MB373.namprd03.prod.outlook.com> <51405872.2030201@kcl.ac.uk> <514093E4.6040201@kcl.ac.uk> Message-ID: <1363194236.98864.YahooMailNeo@web163802.mail.gq1.yahoo.com> >> Yes, you are right, of course. >> Thanks for reminding me that we are dealing with floats. >> I should have used approximations, with an (epsilon) error range. >> I will remember if future, I hope. > > The solution I had in mind is simpler: > > if bmi < 18.5: > ? ? print "underweight" > elif bmi < 25: > ? ? print "normal" > elif bmi < 30: > ? ? print "overweight" > else: > ? ? print "obese" How about this approach? the "if" statements are simpler=better, but this is fun too! ? import bisect ? def getBMI(height, weight, cutoffs=[18, 25, 30], ?????????? categories=('under', 'normal', 'obese', 'morbidly')): ??? bmi = weight / float(height ** 2) ????return categories[bisect.bisect(cutoffs, bmi)] ? cutoffs=[18, 25, 30] categories =('skinny', 'normal', 'teddybear', 'huge teddybear') print getBMI(1.82, 180, cutoffs, categories) -------------- next part -------------- An HTML attachment was scrubbed... URL: From abhishek.vit at gmail.com Wed Mar 13 20:50:28 2013 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Wed, 13 Mar 2013 12:50:28 -0700 Subject: [Tutor] increment a counter inside generator Message-ID: Hey Guys I might be missing something obvious here. import numpy as np count = 0 [ count += 1 for num in np.random.random_integers(1,100,20) if num > 20] File "", line 2 [ count += 1 for num in np.random.random_integers(1,100,20) if num > 20] ^ SyntaxError: invalid syntax Also tried From oscar.j.benjamin at gmail.com Wed Mar 13 22:02:23 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 13 Mar 2013 21:02:23 +0000 Subject: [Tutor] increment a counter inside generator In-Reply-To: References: Message-ID: On 13 March 2013 19:50, Abhishek Pratap wrote: > Hey Guys > > I might be missing something obvious here. > > > import numpy as np > > count = 0 > [ count += 1 for num in np.random.random_integers(1,100,20) if num > 20] > > File "", line 2 > [ count += 1 for num in np.random.random_integers(1,100,20) if num > 20] > ^ > SyntaxError: invalid syntax I think this does what you want: >>> import numpy as np >>> a = np.random.random_integers(1, 100, 20) >>> (a > 20).sum() 17 I don't know if this really applies to what you're doing but the result of this computation is a binomially distributed random number that you could generate directly (without creating the intermediate array): >>> np.random.binomial(100, .2) 26 Oscar From davea at davea.name Wed Mar 13 22:08:47 2013 From: davea at davea.name (Dave Angel) Date: Wed, 13 Mar 2013 17:08:47 -0400 Subject: [Tutor] increment a counter inside generator In-Reply-To: References: Message-ID: <5140EADF.9080001@davea.name> On 03/13/2013 03:50 PM, Abhishek Pratap wrote: > Hey Guys > > I might be missing something obvious here. > > > import numpy as np > > count = 0 > [ count += 1 for num in np.random.random_integers(1,100,20) if num > 20] > > File "", line 2 > [ count += 1 for num in np.random.random_integers(1,100,20) if num > 20] > ^ > SyntaxError: invalid syntax > > > Also tried > I can't help with the numpy portion of that, but that's not the correct syntax for a list comprehension. The first item must be an expression, and count+=1 is NOT. You probably want (untested) count = sum([ 1 for num in ......]) which will add a bunch of ones. That will probably give you a count of how many of the random integers are > 20. There also may very well be a function in numpy that would do it in one step. See Oscar's message. -- DaveA From abhishek.vit at gmail.com Wed Mar 13 22:12:22 2013 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Wed, 13 Mar 2013 14:12:22 -0700 Subject: [Tutor] increment a counter inside generator In-Reply-To: References: Message-ID: On Wed, Mar 13, 2013 at 2:02 PM, Oscar Benjamin wrote: > On 13 March 2013 19:50, Abhishek Pratap wrote: >> Hey Guys >> >> I might be missing something obvious here. >> >> >> import numpy as np >> >> count = 0 >> [ count += 1 for num in np.random.random_integers(1,100,20) if num > 20] >> >> File "", line 2 >> [ count += 1 for num in np.random.random_integers(1,100,20) if num > 20] >> ^ >> SyntaxError: invalid syntax > > I think this does what you want: > >>>> import numpy as np >>>> a = np.random.random_integers(1, 100, 20) >>>> (a > 20).sum() > 17 > > I don't know if this really applies to what you're doing but the > result of this computation is a binomially distributed random number > that you could generate directly (without creating the intermediate > array): > >>>> np.random.binomial(100, .2) > 26 > > > Oscar Hi Oscar I just used a very contrived example to ask if we can increment a counter inside a generator. The real case is more specific and dependent on other code and not necessarily useful for the question. -Abhi From abhishek.vit at gmail.com Wed Mar 13 22:15:48 2013 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Wed, 13 Mar 2013 14:15:48 -0700 Subject: [Tutor] increment a counter inside generator In-Reply-To: <5140EADF.9080001@davea.name> References: <5140EADF.9080001@davea.name> Message-ID: On Wed, Mar 13, 2013 at 2:08 PM, Dave Angel wrote: > On 03/13/2013 03:50 PM, Abhishek Pratap wrote: >> >> Hey Guys >> >> I might be missing something obvious here. >> >> >> import numpy as np >> >> count = 0 >> [ count += 1 for num in np.random.random_integers(1,100,20) if num > 20] >> >> File "", line 2 >> [ count += 1 for num in np.random.random_integers(1,100,20) if num > >> 20] >> ^ >> SyntaxError: invalid syntax >> >> >> Also tried >> > > > I can't help with the numpy portion of that, but that's not the correct > syntax for a list comprehension. The first item must be an expression, and > count+=1 is NOT. > > You probably want (untested) > count = sum([ 1 for num in ......]) > > which will add a bunch of ones. That will probably give you a count of how > many of the random integers are > 20. > > There also may very well be a function in numpy that would do it in one > step. See Oscar's message. > > -- > DaveA > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor Thanks Dave. That probably is the reason why I am getting the error. -Abhi From jmz at kontrol.kode5.net Mon Mar 11 12:49:59 2013 From: jmz at kontrol.kode5.net (James Griffin) Date: Mon, 11 Mar 2013 11:49:59 +0000 Subject: [Tutor] python on ipad In-Reply-To: <315460BC-0389-4E18-B7EF-0C4E1D7CA47E@gmail.com> References: <315460BC-0389-4E18-B7EF-0C4E1D7CA47E@gmail.com> Message-ID: <20130311114959.GA84@kontrol.kode5.net> [--------- Sun 10.Mar'13 at 16:42:59 -0500 Benjamin Fishbein :---------] > Hello. I wrote some python programs for my small business that I run on my computer...macbook air. I'm planning to backpack around Mexico and perhaps south america. I'll still be working though. Basically my computer does all the work, I just need to have internet connections and run the programs, and periodically click here and there. > I don't want to take my macbook with me because I'd have anxiety that it'd get stolen and I wouldn't have any fun. > So I'm debating if I should get a cheap computer for a couple hundred bucks and run the python scripts on it. I think this is possible because I hear the code is the same whether it's mac or PC or whatever. > Or I might take my ipad with me. Or just run it on my iphone. > Do you know if it's possible to run python scripts on a ipad/iphone, and if so how to do it? > Thanks, > Ben An iPad will be far more atttractive to a thief than a laptop, Mac or otherwise. Just get a cheap laptop and put linux on it. You can use your python programs on that easily enough. From joshjwilkerson at yahoo.com Wed Mar 13 16:12:33 2013 From: joshjwilkerson at yahoo.com (Joshua Wilkerson) Date: Wed, 13 Mar 2013 08:12:33 -0700 (PDT) Subject: [Tutor] Help Message-ID: <1363187553.73209.YahooMailNeo@web121601.mail.ne1.yahoo.com> Can you help me with something? This code (it also draws from the text_game file) says it has a syntax error, but I can't seem to find what it is, I think the code is having a fit but I'm not sure. I'm appreciative to all hep. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: P1P3.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: text_game.py URL: From joshjwilkerson at yahoo.com Wed Mar 13 16:14:31 2013 From: joshjwilkerson at yahoo.com (Joshua Wilkerson) Date: Wed, 13 Mar 2013 08:14:31 -0700 (PDT) Subject: [Tutor] p.s. Message-ID: <1363187671.91381.YahooMailNeo@web121601.mail.ne1.yahoo.com> It was even giving me a syntax error when said code was in a comment. -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Wed Mar 13 22:23:43 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 13 Mar 2013 21:23:43 +0000 Subject: [Tutor] increment a counter inside generator In-Reply-To: References: Message-ID: On 13 March 2013 21:12, Abhishek Pratap wrote: > On Wed, Mar 13, 2013 at 2:02 PM, Oscar Benjamin > wrote: >> On 13 March 2013 19:50, Abhishek Pratap wrote: >>> Hey Guys >>> >>> I might be missing something obvious here. >>> >>> >>> import numpy as np >>> >>> count = 0 >>> [ count += 1 for num in np.random.random_integers(1,100,20) if num > 20] >>> >>> File "", line 2 >>> [ count += 1 for num in np.random.random_integers(1,100,20) if num > 20] >>> ^ >>> SyntaxError: invalid syntax [SNIP] > > I just used a very contrived example to ask if we can increment a > counter inside a generator. The real case is more specific and > dependent on other code and not necessarily useful for the question. Ok, so can you be more specific about the effect that you are trying to achieve? Do you want to know the length of the list (equivalent to Dave's suggestion)? len([num for num in np.random.random_integers(1,100,20) if num > 20]) Or is it that you want to use count in the expression in the list comprehension (it's not actually a generator by the way)? You can achieve this with enumerate and an inner generator: data = np.random.random_integers(1, 100, 20) [x + count for count, x in enumerate(n for n in data if n > 2)] If your case is much more complicated than this then personally I would write a generator function rather than use a comprehension. Then you can increment variables or anything else just like normal. Oscar From alan.gauld at btinternet.com Wed Mar 13 22:35:55 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 13 Mar 2013 21:35:55 +0000 Subject: [Tutor] Help In-Reply-To: <1363187553.73209.YahooMailNeo@web121601.mail.ne1.yahoo.com> References: <1363187553.73209.YahooMailNeo@web121601.mail.ne1.yahoo.com> Message-ID: On 13/03/13 15:12, Joshua Wilkerson wrote: > Can you help me with something? This code (it also draws from the > text_game file) says it has a syntax error, Don't make us guess, post the error message. It will tell us where. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From oscar.j.benjamin at gmail.com Wed Mar 13 22:39:35 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 13 Mar 2013 21:39:35 +0000 Subject: [Tutor] Help In-Reply-To: <1363187553.73209.YahooMailNeo@web121601.mail.ne1.yahoo.com> References: <1363187553.73209.YahooMailNeo@web121601.mail.ne1.yahoo.com> Message-ID: On 13 March 2013 15:12, Joshua Wilkerson wrote: > Can you help me with something? This code (it also draws from the text_game > file) says it has a syntax error, but I can't seem to find what it is, I > think the code is having a fit but I'm not sure. I'm appreciative to all > hep. Could you perhaps copy and paste the entire error message here? Usually it says the line on which the error occurs, shows that line and a pointer to where there error is, e.g.: $ python tmp.py File "tmp.py", line 9 [count+=1 for n in range()] ^ SyntaxError: invalid syntax Oscar From davea at davea.name Wed Mar 13 22:48:49 2013 From: davea at davea.name (Dave Angel) Date: Wed, 13 Mar 2013 17:48:49 -0400 Subject: [Tutor] p.s. In-Reply-To: <1363187671.91381.YahooMailNeo@web121601.mail.ne1.yahoo.com> References: <1363187671.91381.YahooMailNeo@web121601.mail.ne1.yahoo.com> Message-ID: <5140F441.9000304@davea.name> On 03/13/2013 11:14 AM, Joshua Wilkerson wrote: > It was even giving me a syntax error when said code was in a comment. > > > Really useful question, where you break the thread, change the subject, don't quote anything from earlier, and don't bother identifying anything about your environment. Good luck with that. -- DaveA From alan.gauld at btinternet.com Wed Mar 13 23:08:35 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 13 Mar 2013 22:08:35 +0000 Subject: [Tutor] p.s. In-Reply-To: <5140F441.9000304@davea.name> References: <1363187671.91381.YahooMailNeo@web121601.mail.ne1.yahoo.com> <5140F441.9000304@davea.name> Message-ID: On 13/03/13 21:48, Dave Angel wrote: > On 03/13/2013 11:14 AM, Joshua Wilkerson wrote: >> It was even giving me a syntax error when said code was in a comment. > > Really useful question, where you break the thread, change the subject, > don't quote anything from earlier, and don't bother identifying anything > about your environment. Good luck with that. To be fair this was sitting in the moderation queue which I just belatedly flushed and they would have come through within seconds of each other in normal use. But in general I agree it's not too helpful in identifying the issue... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ramit.prasad at jpmorgan.com Wed Mar 13 23:01:06 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 13 Mar 2013 22:01:06 +0000 Subject: [Tutor] python on ipad In-Reply-To: <20130311114959.GA84@kontrol.kode5.net> References: <315460BC-0389-4E18-B7EF-0C4E1D7CA47E@gmail.com> <20130311114959.GA84@kontrol.kode5.net> Message-ID: <5B80DD153D7D744689F57F4FB69AF4741823F52E@SCACMX008.exchad.jpmchase.net> James Griffin wrote: > [--------- Sun 10.Mar'13 at 16:42:59 -0500 Benjamin Fishbein :---------] > > > Hello. I wrote some python programs for my small business that I run on my computer...macbook air. > I'm planning to backpack around Mexico and perhaps south america. I'll still be working though. > Basically my computer does all the work, I just need to have internet connections and run the > programs, and periodically click here and there. > > I don't want to take my macbook with me because I'd have anxiety that it'd get stolen and I wouldn't > have any fun. > > So I'm debating if I should get a cheap computer for a couple hundred bucks and run the python > scripts on it. I think this is possible because I hear the code is the same whether it's mac or PC or > whatever. > > Or I might take my ipad with me. Or just run it on my iphone. > > Do you know if it's possible to run python scripts on a ipad/iphone, and if so how to do it? > > Thanks, > > Ben > > An iPad will be far more atttractive to a thief than a laptop, Mac or otherwise. Just get a cheap > laptop and put linux on it. You can use your python programs on that easily enough. On the flip side, iPads are easier to carry and secure (especially for international customs/security). I can walk around with it easily, so am unlikely to leave it anywhere to get stolen. Many laptops are cheaper than new iPads and have more generic utility, but also can be harder to charge and the batteries don't always last as long. A USB port is probably pretty easy to find, not sure if you need an voltage/plug transformer where the OP is going. I would probably go cheap laptop if the OP can afford it, but then I think I would have an eye on it for a headless server, htpc or a million other uses for a spare laptop after the trip (if I did not sell it). Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From davea at davea.name Thu Mar 14 01:20:43 2013 From: davea at davea.name (Dave Angel) Date: Wed, 13 Mar 2013 20:20:43 -0400 Subject: [Tutor] Fwd: Which databases allow lists as record fields? In-Reply-To: References: Message-ID: <514117DB.4080900@davea.name> I presume you meant this for the tutor list. I don't have any answers for the question. -------- Original Message -------- Subject: [Tutor] Which databases allow lists as record fields? Date: Thu, 14 Mar 2013 10:59:27 +1100 From: DoanVietTrungAtGmail To: Dave Angel Dear tutors To elaborate on my above question, I mean: Which database (which a Python program can access) allows a record to have not just simple fields but also fields that are variable-length lists? For my application, records in one database table might have 1 list, those in another have, say, 4. Each list has a variable number of integers, no list contains embedded lists. The purpose of asking this question is to know which database to learn. Before asking this question, I looked at Alan Gauld's SQLite tutorialand the list of data types in W3school's SQL tute, plus a few Google searches. Trung Doan From alan.gauld at btinternet.com Thu Mar 14 02:08:47 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 14 Mar 2013 01:08:47 +0000 Subject: [Tutor] Fwd: Which databases allow lists as record fields? In-Reply-To: <514117DB.4080900@davea.name> References: <514117DB.4080900@davea.name> Message-ID: > To elaborate on my above question, I mean: Which database (which a Python > program can access) allows a record to have not just simple fields but also > fields that are variable-length lists? You don't. You create a second table to hold the list. Then in the second table you include be reference back to the first. For example an order may have a list of order items. You don't create an order_item field with multiple values. Instead you create a new order_Item table. Each order_item has a reference to the owning order. That concept is fundamental to relational database theory > > For my application, records in one database table might have 1 list, those > in another have, say, 4. Each list has a variable number of integers, no > list contains embedded lists. > > The purpose of asking this question is to know which database to learn. > > Before asking this question, I looked at Alan Gauld's SQLite > tutorialand the list > of data types in W3school's SQL > tute, > plus a few Google searches. > > Trung Doan > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From knupp at well.com Thu Mar 14 02:13:09 2013 From: knupp at well.com (David Knupp) Date: Wed, 13 Mar 2013 18:13:09 -0700 (PDT) Subject: [Tutor] increment a counter inside generator In-Reply-To: References: Message-ID: On Wed, 13 Mar 2013, Oscar Benjamin wrote: > (it's not actually a generator by the way) As Oscar points out, you're not working with a generator expression. The syntactical difference between a list comprehension and a generator expression is subtle. List comprehensions use square brackets, but generator expressions use parentheses. >>> foo = [n for n in xrange(10)] >>> foo [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> bar = (n for n in xrange(10)) >>> bar FWIW, if you're working with very large lists, but don't need to create the full list in memory, then a generator expression is usually preferred. To get the number of items a generator would return, you can use sum() like this: >>> gen = (n for n in xrange(some_really_huge_number)) >>> sum(1 for n in gen) # outputs some_really_huge_number --dk. From cfuller084 at thinkingplanet.net Thu Mar 14 01:35:35 2013 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Wed, 13 Mar 2013 19:35:35 -0500 Subject: [Tutor] Fwd: Which databases allow lists as record fields? In-Reply-To: <514117DB.4080900@davea.name> References: <514117DB.4080900@davea.name> Message-ID: <201303131935.35419.cfuller084@thinkingplanet.net> Use pickle to serialize the list, then use any DB that takes strings of arbitrary length. You will probably be frustrated if you seek a (useful) DB that has native support for such things. Cheers On Wednesday, March 13, 2013, Dave Angel wrote: > I presume you meant this for the tutor list. I don't have any answers > for the question. > > > -------- Original Message -------- > Subject: [Tutor] Which databases allow lists as record fields? > Date: Thu, 14 Mar 2013 10:59:27 +1100 > From: DoanVietTrungAtGmail > To: Dave Angel > > Dear tutors > > To elaborate on my above question, I mean: Which database (which a Python > program can access) allows a record to have not just simple fields but also > fields that are variable-length lists? > > For my application, records in one database table might have 1 list, those > in another have, say, 4. Each list has a variable number of integers, no > list contains embedded lists. > > The purpose of asking this question is to know which database to learn. > > Before asking this question, I looked at Alan Gauld's SQLite > tutorialand the list > of data types in W3school's SQL > tute, > plus a few Google searches. > > Trung Doan > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From doanviettrung at gmail.com Thu Mar 14 02:39:17 2013 From: doanviettrung at gmail.com (DoanVietTrungAtGmail) Date: Thu, 14 Mar 2013 12:39:17 +1100 Subject: [Tutor] Fwd: Which databases allow lists as record fields? In-Reply-To: References: <514117DB.4080900@davea.name> Message-ID: .. > You don't. You create a second table to hold the list. > Then in the second table you include be reference back to the first. > I thought about that but thought it seemed a roundabout way. But assuming I do it that way, how to deal with variable-length list? Most lists have 10^3, but some can grow to perhaps 10^7 items. A fixed record structure to fit the longest possible record would make the database table sparse and, presumably, waste space. An alternative I thought of was to use SQL Server fields for XML, or varchar variable-length character strings containing 10^9 characters, then to read the list I'd parse the XML or split the string into literal integers then convert to int. I wanted to avoid this computation cost if possible. Trung ======== > >> For my application, records in one database table might have 1 list, those >> in another have, say, 4. Each list has a variable number of integers, no >> list contains embedded lists. >> >> The purpose of asking this question is to know which database to learn. >> >> Before asking this question, I looked at Alan Gauld's SQLite >> tutorial>and >> the list >> of data types in W3school's SQL >> tute >> >, >> plus a few Google searches. >> >> Trung Doan >> >> >> >> ______________________________**_________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/**mailman/listinfo/tutor >> >> > > -- > Alan G > 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 breamoreboy at yahoo.co.uk Thu Mar 14 02:46:53 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 14 Mar 2013 01:46:53 +0000 Subject: [Tutor] increment a counter inside generator In-Reply-To: References: Message-ID: On 14/03/2013 01:13, David Knupp wrote: > On Wed, 13 Mar 2013, Oscar Benjamin wrote: >> (it's not actually a generator by the way) > > As Oscar points out, you're not working with a generator expression. The > syntactical difference between a list comprehension and a generator > expression is subtle. List comprehensions use square brackets, but > generator expressions use parentheses. > >>>> foo = [n for n in xrange(10)] >>>> foo > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>>> bar = (n for n in xrange(10)) >>>> bar > > > FWIW, if you're working with very large lists, but don't need to create > the full list in memory, then a generator expression is usually > preferred. To get the number of items a generator would return, you can > use sum() like this: > >>>> gen = (n for n in xrange(some_really_huge_number)) >>>> sum(1 for n in gen) # outputs some_really_huge_number > > --dk. There is little point in creating a generator from an xrange object. Quoting from http://docs.python.org/2/library/stdtypes.html#typesseq-xrange "The xrange type is an immutable sequence which is commonly used for looping. The advantage of the xrange type is that an xrange object will always take the same amount of memory, no matter the size of the range it represents. There are no consistent performance advantages." -- Cheers. Mark Lawrence From steve at pearwood.info Thu Mar 14 02:45:55 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 14 Mar 2013 12:45:55 +1100 Subject: [Tutor] increment a counter inside generator In-Reply-To: References: Message-ID: <51412BD3.6010603@pearwood.info> On 14/03/13 08:12, Abhishek Pratap wrote: >>> import numpy as np >>> >>> count = 0 >>> [ count += 1 for num in np.random.random_integers(1,100,20) if num > 20] >>> >>> File "", line 2 >>> [ count += 1 for num in np.random.random_integers(1,100,20) if num > 20] >>> ^ >>> SyntaxError: invalid syntax [...] > I just used a very contrived example to ask if we can increment a > counter inside a generator. The real case is more specific and > dependent on other code and not necessarily useful for the question. Not everything can happen inside a list comprehension or generator comprehension. They are both deliberately kept simple, and can only include an expression. Since count += 1 is not an expression, you cannot use it directly inside a list comp. Some possible solutions: 1) wrap it in a helper function: count = 0 def incr(): global count count += 1 values = [incr() or expr for num in np.random.random_integers(1, 100, 20) if num > 20] 2) Use a for loop: count = 0 for num in np.random.random_integers(1, 100, 20): if num > 20: count += 1 3) Use len: values = [num for num in np.random.random_integers(1, 100, 20) if num > 20] # or if you prefer: # values = filter(lambda x: x > 20, np.random.random_integers(1, 100, 20)) count = len(values) 4) Use sum: count = sum(1 for num in np.random.random_integers(1, 100, 20) if num > 20) -- Steven From steve at pearwood.info Thu Mar 14 02:59:04 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 14 Mar 2013 12:59:04 +1100 Subject: [Tutor] increment a counter inside generator In-Reply-To: References: Message-ID: <51412EE8.1050806@pearwood.info> On 14/03/13 12:13, David Knupp wrote: > FWIW, if you're working with very large lists, but don't need to create the full list in memory, then a generator expression is usually preferred. To get the number of items a generator would return, you can use sum() like this: > >>>> gen = (n for n in xrange(some_really_huge_number)) >>>> sum(1 for n in gen) # outputs some_really_huge_number Don't do that. You already know how many items you have, because you created the xrange object: count = some_really_huge_number If you didn't create the xrange object yourself, or if you can't easily tell how many items it will include, remember that xrange objects support the len function: py> x = xrange(23, 1987639292, 17) py> len(x) 116919957 If you have some unknown, arbitrary iterable that doesn't support len(), then you can use the sum() trick: it = some_unknown_iterable() sum(1 for x in it) There is almost never any reason to write a list comprehension or generator expression that merely walks over an iterable, without doing any further processing: (x for x in iterable) is just like iterable, only slower because it is indirect. -- Steven From doanviettrung at gmail.com Thu Mar 14 03:08:45 2013 From: doanviettrung at gmail.com (DoanVietTrungAtGmail) Date: Thu, 14 Mar 2013 13:08:45 +1100 Subject: [Tutor] Fwd: Which databases allow lists as record fields? In-Reply-To: <201303131935.35419.cfuller084@thinkingplanet.net> References: <514117DB.4080900@davea.name> <201303131935.35419.cfuller084@thinkingplanet.net> Message-ID: I saw your (Chris') reply after replying to Alan. So, the answer from both of you is No, not native. I've just read that MySQL is free and has a data type called LONGTEXT storing up to 4x10^9 char. Hurrah! As to SQL Server, I've just read that it "could take a small independent company?s budget and eat it for lunch". That's scary. Thanks Chris, thanks Alan! Trung ========= On Thu, Mar 14, 2013 at 11:35 AM, Chris Fuller < cfuller084 at thinkingplanet.net> wrote: > > Use pickle to serialize the list, then use any DB that takes strings of > arbitrary length. You will probably be frustrated if you seek a (useful) > DB > that has native support for such things. > > Cheers > > On Wednesday, March 13, 2013, Dave Angel wrote: > > I presume you meant this for the tutor list. I don't have any answers > > for the question. > > > > > > -------- Original Message -------- > > Subject: [Tutor] Which databases allow lists as record fields? > > Date: Thu, 14 Mar 2013 10:59:27 +1100 > > From: DoanVietTrungAtGmail > > To: Dave Angel > > > > Dear tutors > > > > To elaborate on my above question, I mean: Which database (which a Python > > program can access) allows a record to have not just simple fields but > also > > fields that are variable-length lists? > > > > For my application, records in one database table might have 1 list, > those > > in another have, say, 4. Each list has a variable number of integers, no > > list contains embedded lists. > > > > The purpose of asking this question is to know which database to learn. > > > > Before asking this question, I looked at Alan Gauld's SQLite > > tutorialand the list > > of data types in W3school's SQL > > tute, > > plus a few Google searches. > > > > Trung Doan > > > > > > > > _______________________________________________ > > 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 steve at pearwood.info Thu Mar 14 03:38:24 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 14 Mar 2013 13:38:24 +1100 Subject: [Tutor] Help In-Reply-To: <1363187553.73209.YahooMailNeo@web121601.mail.ne1.yahoo.com> References: <1363187553.73209.YahooMailNeo@web121601.mail.ne1.yahoo.com> Message-ID: <51413820.9040601@pearwood.info> On 14/03/13 02:12, Joshua Wilkerson wrote: > Can you help me with something? This code (it also draws from the text_game file) says it has a syntax error, but I can't seem to find what it is, I think the code is having a fit but I'm not sure. I'm appreciative to all hep. The most valuable help we can give you is to teach you to help yourself, and to learn what not to do. Here are some Do Nots: - Do not expect us to read through hundreds of lines of code looking for the error. - Do not expect us to save your files and then run them. We have no idea what they will do, you might be trying to trick us into running harmful code. Unless we read through all your code and study it carefully, we can't know if it is safe. - Even if we trust you AND trust your code, we're volunteers, not servants. We're only going to install your code and run it if you pay us, or if your problem seems so interesting that we want to solve the problem no matter how much work it takes. Unfortunately, "a syntax error" does not sound interesting. - Don't assume that Python is "having a fit". Trust me, hundreds of thousands or millions of people have used Python for 20+ years now. No software is perfect and bug free, but trust me, the chances that you have discovered a bug that nobody before you has ever seen is remote. 99.99% of the bugs you experience as a programmer will be bugs in *your* code, not the language. (But don't worry, you'll soon learn to fix those bugs so quickly you won't even remember them.) And here are some Dos: - The most valuable thing you can do right now is learn how to read and understand the error messages that Python gives you. There is a lot of information buried in them. And usually not buried very deeply, often all you need to do is read it and it will tell you what went wrong. (At least once you get experiences enough to know how to interpret the error.) Compared to some other languages, Python's error messages are a paragon of clarity and simplicity. See below for more on this one. - If you have trouble with an error that you can't solve yourself, make it easy for us to help you: * The absolute LEAST you need to do is copy and paste the entire traceback, starting with the line "Traceback (most recent call last)" all the way to the end, including the error message. SyntaxErrors may not have a Traceback line, but you should still copy and paste the entire message. * Better still, if you can, try to SIMPLIFY the problem to the smallest amount of code that displays the same error. Nine times out of ten, by going through this process of simplifying the code, *you* will discover what the error was, and solve the problem yourself. The tenth time, you will then have a nice, simple piece of code that you can show us, instead of hundreds and hundreds of lines that we won't read. See this website for more detail: http://sscce.org/ Although it is written for Java programmers, the lessons it gives apply to any language. * Remember to mention what version of Python you are using, and what operating system. (Windows, Linux, Mac, something else?) If you are using a less common Python compiler, like IronPython or Jython, say so. If you are running your code via an IDE like IDLE or IPython, say so. Now for this specific error. You are getting a SyntaxError. Unfortunately, syntax errors sometimes give the least informative error messages in Python. But fortunately you can still work out what is wrong: py> for x = range(1, 2): File "", line 1 for x = range(1, 2): ^ SyntaxError: invalid syntax Notice the small caret ^ on a line on its own? In your email, it may not line up correctly, but if you read the error in context, in the Python compiler or IDE where it occurs, it will line up with the first thing that Python found that was broken syntax. In this case, you simply cannot use assignment, "x = something", inside the for line. The right syntax is "for x in range(1, 20)". Here's another example: py> x = 23*)1+5) File "", line 1 x = 23*)1+5) ^ SyntaxError: invalid syntax Here the caret should line up under the left-most parenthesis (round bracket). The solution is to use the open-bracket, not close-bracket. A common error is to use too few closing brackets. py> x = 23*(1 + (15 - 7) ... y = x + 1 File "", line 2 y = x + 1 ^ SyntaxError: invalid syntax See what happens here? The error, the missing bracket, is on the *previous* line. That's because Python cannot tell that it is truly missing until it gets to the next line. So if you have a Syntax Error on a line that looks right, or that is a comment, *work backwards*, line by line, until you find something that is missing a closing bracket. -- Steven From __peter__ at web.de Thu Mar 14 09:43:14 2013 From: __peter__ at web.de (Peter Otten) Date: Thu, 14 Mar 2013 09:43:14 +0100 Subject: [Tutor] Fwd: Which databases allow lists as record fields? References: <514117DB.4080900@davea.name> Message-ID: DoanVietTrungAtGmail wrote: >> You don't. You create a second table to hold the list. >> Then in the second table you include be reference back to the first. >> > > I thought about that but thought it seemed a roundabout way. But assuming > I do it that way, how to deal with variable-length list? Most lists have > 10^3, but some can grow to perhaps 10^7 items. A fixed record structure to > fit the longest possible record would make the database table sparse and, > presumably, waste space. You are misunderstanding Alan, there is nothing "fixed" in his approach. Instead of one table, e. g. holding student name and a list of courses taken by the student students_with_courses studendId | name | courses -------------------------------------------- 1 | Jim | [maths, biology, english] 2 | Sue | [chemistry, spanish] you have two tables students studendId | name ---------------- 1 | Jim 2 | Sue courses studentId | coursename ---------------------- 1 | maths 1 | biology 1 | english 2 | chemistry 2 | spanish To find out Sue's courses you'd do two queries: (1) Find out the studentId sql = "select studentId from students where name = ?" studentID = cursor.execute(sql, ["Sue"]).fetchone()[0] (2) Find the corresponding courses sql = select coursename from courses where studentId = ?" for row in cursor.execute(sql, [studentId]).fetchall(): print row[0] PS: A realistic use case would introduce a third table to hold course information and the table connecting courses and students would hold the studentId and the courseId. From alan.gauld at btinternet.com Thu Mar 14 10:13:15 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 14 Mar 2013 09:13:15 +0000 Subject: [Tutor] Fwd: Which databases allow lists as record fields? In-Reply-To: References: <514117DB.4080900@davea.name> Message-ID: On 14/03/13 01:39, DoanVietTrungAtGmail wrote: > You don't. You create a second table to hold the list. > Then in the second table you include be reference back to the first. > > assuming I do it that way, how to deal with variable-length list? Most > lists have 10^3, but some can grow to perhaps 10^7 items. A fixed record > structure to fit the longest possible record would make the database > table sparse and, presumably, waste space. I'm not sure what you mean here but the tables are not fixed size. Usually you are only limited by the size of your hard drive. To give an example if you have an object MyType with two of these list type attributes called foo and bar. We have two instances of MyType, A and B. A has 10 foos and 50 bars while B has 500 foos and 1000 bars. Create a table MyType and populate it with A and B Create a Table MyType_foo and populate it with 10 rows referencing A and 500 rows referencing B Create a table Mytype_bar and populate it with 50 rows referencing A and 1000 rows referencing bar Now to see all the foos for A use select value from foo where parent = A or for B use select value from foo whee parent = B and the same for bar... You can keep adding rows to foo or bar for as long as ypou like. Youb can add new MyType rows and then add more rows to MyType_foo and bar which reference thiose new MyTypes. There is no limit to how many items you add until your disk fills up! > An alternative I thought of was to use SQL Server fields for XML, or > varchar variable-length character strings containing 10^9 characters, > then to read the list I'd parse the XML or split the string into literal > integers then convert to int. I wanted to avoid this computation cost if > possible. You can do this but you might as well just store everything in XML in a flat file. You lose the power of the database query language to search/filter the results and give yourself a huge development/test/maintenance task. The people who build databases are likely much better at this stuff that you or me. Use what they give you. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From dave_bradshaw at talk21.com Thu Mar 14 11:30:51 2013 From: dave_bradshaw at talk21.com (David Bradshaw) Date: Thu, 14 Mar 2013 10:30:51 +0000 (GMT) Subject: [Tutor] Text Processing - Questions/Help. Message-ID: <1363257051.53559.YahooMailNeo@web87405.mail.ir2.yahoo.com> I have written some code that logs into a list of hosts and runs a couple of commands to find out some information. Which I then save to a file and process. A cut down version of the information I generate and save can be found here - http://pastebin.com/4ePz3Z7m The code I have written to process this file can be found here - http://pastebin.com/WBbKydLg I need to run the two commands when generating the information as in some cases we have a high speed expansion card installed and I need its MAC rather than the MAC of the on-board card. Why? As well as generating output to show the layout of each chassis, I also then want to use this information to generate a dhcpd.conf file. I have written the code to do it, but it suffers the same problem. Currently when I run my code I get this as the output - ???? BBC21-14.ZONE21.WORK ??? ?178.28.185.89 6??? ?vm14-6 ??? ?06BNBB6 ??? ?5C:F3:FC:C2:08:0C 7??? ?vm14-7 ??? ?06BNBM3 ??? ?5C:F3:FC:C2:0D:48 8??? ?s21-04 ??? ?06KKY20 ??? ?5C:F3:FC:79:53:50 ??? ?00:10:18:E4:EA:EC 9??? ?ps41.p33 ??? ?06CZHR8 ??? ?34:40:B5:DC:2C:50 ??? ?00:10:18:E4:F3:2C 10??? ?vm14-8 ??? ?06BNBN6 ??? ?5C:F3:FC:C1:F3:10 Any pointers as to how in the cases where 2 MACs are displayed I only display/output the second? Also there is no guarantee that in the future the second MAC will start with 00:10. From my code was it a fluke that I got the output formatted as it is and I actually need to rethink how I process the information? Finally the information on pastebin, is it better or preferred that I add it all in this thread, rather the putting it in pastebin? Thanks for any help provided. Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From s.charonis at gmail.com Thu Mar 14 11:56:28 2013 From: s.charonis at gmail.com (Spyros Charonis) Date: Thu, 14 Mar 2013 10:56:28 +0000 Subject: [Tutor] Text Processing Query Message-ID: Hello Pythoners, I am trying to extract certain fields from a file that whose text looks like this: COMPND 2 MOLECULE: POTASSIUM CHANNEL SUBFAMILY K MEMBER 4; COMPND 3 CHAIN: A, B; COMPND 10 MOL_ID: 2; COMPND 11 MOLECULE: ANTIBODY FAB FRAGMENT LIGHT CHAIN; COMPND 12 CHAIN: D, F; COMPND 13 ENGINEERED: YES; COMPND 14 MOL_ID: 3; COMPND 15 MOLECULE: ANTIBODY FAB FRAGMENT HEAVY CHAIN; COMPND 16 CHAIN: E, G; I would like the chain IDs, but only those following the text heading "ANTIBODY FAB FRAGMENT", i.e. I need to create a list with D,F,E,G which excludes A,B which have a non-antibody text heading. I am using the following syntax: with open(filename) as file: scanfile=file.readlines() for line in scanfile: if line[0:6]=='COMPND' and 'FAB FRAGMENT' in line: continue elif line[0:6]=='COMPND' and 'CHAIN' in line: print line But this yields: COMPND 3 CHAIN: A, B; COMPND 12 CHAIN: D, F; COMPND 16 CHAIN: E, G; I would like to ignore the first line since A,B correspond to non-antibody text headings, and instead want to extract only D,F & E,G whose text headings are specified as antibody fragments. Many thanks, Spyros -------------- next part -------------- An HTML attachment was scrubbed... URL: From taserian at gmail.com Thu Mar 14 12:28:47 2013 From: taserian at gmail.com (taserian) Date: Thu, 14 Mar 2013 07:28:47 -0400 Subject: [Tutor] Text Processing Query In-Reply-To: References: Message-ID: Since the identifier and the item that you want to keep are on different lines, you'll need to set a "flag". with open(filename) as file: scanfile=file.readlines() flag = 0 for line in scanfile: if line[0:6]=='COMPND' and 'FAB FRAGMENT' in line: flag = 1 elif line[0:6]=='COMPND' and 'CHAIN' in line and flag = 1: print line flag = 0 Notice that the flag is set to 1 only on "FAB FRAGMENT", and it's reset to 0 after the next "CHAIN" line that follows the "FAB FRAGMENT" line. AR On Thu, Mar 14, 2013 at 6:56 AM, Spyros Charonis wrote: > Hello Pythoners, > > I am trying to extract certain fields from a file that whose text looks > like this: > > COMPND 2 MOLECULE: POTASSIUM CHANNEL SUBFAMILY K MEMBER 4; > > COMPND 3 CHAIN: A, B; > > COMPND 10 MOL_ID: 2; > > COMPND 11 MOLECULE: ANTIBODY FAB FRAGMENT LIGHT CHAIN; > > COMPND 12 CHAIN: D, F; > > COMPND 13 ENGINEERED: YES; > > COMPND 14 MOL_ID: 3; > > COMPND 15 MOLECULE: ANTIBODY FAB FRAGMENT HEAVY CHAIN; > > COMPND 16 CHAIN: E, G; > > I would like the chain IDs, but only those following the text heading > "ANTIBODY FAB FRAGMENT", i.e. I need to create a list with D,F,E,G which > excludes A,B which have a non-antibody text heading. I am using the > following syntax: > > with open(filename) as file: > > scanfile=file.readlines() > > for line in scanfile: > > if line[0:6]=='COMPND' and 'FAB FRAGMENT' in line: continue > > elif line[0:6]=='COMPND' and 'CHAIN' in line: > > print line > > But this yields: > > COMPND 3 CHAIN: A, B; > > COMPND 12 CHAIN: D, F; > > COMPND 16 CHAIN: E, G; > > I would like to ignore the first line since A,B correspond to non-antibody > text headings, and instead want to extract only D,F & E,G whose text > headings are specified as antibody fragments. > > Many thanks, > Spyros > > > > > _______________________________________________ > 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 bodsda at googlemail.com Thu Mar 14 13:13:40 2013 From: bodsda at googlemail.com (Bod Soutar) Date: Thu, 14 Mar 2013 12:13:40 +0000 Subject: [Tutor] Text Processing Query In-Reply-To: References: Message-ID: On 14 March 2013 10:56, Spyros Charonis wrote: > Hello Pythoners, > > I am trying to extract certain fields from a file that whose text looks like > this: > > COMPND 2 MOLECULE: POTASSIUM CHANNEL SUBFAMILY K MEMBER 4; > COMPND 3 CHAIN: A, B; > COMPND 10 MOL_ID: 2; > COMPND 11 MOLECULE: ANTIBODY FAB FRAGMENT LIGHT CHAIN; > COMPND 12 CHAIN: D, F; > COMPND 13 ENGINEERED: YES; > COMPND 14 MOL_ID: 3; > COMPND 15 MOLECULE: ANTIBODY FAB FRAGMENT HEAVY CHAIN; > COMPND 16 CHAIN: E, G; > > I would like the chain IDs, but only those following the text heading > "ANTIBODY FAB FRAGMENT", i.e. I need to create a list with D,F,E,G which > excludes A,B which have a non-antibody text heading. I am using the > following syntax: > > with open(filename) as file: > > scanfile=file.readlines() > > for line in scanfile: > > if line[0:6]=='COMPND' and 'FAB FRAGMENT' in line: continue > > elif line[0:6]=='COMPND' and 'CHAIN' in line: > > print line > > > But this yields: > > COMPND 3 CHAIN: A, B; > COMPND 12 CHAIN: D, F; > COMPND 16 CHAIN: E, G; > > I would like to ignore the first line since A,B correspond to non-antibody > text headings, and instead want to extract only D,F & E,G whose text > headings are specified as antibody fragments. > > Many thanks, > Spyros > > > This is how I would do it. with open(filename) as file: scanfile = file.readlines() wanted = "CHAIN:" unwanted = [" A", " B"] for line in scanfile: for item in unwanted: if item not in line and wanted in line: print line HTH, Bodsda From alan.gauld at btinternet.com Thu Mar 14 13:14:11 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 14 Mar 2013 12:14:11 +0000 Subject: [Tutor] Text Processing - Questions/Help. In-Reply-To: <1363257051.53559.YahooMailNeo@web87405.mail.ir2.yahoo.com> References: <1363257051.53559.YahooMailNeo@web87405.mail.ir2.yahoo.com> Message-ID: On 14/03/13 10:30, David Bradshaw wrote: > I have written some code that logs into a list of hosts and runs a > couple of commands to find out some information. Which I then save to a > file and process. > > A cut down version of the information I generate and save can be found > here - http://pastebin.com/4ePz3Z7m > > The code I have written to process this file can be found here - > http://pastebin.com/WBbKydLg Its fine to use pastebin for long programs. But... > information to generate a dhcpd.conf file. I have written the code to do > it, but it suffers the same problem. It's not totally clear what the problem is? > Currently when I run my code I get this as the output - > > BBC21-14.ZONE21.WORK > 178.28.185.89 > 6 vm14-6 > 06BNBB6 > 5C:F3:FC:C2:08:0C > 7 vm14-7 > 06BNBM3 > 5C:F3:FC:C2:0D:48 > 8 s21-04 > 06KKY20 > 5C:F3:FC:79:53:50 > 00:10:18:E4:EA:EC > 9 ps41.p33 > 06CZHR8 > 34:40:B5:DC:2C:50 > 00:10:18:E4:F3:2C > 10 vm14-8 > 06BNBN6 > 5C:F3:FC:C1:F3:10 > > Any pointers as to how in the cases where 2 MACs are displayed I only > display/output the second? Also there is no guarantee that in the future > the second MAC will start with 00:10. See the other thread about text processing. You need top use a flag, or sentinel. In your case the flag tells you when you stop getting MAC addresses, so in pseudo code inMacs = False for line in inputfile: if not inMacs and isMac(line): # your function to identify a MAC inMacs = True if inMacs: if isMac(line): lastMac = line else: print lastMac inMacs = False > From my code was it a fluke that I got the output formatted as it is > and I actually need to rethink how I process the information? Probably not, it'll be because that's how you processed it. But without reading your code I can't tell what that was. Whether the formatting is due to an explicit decision on your part or a result of some default Python behaviour I don't know, but it almost certainly won't be a fluke. (The exception is if its down to the order/structure of your input data) > Finally the information on pastebin, is it better or preferred that I > add it all in this thread, rather the putting it in pastebin? Its best if you can either post the relevant snippet from your code (with optional link to the full listing) or recreate the situation using a small example program. Having nothing in the mail puts too much onus on the reader to do all the work. If they are busy, lazy, or both, they won't bother. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From knupp at well.com Thu Mar 14 16:26:08 2013 From: knupp at well.com (David Knupp) Date: Thu, 14 Mar 2013 08:26:08 -0700 (PDT) Subject: [Tutor] increment a counter inside generator In-Reply-To: <51412EE8.1050806@pearwood.info> References: <51412EE8.1050806@pearwood.info> Message-ID: On Thu, 14 Mar 2013, Steven D'Aprano wrote: > If you have some unknown, arbitrary iterable that doesn't support len(), > then you can use the sum() trick: > > it = some_unknown_iterable() > sum(1 for x in it) Yes, of course you are correct. This was my intention, but I chose an especially poorly contrived example. Thank you for the clarification. --dk From msirenef at lightbird.net Thu Mar 14 16:33:20 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Thu, 14 Mar 2013 11:33:20 -0400 Subject: [Tutor] Text Processing Query In-Reply-To: References: Message-ID: <5141EDC0.7090702@lightbird.net> On 03/14/2013 07:28 AM, taserian wrote: > Since the identifier and the item that you want to keep are on different lines, you'll need to set a "flag". > > with open(filename) as file: > > scanfile=file.readlines() > > flag = 0 > > for line in scanfile: > > if line[0:6]=='COMPND' and 'FAB FRAGMENT' in line: flag = 1 > > elif line[0:6]=='COMPND' and 'CHAIN' in line and flag = 1: > > print line > > flag = 0 > > > Notice that the flag is set to 1 only on "FAB FRAGMENT", and it's reset to 0 after the next "CHAIN" line that follows the "FAB FRAGMENT" line. I would simplify this a bit as follows: flag = 0 for line in scanfile: if line.strip(): if 'FAB FRAGMENT' in line: flag = 1 elif flag: print line flag = 0 This assumes CHAIN line always follows MOLECULE line (otherwise elif needs to check for CHAIN as well), it also ignores blank lines. -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ It is pleasant at times to play the madman. Seneca From breamoreboy at yahoo.co.uk Thu Mar 14 17:33:20 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 14 Mar 2013 16:33:20 +0000 Subject: [Tutor] Text Processing Query In-Reply-To: References: Message-ID: On 14/03/2013 11:28, taserian wrote: Top posting fixed > > On Thu, Mar 14, 2013 at 6:56 AM, Spyros Charonis > wrote: > > Hello Pythoners, > > I am trying to extract certain fields from a file that whose text > looks like this: > > COMPND 2 MOLECULE: POTASSIUM CHANNEL SUBFAMILY K MEMBER 4; > COMPND 3 CHAIN: A, B; > COMPND 10 MOL_ID: 2; > COMPND 11 MOLECULE: ANTIBODY FAB FRAGMENT LIGHT CHAIN; > COMPND 12 CHAIN: D, F; > COMPND 13 ENGINEERED: YES; > COMPND 14 MOL_ID: 3; > COMPND 15 MOLECULE: ANTIBODY FAB FRAGMENT HEAVY CHAIN; > COMPND 16 CHAIN: E, G; > > I would like the chain IDs, but only those following the text > heading "ANTIBODY FAB FRAGMENT", i.e. I need to create a list with > D,F,E,G which excludes A,B which have a non-antibody text heading. > I am using the following syntax: > > with open(filename) as file: > > scanfile=file.readlines() > > for line in scanfile: > > if line[0:6]=='COMPND' and 'FAB FRAGMENT' in line: continue > > elif line[0:6]=='COMPND' and 'CHAIN' in line: > > print line > > > But this yields: > > COMPND 3 CHAIN: A, B; > COMPND 12 CHAIN: D, F; > COMPND 16 CHAIN: E, G; > > I would like to ignore the first line since A,B correspond to > non-antibody text headings, and instead want to extract only D,F & > E,G whose text headings are specified as antibody fragments. > > Many thanks, > Spyros > > Since the identifier and the item that you want to keep are on different > lines, you'll need to set a "flag". > > with open(filename) as file: > > scanfile=file.readlines() > > flag = 0 > > for line in scanfile: > > if line[0:6]=='COMPND' and 'FAB FRAGMENT' in line: flag = 1 > > elif line[0:6]=='COMPND' and 'CHAIN' in line and flag = 1: > > print line > > flag = 0 > > > Notice that the flag is set to 1 only on "FAB FRAGMENT", and it's reset > to 0 after the next "CHAIN" line that follows the "FAB FRAGMENT" line. > > > AR > > Notice that this code won't run due to a syntax error. -- Cheers. Mark Lawrence From s.charonis at gmail.com Thu Mar 14 17:40:20 2013 From: s.charonis at gmail.com (Spyros Charonis) Date: Thu, 14 Mar 2013 16:40:20 +0000 Subject: [Tutor] Text Processing Query In-Reply-To: References: Message-ID: Yes, the elif line need to have **flag_FAB ==1** as is conidition instead of **flag_FAB=1**. So: for line in scanfile: if line[0:6]=='COMPND' and 'FAB' in line: flag_FAB = 1 elif line[0:6]=='COMPND' and 'CHAIN' in line and flag_FAB == 1: print line flag_FAB = 0 On Thu, Mar 14, 2013 at 4:33 PM, Mark Lawrence wrote: > On 14/03/2013 11:28, taserian wrote: > > Top posting fixed > > >> On Thu, Mar 14, 2013 at 6:56 AM, Spyros Charonis > > wrote: >> >> Hello Pythoners, >> >> I am trying to extract certain fields from a file that whose text >> looks like this: >> >> COMPND 2 MOLECULE: POTASSIUM CHANNEL SUBFAMILY K MEMBER 4; >> COMPND 3 CHAIN: A, B; >> COMPND 10 MOL_ID: 2; >> COMPND 11 MOLECULE: ANTIBODY FAB FRAGMENT LIGHT CHAIN; >> COMPND 12 CHAIN: D, F; >> COMPND 13 ENGINEERED: YES; >> COMPND 14 MOL_ID: 3; >> COMPND 15 MOLECULE: ANTIBODY FAB FRAGMENT HEAVY CHAIN; >> COMPND 16 CHAIN: E, G; >> >> I would like the chain IDs, but only those following the text >> heading "ANTIBODY FAB FRAGMENT", i.e. I need to create a list with >> D,F,E,G which excludes A,B which have a non-antibody text heading. >> I am using the following syntax: >> >> with open(filename) as file: >> >> scanfile=file.readlines() >> >> for line in scanfile: >> >> if line[0:6]=='COMPND' and 'FAB FRAGMENT' in line: continue >> >> elif line[0:6]=='COMPND' and 'CHAIN' in line: >> >> print line >> >> >> But this yields: >> >> COMPND 3 CHAIN: A, B; >> COMPND 12 CHAIN: D, F; >> COMPND 16 CHAIN: E, G; >> >> I would like to ignore the first line since A,B correspond to >> non-antibody text headings, and instead want to extract only D,F & >> E,G whose text headings are specified as antibody fragments. >> >> Many thanks, >> Spyros >> >> Since the identifier and the item that you want to keep are on different >> lines, you'll need to set a "flag". >> >> with open(filename) as file: >> >> scanfile=file.readlines() >> >> flag = 0 >> >> for line in scanfile: >> >> if line[0:6]=='COMPND' and 'FAB FRAGMENT' in line: flag = 1 >> >> elif line[0:6]=='COMPND' and 'CHAIN' in line and flag = 1: >> >> print line >> >> flag = 0 >> >> >> Notice that the flag is set to 1 only on "FAB FRAGMENT", and it's reset >> to 0 after the next "CHAIN" line that follows the "FAB FRAGMENT" line. >> >> >> AR >> >> >> > Notice that this code won't run due to a syntax error. > > -- > Cheers. > > Mark Lawrence > > > ______________________________**_________________ > 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 ramit.prasad at jpmorgan.com Thu Mar 14 18:41:53 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 14 Mar 2013 17:41:53 +0000 Subject: [Tutor] Text Processing Query In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF47418243D0E@SCACMX008.exchad.jpmchase.net> Spyros Charonis wrote: > Hello Pythoners, > > I am trying to extract certain fields from a file that whose text looks like this: > > COMPND ? 2 MOLECULE: POTASSIUM CHANNEL SUBFAMILY K MEMBER 4; > COMPND ? 3 CHAIN: A, B; > > COMPND ?10 MOL_ID: 2; > COMPND ?11 MOLECULE: ANTIBODY FAB FRAGMENT LIGHT CHAIN; > COMPND ?12 CHAIN: D, F; > COMPND ?13 ENGINEERED: YES; > COMPND ?14 MOL_ID: 3; > COMPND ?15 MOLECULE: ANTIBODY FAB FRAGMENT HEAVY CHAIN; > COMPND ?16 CHAIN: E, G; > > I would like the chain IDs, but only those following the text heading "ANTIBODY FAB FRAGMENT", i.e. I > need to create a list with D,F,E,G ?which excludes A,B which have a non-antibody text heading. I am > using the following syntax: > > with open(filename) as file: > ? ? scanfile=file.readlines() > ? ? for line in scanfile: > ? ? ? ? if line[0:6]=='COMPND' and 'FAB FRAGMENT' in line: continue > ? ? ? ? elif line[0:6]=='COMPND' and 'CHAIN' in line: > ? ? ? ? ? ? print line There is no reason to use readlines in this example, just iterate over the file object directly. with open(filename) as file: for line in file: if line[0:6]=='COMPND' and 'FAB FRAGMENT' in line: continue elif line[0:6]=='COMPND' and 'CHAIN' in line: print line > > But this yields: > > COMPND ? 3 CHAIN: A, B; > COMPND ?12 CHAIN: D, F; > COMPND ?16 CHAIN: E, G; > > I would like to ignore the first line since A,B correspond to non-antibody text headings, and instead > want to extract only D,F & E,G whose text headings are specified as antibody fragments. > > Many thanks, > Spyros > Will 'FAB FRAGMENT' always be the line before 'CHAIN'? If so, then just keep track of the previous line. >>> raw 'COMPND 2 MOLECULE: POTASSIUM CHANNEL SUBFAMILY K MEMBER 4;\nCOMPND 3 CHAIN: A, B;\nCOMPND 10 MOL_ID: 2;\nCOMPND 11 MOLECULE: \ ANTIBODY FAB FRAGMENT LIGHT CHAIN;\nCOMPND 12 CHAIN: D, F;\nCOMPND 13 ENGINEERED: YES;\nCOMPND 14 MOL_ID: 3;\nCOMPND 15 MOLECULE\ : ANTIBODY FAB FRAGMENT HEAVY CHAIN;\nCOMPND 16 CHAIN: E, G;' >>> prev = '' >>> chains = [] >>> for line in raw.split('\n'): ... if 'COMPND' in prev and 'FAB FRAGMENT' in prev and 'CHAIN' in line: ... chains.extend( line.split(':')[1].replace(',','').replace(';','').split()) ... prev = line ... >>> chains ['D', 'F', 'E', 'G'] This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From irina_khanoom at yahoo.com Thu Mar 14 19:22:31 2013 From: irina_khanoom at yahoo.com (Irina I) Date: Thu, 14 Mar 2013 11:22:31 -0700 (PDT) Subject: [Tutor] Passing a config file to Python Message-ID: <1363285351.23279.YahooMailClassic@web124902.mail.ne1.yahoo.com> Hi all, I'm new to Python and am trying to pass a config file to my Python script. The config file is so simple and has only two URLs. The code should takes that configuration file as input and generates a single file in HTML format as output. The program must retrieve each web page in the list and extract all the tag links from each page. It is only necessary to extract the tag links from the landing page of the URLs that you have placed in your configuration file. The program will output an HTML file containing a list of clickable links from the source webpages and will be grouped by webpage. This is what I came up with so far, can someone please tell me if it's good? Thanks in advance. [CODE] - - - - - - - - config.txt - - - - - - - - http://www.blahblah.bla http://www.etcetc.etc - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - linkscraper.py - - - - - - - - import urllib def get_seed_links(): ...."""return dict with seed links, from the config file, as keys -- {seed_link: None, ... }""" ....with open("config.txt", "r") as f: ........seed_links = f.read().split('\n') ....return dict([(s_link, None) for s_link in seed_links]) def get_all_links(seed_link): ...."""return list of links from seed_link page""" ....all_links = [] ....source_page = urllib.urlopen(seed_link).read() ....start = 0 ....while True: ........start = source_page.find(" References: <1363285351.23279.YahooMailClassic@web124902.mail.ne1.yahoo.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF47418243F90@SCACMX008.exchad.jpmchase.net> Irina I > Hi all, > > I'm new to Python and am trying to pass a config file to my Python script. The config file is so > simple and has only two URLs. > > The code should takes that configuration file as input and generates a single file in HTML format as > output. > > The program must retrieve each web page in the list and extract all the tag links from each page. > It is only necessary to extract the tag links from the landing page of the URLs that you have > placed in your configuration file. > > The program will output an HTML file containing a list of clickable links from the source webpages and > will be grouped by webpage. This is what I came up with so far, can someone please tell me if it's > good? > > Thanks in advance. > I would advise you to use a library like Beautiful Soup to parse the HTML. You will find lots of badly formed pages and trying to manually search for tags is error prone and frustrating. It is nice to see that you are not using regular expressions, so your solution will be much easier to debug. > [CODE] > > - - - - - - - - config.txt - - - - - - - - > http://www.blahblah.bla > http://www.etcetc.etc > - - - - - - - - - - - - - - - - - - - - - - > > - - - - - - - - linkscraper.py - - - - - - - - > import urllib > > def get_seed_links(): > ...."""return dict with seed links, from the config file, as keys -- {seed_link: None, ... }""" > ....with open("config.txt", "r") as f: > ........seed_links = f.read().split('\n') seed_links = f.readlines() # This is more descriptive with the same effect. > ....return dict([(s_link, None) for s_link in seed_links]) > > def get_all_links(seed_link): > ...."""return list of links from seed_link page""" > ....all_links = [] > ....source_page = urllib.urlopen(seed_link).read() > ....start = 0 > ....while True: > ........start = source_page.find(" ........if start == -1: > ............return all_links > ........start = source_page.find("href=", start) > ........start = source_page.find("=", start) + 1 Why keep using find? (Ignoring that I think you should use a true HTML parser) start = source_page.find("href=", start) + 7 # + len("href=") + delimiter > ........end = source_page.find(" ", start) What about links with a space in them? I have seen it before. What if the link does not have a space between URL and closing tag? > ........link = source_page[start:end] Does this remove the ending quote? > ........all_links.append(link) > > def build_output_file(data): > ...."""build and save output file from data. data -- {seed_link:[link, ...], ...}""" > ....result = "" > ....for seed_link in data: > ........result += "

%s

\n" % seed_link > ........for link in data[seed_link]: I think this would be better written using .iteritems() (Python 2) or .items() (Python3) for seed_link, links in data.iteritems(): result += "

%s

\n" % seed_link for link in links: > ............result += '
%s\n' % (link, link.replace("http://", "")) > ........result += "" > ....with open("result.htm", "w") as f: > ........f.write(result) In general string concatenation in this manner is a bad idea because it is a quadratic process. (It takes a lot more time and memory.) The python idiom is to use ''.join(). Make result a list and then do a `result.append()` instead of `result += `. When you finally need the string, do a `f.write(''.join(result))`. I have given three examples below to illustrate how the ''.join() idiom works. >>> '!#$#'.join( [ 'a', 'B', '4' ] ) 'a!#$#B!#$#4' >>> ''.join( [ 'a', 'B', '4' ] ) 'aB4' >>> '_'.join( [ 'a', 'B', '4' ] ) 'a_B_4' > > def main(): > ....seed_link_data = get_seed_links() > ....for seed_link in seed_link_data: > ........seed_link_data[seed_link] = get_all_links(seed_link) > ....build_output_file(seed_link_data) > > if __name__ == "__main__": > ....main() > > [/CODE] ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From cpe.list at gmail.com Thu Mar 14 22:25:34 2013 From: cpe.list at gmail.com (Christopher Emery) Date: Thu, 14 Mar 2013 17:25:34 -0400 Subject: [Tutor] Designing a program (File-Fetcher) Message-ID: Hello All, Okay, I know the best way to learn how to do something is to jump in so I have decided I would like to make a program (command line) to get files from a website that will be then used later on by another program. Program idea - quick steps to do *** file-fetcher (within zip file) get internet location of files (ex: http://www.get_file.get/file_??.zip get name of files check date of file download file unzip file delete zip file after saving the txt file *** Here are the things I need it to do: * if its ran just with its name file-fetcher.py then it should ask for location of file(s) * it should also ask for a list of files to download seperated by a corma "," or by a file with a line by line list of files to download * it should be able to download files that are zip or other format such as txt, * if its ran with file-fetcher.py -L=url -F=file.zip, file.txt * if its a zip file it need to extract the file(s) from it * it then need to put the downloaded, extracted files into a directory * it then needs to delete the zip file * it needs to check for the date before downloading the whole file, maybe download the first few bytes to check time stamp Okay with the above said, how should I start to do psceduo code? Would each of the above be a function within the program? Any advise on class that exist that can make this process easier? How would someone run a command that is normally done at the command line like espeak within python program? Also how would I hide the visual output of a command like espeak, it throws alot of erros but it works, it happens to others using it too. By the way I am using python 3.2 as this is what is on R-Pi Raspbain (latest version) Thank you greatly for your assistance in guidance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From chigga101 at gmail.com Thu Mar 14 23:38:41 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 14 Mar 2013 22:38:41 +0000 Subject: [Tutor] break Message-ID: i cant seem to break out of this loop. let me explain the variables you see: Enemy.ships = [] #an Enemy class variable that contains enemy ships self.missiles = [] an instance variable that appends how many Visible missiles my ship has fired Enemy.rects = [] an Enemy class variable that represents a rectangle for every ship in Enemy.ships Explosion() = a class where explosions occur QPoint() = is a pyqt function that takes a point x, y position as arguments im trying to destroy the ships if they hit a missile, even though i use pyqt this is mainly python code if Enemy.ships: for missile in self.missiles: for rect in Enemy.rects: if QPoint(missile.x + 5, missile.y) in rect: explosion = Explosion(rect.x(), rect.y()) self.explosions.append(explosion) break once the missile has hit 1 Enemy.rect i want to break and go to the next missile so the missile is destroyed and doesnt hit another Enemy, but for some reason the break i have isnt working and the same missile sometimes is hitting 2 different rects on the same iteration. i have done the same loop using a simple print statements on strings greater than a certain length and it breaks correctly. anyone have any ideas why the break isnt breaking out of the nested/inner loop but instead continuing to loop through the Enemies? From davea at davea.name Thu Mar 14 23:51:06 2013 From: davea at davea.name (Dave Angel) Date: Thu, 14 Mar 2013 18:51:06 -0400 Subject: [Tutor] Passing a config file to Python In-Reply-To: <1363285351.23279.YahooMailClassic@web124902.mail.ne1.yahoo.com> References: <1363285351.23279.YahooMailClassic@web124902.mail.ne1.yahoo.com> Message-ID: <5142545A.4080303@davea.name> On 03/14/2013 02:22 PM, Irina I wrote: > Hi all, > > I'm new to Python and am trying to pass a config file to my Python script. The config file is so simple and has only two URLs. > > The code should takes that configuration file as input and generates a single file in HTML format as output. > > The program must retrieve each web page in the list and extract all the tag links from each page. It is only necessary to extract the tag links from the landing page of the URLs that you have placed in your configuration file. > > The program will output an HTML file containing a list of clickable links from the source webpages and will be grouped by webpage. This is what I came up with so far, can someone please tell me if it's good? > > Thanks in advance. > > [CODE] > > - - - - - - - - config.txt - - - - - - - - > http://www.blahblah.bla > http://www.etcetc.etc > - - - - - - - - - - - - - - - - - - - - - - > > - - - - - - - - linkscraper.py - - - - - - - - > import urllib > > def get_seed_links(): > ...."""return dict with seed links, from the config file, as keys -- {seed_link: None, ... }""" > ....with open("config.txt", "r") as f: > ........seed_links = f.read().split('\n') readline() is much clearer and accomplishes what you want. Of course then you'd have to move the newline from each line. But generally when you're reading in manually entered data, you want to do a strip() on each line anyway. > ....return dict([(s_link, None) for s_link in seed_links]) > > def get_all_links(seed_link): > ...."""return list of links from seed_link page""" > ....all_links = [] > ....source_page = urllib.urlopen(seed_link).read() > ....start = 0 > ....while True: > ........start = source_page.find(" ........if start == -1: > ............return all_links > ........start = source_page.find("href=", start) > ........start = source_page.find("=", start) + 1 > ........end = source_page.find(" ", start) > ........link = source_page[start:end] > ........all_links.append(link) > > def build_output_file(data): > ...."""build and save output file from data. data -- {seed_link:[link, ...], ...}""" > ....result = "" > ....for seed_link in data: > ........result += "

%s

\n" % seed_link Perhaps by 'break' you really meant 'b' ?? > ........for link in data[seed_link]: > ............result += '
%s\n' % (link, link.replace("http://", "")) > ........result += "" You have no DOCTYPE header in your output file. The html tag pair need to surround the bulk of the file, not consist of a one-space content. You have no header and body section. > ....with open("result.htm", "w") as f: > ........f.write(result) > > def main(): > ....seed_link_data = get_seed_links() > ....for seed_link in seed_link_data: > ........seed_link_data[seed_link] = get_all_links(seed_link) > ....build_output_file(seed_link_data) > > if __name__ == "__main__": > ....main() > > [/CODE] > You never specify which version of Python this is written for, nor what constraints there are on either the input html or output html. Some comments are omitted, since they're version dependent. Generally, your code is fragile as to what actual web pages would actually work. Few websites actually try very hard to have valid html, and even much valid html could break your current assumptions. Consider Beautiful Soup instead of urllib or urllib2. Your source code would have to be carefully edited to change all those leading periods into spaces before it could even compile in Python. That stops any of us from actually trying it, or pieces of it. So we can only comment by inspection. -- DaveA From msirenef at lightbird.net Thu Mar 14 23:56:31 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Thu, 14 Mar 2013 18:56:31 -0400 Subject: [Tutor] break In-Reply-To: References: Message-ID: <5142559F.7030604@lightbird.net> On 03/14/2013 06:38 PM, Matthew Ngaha wrote: > i cant seem to break out of this loop. let me explain the variables you see: > > Enemy.ships = [] #an Enemy class variable that contains enemy ships > self.missiles = [] an instance variable that appends how many Visible > missiles my ship has fired > Enemy.rects = [] an Enemy class variable that represents a rectangle > for every ship in Enemy.ships > Explosion() = a class where explosions occur > QPoint() = is a pyqt function that takes a point x, y position as arguments > > im trying to destroy the ships if they hit a missile, even though i > use pyqt this is mainly python code > > if Enemy.ships: > for missile in self.missiles: > for rect in Enemy.rects: > if QPoint(missile.x + 5, missile.y) in rect: > explosion = Explosion(rect.x(), rect.y()) > self.explosions.append(explosion) > break > > once the missile has hit 1 Enemy.rect i want to break and go to the > next missile so the missile is destroyed and doesnt hit another Enemy, > but for some reason the break i have isnt working and the same missile > sometimes is hitting 2 different rects on the same iteration. i have > done the same loop using a simple print statements on strings greater > than a certain length and it breaks correctly. anyone have any ideas > why the break isnt breaking out of the nested/inner loop but instead > continuing to loop through the Enemies? > Yes, break statement exits only the current loop, not all loops. One good approach is to have a separate function or method with both loops: def attack(self, Enemy): for missile in self.missiles: for rect in Enemy.rects: if QPoint(missile.x + 5, missile.y) in rect: explosion = Explosion(rect.x(), rect.y()) self.explosions.append(explosion) return You could also set a flag and check it at the end of outer loop and have a second break statement when the flag is set. HTH, -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Fanaticism consists of redoubling your effort when you have forgotten your aim. George Santayana From davea at davea.name Fri Mar 15 00:08:00 2013 From: davea at davea.name (Dave Angel) Date: Thu, 14 Mar 2013 19:08:00 -0400 Subject: [Tutor] break In-Reply-To: References: Message-ID: <51425850.4070900@davea.name> On 03/14/2013 06:38 PM, Matthew Ngaha wrote: > i cant seem to break out of this loop. let me explain the variables you see: > > > > > if Enemy.ships: > for missile in self.missiles: flag = False > for rect in Enemy.rects: assert(!flag) > if QPoint(missile.x + 5, missile.y) in rect: > explosion = Explosion(rect.x(), rect.y()) > self.explosions.append(explosion) flag = True > break > (untested) With that added code, if the break ever fails, it will raise an exception that you can then figure out. At that point, you can figure out why your Python executable got corrupted. more likely, you'll find that some other loop is similar enough that you got this one confused with that one. -- DaveA From chigga101 at gmail.com Fri Mar 15 00:23:07 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Thu, 14 Mar 2013 23:23:07 +0000 Subject: [Tutor] break In-Reply-To: <51425850.4070900@davea.name> References: <51425850.4070900@davea.name> Message-ID: >> if Enemy.ships: >> for missile in self.missiles: > > flag = False >> >> for rect in Enemy.rects: > > assert(!flag) > >> if QPoint(missile.x + 5, missile.y) in rect: >> explosion = Explosion(rect.x(), rect.y()) >> self.explosions.append(explosion) > > flag = True >> >> break im about to try the suggestions. i on python 3 and this line is giving me a syntax error assert(!flag). From chigga101 at gmail.com Fri Mar 15 01:08:11 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Fri, 15 Mar 2013 00:08:11 +0000 Subject: [Tutor] break In-Reply-To: <5142559F.7030604@lightbird.net> References: <5142559F.7030604@lightbird.net> Message-ID: > One good approach is to have a separate function or method with > both loops: > > def attack(self, Enemy): > > for missile in self.missiles: > for rect in Enemy.rects: > if QPoint(missile.x + 5, missile.y) in rect: > explosion = Explosion(rect.x(), rect.y()) > self.explosions.append(explosion) > return i altered this because once it returns the outer loop also stops and i need it incase i have more than 1 missile to loop through. i made it so i did the outer loop in the program and sent the inner loop to this function, but for some reason the code seems to break my program.. no errors are returned but it just freezes on inputs and missile collision. > You could also set a flag and check it at the end of outer loop > and have a second break statement when the flag is set. > im trying to figure out this technique with flags but i havent got it yet.. what does a flag stand for? From msirenef at lightbird.net Fri Mar 15 01:24:29 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Thu, 14 Mar 2013 20:24:29 -0400 Subject: [Tutor] break In-Reply-To: References: <5142559F.7030604@lightbird.net> Message-ID: <51426A3D.5070404@lightbird.net> On 03/14/2013 08:08 PM, Matthew Ngaha wrote: >> One good approach is to have a separate function or method with >> both loops: >> >> def attack(self, Enemy): >> >> for missile in self.missiles: >> for rect in Enemy.rects: >> if QPoint(missile.x + 5, missile.y) in rect: >> explosion = Explosion(rect.x(), rect.y()) >> self.explosions.append(explosion) >> return > > i altered this because once it returns the outer loop also stops and i > need it incase i have more than 1 missile to loop through. i made it > so i did the outer loop in the program and sent the inner loop to this > function, but for some reason the code seems to break my program.. no > errors are returned but it just freezes on inputs and missile > collision. Sorry, reading failure on my part. The code you had originally should break properly. You can add assert(not flag) as Dave suggested to figure out what actually happens. Maybe you have more than one instance of the same missile? -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Children begin by loving their parents; after a time they judge them; rarely, if ever, do they forgive them. Oscar Wilde From chigga101 at gmail.com Fri Mar 15 01:45:17 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Fri, 15 Mar 2013 00:45:17 +0000 Subject: [Tutor] break In-Reply-To: <51426A3D.5070404@lightbird.net> References: <5142559F.7030604@lightbird.net> <51426A3D.5070404@lightbird.net> Message-ID: thanks guys ive finally got it working. even though i didnt use the flag due to invalid syntax i realized since i was getting no errors i wasnt actually doing anything wrong. My mistake was i removed the ememy ship but for some reason forgot to remove the missile so it was still active on the next update/mainloop. im still interested in finding out how to write this in python 3 assert(!flag). From msirenef at lightbird.net Fri Mar 15 01:47:45 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Thu, 14 Mar 2013 20:47:45 -0400 Subject: [Tutor] break In-Reply-To: References: <5142559F.7030604@lightbird.net> <51426A3D.5070404@lightbird.net> Message-ID: <51426FB1.9090701@lightbird.net> On 03/14/2013 08:45 PM, Matthew Ngaha wrote: > thanks guys ive finally got it working. even though i didnt use the > flag due to invalid syntax i realized since i was getting no errors i > wasnt actually doing anything wrong. My mistake was i removed the > ememy ship but for some reason forgot to remove the missile so it was > still active on the next update/mainloop. im still interested in > finding out how to write this in python 3 assert(!flag). > assert(not flag) -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ From alan.gauld at btinternet.com Fri Mar 15 02:02:21 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 15 Mar 2013 01:02:21 +0000 Subject: [Tutor] Designing a program (File-Fetcher) In-Reply-To: References: Message-ID: On 14/03/13 21:25, Christopher Emery wrote: > Okay, I know the best way to learn how to do something is to jump in so > I have decided I would like to make a program (command line) to get > files from a website that will be then used later on by another program. OK, thats a good place to start. Next step, having thought about what you want, is to step back and pick a single scenario and build that. Once it workls add the next thing you want, repeat till complete. > Program idea - quick steps to do > *** > file-fetcher (within zip file) > > get internet location of files (ex: http://www.get_file.get/file_??.zip > get name of files These can be interactively from a user or from a config file or from command line arguments. > check date of file > download file This could use the ftp module if the far end has an ftp server running. > unzip file Using the zipfile module? > delete zip file after saving the txt file Yep, that looks like a fair start. > *** > > Here are the things I need it to do: > * if its ran just with its name file-fetcher.py then it should ask for > location of file(s) using input() and a test of sys.argv > * it should also ask for a list of files to download seperated by a > corma "," or by a file with a line by line list of files to download you need to work out how you identify which it is. For starters stick with a single file input by the user... > * it should be able to download files that are zip or other format such > as txt, ok, but pick one to start. > * if its ran with file-fetcher.py -L=url -F=file.zip, file.txt worry about options later and look at the various modules for parsing command line options - there are a few variants. > * if its a zip file it need to extract the file(s) from it > * it then need to put the downloaded, extracted files into a directory > * it then needs to delete the zip file zipfile, the os and shutil modules should all help here. > * it needs to check for the date before downloading the whole file, > maybe download the first few bytes to check time stamp if its ftp then the standard ftp commands should do all you need. > Okay with the above said, how should I start to do psceduo code? you almost have above. > Would each of the above be a function within the program? probably. > Any advise on class that exist that can make this process easier? see above for useful modules. read the documentation for each. experiment at the >>> prompt. > How would someone run a command that is normally done at the command > line like espeak within python program? look at the subprocess module documentation. > Also how would I hide the > visual output of a command like espeak, it throws alot of erros but it > works, it happens to others using it too. see last comment. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at davea.name Fri Mar 15 02:21:09 2013 From: davea at davea.name (Dave Angel) Date: Thu, 14 Mar 2013 21:21:09 -0400 Subject: [Tutor] break In-Reply-To: References: <51425850.4070900@davea.name> Message-ID: <51427785.9070804@davea.name> On 03/14/2013 07:23 PM, Matthew Ngaha wrote: >>> if Enemy.ships: >>> for missile in self.missiles: >> >> flag = False >>> >>> for rect in Enemy.rects: >> >> assert(!flag) >> >>> if QPoint(missile.x + 5, missile.y) in rect: >>> explosion = Explosion(rect.x(), rect.y()) >>> self.explosions.append(explosion) >> >> flag = True >>> >>> break > > im about to try the suggestions. i on python 3 and this line is giving > me a syntax error assert(!flag). > > My mistake. The exclamation point is from C. In Python, it should be "not" assert(not flag) This statement simply asserts (claims) that flag is NOT TRUE, and if for some reason it is true, it throws an exception. -- DaveA From cpe.list at gmail.com Fri Mar 15 03:07:43 2013 From: cpe.list at gmail.com (Christopher Emery) Date: Thu, 14 Mar 2013 22:07:43 -0400 Subject: [Tutor] Designing a program (File-Fetcher) In-Reply-To: References: Message-ID: Hello Alan, Thank you for your feedback. I will break it down in the order that I had stated in my quick steps, work on each pice getting one part work at a time build like lays (smile) Thank You, will post as I do to get advise on improvements or corrections. Sincerely in Christ, Christopher On Thu, Mar 14, 2013 at 9:02 PM, Alan Gauld wrote: > On 14/03/13 21:25, Christopher Emery wrote: > >> Okay, I know the best way to learn how to do something is to jump in so >> I have decided I would like to make a program (command line) to get >> files from a website that will be then used later on by another program. > > OK, thats a good place to start. > Next step, having thought about what you want, is to step back and pick a > single scenario and build that. Once it workls add the next thing you want, > repeat till complete. > >> Program idea - quick steps to do >> *** >> file-fetcher (within zip file) >> >> get internet location of files (ex: http://www.get_file.get/file_??.zip >> get name of files > > These can be interactively from a user or from a config file > or from command line arguments. > >> check date of file >> download file > > This could use the ftp module if the far end has an ftp server running. > >> unzip file > > Using the zipfile module? > >> delete zip file after saving the txt file > > Yep, that looks like a fair start. > >> *** >> >> Here are the things I need it to do: >> * if its ran just with its name file-fetcher.py then it should ask for >> location of file(s) > > using input() and a test of sys.argv > >> * it should also ask for a list of files to download seperated by a >> corma "," or by a file with a line by line list of files to download > > you need to work out how you identify which it is. For starters stick with a > single file input by the user... > >> * it should be able to download files that are zip or other format such >> as txt, > > ok, but pick one to start. > >> * if its ran with file-fetcher.py -L=url -F=file.zip, file.txt > > worry about options later and look at the various modules for parsing > command line options - there are a few variants. > >> * if its a zip file it need to extract the file(s) from it >> * it then need to put the downloaded, extracted files into a directory >> * it then needs to delete the zip file > > zipfile, the os and shutil modules should all help here. > >> * it needs to check for the date before downloading the whole file, >> maybe download the first few bytes to check time stamp > > if its ftp then the standard ftp commands should do all you need. > >> Okay with the above said, how should I start to do psceduo code? > > you almost have above. > >> Would each of the above be a function within the program? > > probably. > >> Any advise on class that exist that can make this process easier? > > see above for useful modules. > read the documentation for each. > experiment at the >>> prompt. > >> How would someone run a command that is normally done at the command >> line like espeak within python program? > > look at the subprocess module documentation. > >> Also how would I hide the >> visual output of a command like espeak, it throws alot of erros but it >> works, it happens to others using it too. > > see last comment. > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ From paradox at pobox.com Fri Mar 15 06:53:22 2013 From: paradox at pobox.com (Paradox) Date: Fri, 15 Mar 2013 13:53:22 +0800 Subject: [Tutor] Getting os.walk output into a list Message-ID: <5142B752.9010101@pobox.com> There is something I can't figure out about the following code (using python 2.7.3): def return_tree_files(rootpath, pattern): for root, dirs, files in os.walk(rootpath): i = [os.path.join(root, filename) for filename in fnmatch.filter(files, pattern)] return i I thought the function would return a list of lists of filenames in the rootpath and all subfolders. Instead I get only the filenames that match the pattern in the rootpath, it doesn't go into the subfolders. If I replace the last line with 'print i' instead of 'return i' I get output closer to what I expect but what I really want is a list of lists I can use elsewhere. I know I could collect these and append them but I am trying to understand list comprehensions and os.walk - but I have hit a wall. Why does the list comprehension only go down the rootpath once and stop, not walking to the subfolders? From davea at davea.name Fri Mar 15 07:31:55 2013 From: davea at davea.name (Dave Angel) Date: Fri, 15 Mar 2013 02:31:55 -0400 Subject: [Tutor] Getting os.walk output into a list In-Reply-To: <5142B752.9010101@pobox.com> References: <5142B752.9010101@pobox.com> Message-ID: <5142C05B.7040805@davea.name> On 03/15/2013 01:53 AM, Paradox wrote: > There is something I can't figure out about the following code (using > python 2.7.3): > > def return_tree_files(rootpath, pattern): > for root, dirs, files in os.walk(rootpath): > i = [os.path.join(root, filename) for filename in > fnmatch.filter(files, pattern)] > return i > > I thought the function would return a list of lists of filenames in the > rootpath and all subfolders. Instead I get only the filenames that > match the pattern in the rootpath, it doesn't go into the subfolders. That's because you returned out of the loop, the first time through. Each time through the loop, it describes one directory. Since your return after the first one, that's the only directory you'll see. > > If I replace the last line with 'print i' instead of 'return i' I get > output closer to what I expect but what I really want is a list of lists > I can use elsewhere. > > I know I could collect these and append them but I am trying to > understand list comprehensions and os.walk - but I have hit a wall. > > Why does the list comprehension only go down the rootpath once and stop, > not walking to the subfolders? > > The list comprehension builds a list for the one directory. If you want them all, you'll have to append those lists into another list, giving you a nested list. -- DaveA From paradox at pobox.com Fri Mar 15 08:13:31 2013 From: paradox at pobox.com (Paradox) Date: Fri, 15 Mar 2013 15:13:31 +0800 Subject: [Tutor] Getting os.walk output into a list :p: In-Reply-To: <5142C05B.7040805@davea.name> References: <5142B752.9010101@pobox.com> <5142C05B.7040805@davea.name> Message-ID: <5142CA1B.6030307@pobox.com> On 03/15/2013 02:31 PM, Dave Angel wrote: > On 03/15/2013 01:53 AM, Paradox wrote: >> There is something I can't figure out about the following code (using >> python 2.7.3): >> >> def return_tree_files(rootpath, pattern): >> for root, dirs, files in os.walk(rootpath): >> i = [os.path.join(root, filename) for filename in >> fnmatch.filter(files, pattern)] >> return i >> >> I thought the function would return a list of lists of filenames in the >> rootpath and all subfolders. Instead I get only the filenames that >> match the pattern in the rootpath, it doesn't go into the subfolders. > That's because you returned out of the loop, the first time through. > Each time through the loop, it describes one directory. Since your > return after the first one, that's the only directory you'll see. That makes a lot of sense, thanks so much. I knew the return must be doing something I didn't understand. thomas From mlybrand at gmail.com Fri Mar 15 08:57:21 2013 From: mlybrand at gmail.com (Mark Lybrand) Date: Fri, 15 Mar 2013 00:57:21 -0700 Subject: [Tutor] Random Python Tip Message-ID: I seem to remember a web page that generated a random Python programming tip. However my Google Fu is weak today. Does anyone recall the URL of what I am talking about? -- Mark :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Fri Mar 15 13:26:37 2013 From: davea at davea.name (Dave Angel) Date: Fri, 15 Mar 2013 08:26:37 -0400 Subject: [Tutor] Random Python Tip In-Reply-To: References: Message-ID: <5143137D.3090607@davea.name> On 03/15/2013 03:57 AM, Mark Lybrand wrote: > I seem to remember a web page that generated a random Python programming > tip. However my Google Fu is weak today. Does anyone recall the URL of > what I am talking about? > > > Closest that I've seen is the "Module of the Week" http://www.doughellmann.com/PyMOTW/ Or maybe this: https://twitter.com/python_tips But I'd love to see a daily tip that supplied something very simple, elegant and memorable. http://openbookproject.net/pybiblio/practice/wilson/ One other thing: Much of what you'll find for advice is mistaken or misguided. So learn how to test the advice, and learn who to trust when you have no way to test it yourself. One advantage with a mailing list like this is you have lots of people ready to correct typos and misconceptions. This can generate lots of noise, but has a huge net benefit.l -- DaveA From bgailer at gmail.com Fri Mar 15 13:49:30 2013 From: bgailer at gmail.com (bob gailer) Date: Fri, 15 Mar 2013 08:49:30 -0400 Subject: [Tutor] Designing a program (File-Fetcher) In-Reply-To: References: Message-ID: <514318DA.6060703@gmail.com> On 3/14/2013 5:25 PM, Christopher Emery wrote: > Hello All, > > Okay, I know the best way to learn how to do something is to jump in > so I have decided I would like to make a program (command line) to get > files from a website that will be then used later on by another program. > > I read your post before reading Alan's reply. I had the same thought - > tackle one piece then add on.file-fetcher (within zip file) [snip] > Okay with the above said, how should I start to do pseduo code? There is no formal pseudocode - you write the steps as you think of then ask is that explicit enough to code or should I break it down more? Python has been called executable pseudocode. Might as well begin writing in Python but not rigidly. > Would each of the above be a function within the program? Perhaps. In your case I'd do that to keep the "main" program simple. > How would someone run a command that is normally done at the command > line like espeak within python program? There seems to be an inconsistency at http://espeak.sourceforge.net/download.html It says Compiled for Windows. SAPI5 and command-line versions. but all I get is TTSApp.exe which opens the GUI I am looking for the command line program (Linux and Windows) to speak text from a file or from stdin. Do you know where it is or how one gets it? Take a look at thesubprocess module - this is the usual way to run such a program and give it input. > Also how would I hide the visual output of a command like espeak, it > throws alot of erros but it works, it happens to others using it too. Can't address this as I apparently don't have the correct executable. -- Bob Gailer 919-636-4239 Chapel Hill NC From sydney.shall at kcl.ac.uk Fri Mar 15 14:52:57 2013 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Fri, 15 Mar 2013 13:52:57 +0000 Subject: [Tutor] converting upper case to lowercase and vice-versa Message-ID: <514327B9.9060207@kcl.ac.uk> I am just learning Python and my book does not solve my problem. I have not yet been successful in searching the Python 2.7.3 tutorial I am doing an encryption exercise. Python 2.7.3 MAC OS X 10.6.8 What is the correct syntax to covert English characters from uppercase to lowercase and from lowercase to uppercase? With many thanks, Sydney -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Fri Mar 15 15:13:59 2013 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Fri, 15 Mar 2013 15:13:59 +0100 Subject: [Tutor] converting upper case to lowercase and vice-versa In-Reply-To: <514327B9.9060207@kcl.ac.uk> References: <514327B9.9060207@kcl.ac.uk> Message-ID: > What is the correct syntax to covert English characters from uppercase to > lowercase and from lowercase to uppercase? > s.upper() and s.lower() -- best regards, Robert S. From cpe.list at gmail.com Fri Mar 15 15:39:21 2013 From: cpe.list at gmail.com (Christopher Emery) Date: Fri, 15 Mar 2013 10:39:21 -0400 Subject: [Tutor] Designing a program (File-Fetcher) In-Reply-To: <514318DA.6060703@gmail.com> References: <514318DA.6060703@gmail.com> Message-ID: Hello Bob, BG: I am looking for the command line program (Linux and Windows) to speak text from a file or from stdin. Do you know where it is or how one gets it? CE: If you are putting it on Linux such as debian then you can run apt-get install eSpeak, it is in most distro of Linux these days. Otherwise I don't have a clue. To run it on the command line type espeak "text here" there are other things you can do with it but I don't know yet a whole lot as I am just learning. Sincerely in Christ, Christopher On Fri, Mar 15, 2013 at 8:49 AM, bob gailer wrote: > On 3/14/2013 5:25 PM, Christopher Emery wrote: >> >> Hello All, >> >> Okay, I know the best way to learn how to do something is to jump in so I >> have decided I would like to make a program (command line) to get files from >> a website that will be then used later on by another program. >> >> I read your post before reading Alan's reply. I had the same thought - >> tackle one piece then add on.file-fetcher (within zip file) > > [snip] >> >> Okay with the above said, how should I start to do pseduo code? > > There is no formal pseudocode - you write the steps as you think of then ask > is that explicit enough to code or should I break it down more? > > Python has been called executable pseudocode. Might as well begin writing in > Python but not rigidly. > >> Would each of the above be a function within the program? > > Perhaps. In your case I'd do that to keep the "main" program simple. > >> How would someone run a command that is normally done at the command line >> like espeak within python program? > > There seems to be an inconsistency at > http://espeak.sourceforge.net/download.html > It says Compiled for Windows. SAPI5 and command-line versions. but all I get > is TTSApp.exe which opens the GUI > I am looking for the command line program (Linux and Windows) to speak text > from a file or from stdin. > Do you know where it is or how one gets it? > > Take a look at thesubprocess module - this is the usual way to run such a > program and give it input. > > >> Also how would I hide the visual output of a command like espeak, it >> throws alot of erros but it works, it happens to others using it too. > > Can't address this as I apparently don't have the correct executable. > > -- > Bob Gailer > 919-636-4239 > Chapel Hill NC > From bodsda at googlemail.com Fri Mar 15 16:45:27 2013 From: bodsda at googlemail.com (Bod Soutar) Date: Fri, 15 Mar 2013 15:45:27 +0000 Subject: [Tutor] Fwd: converting upper case to lowercase and vice-versa In-Reply-To: <514333A8.40506@kcl.ac.uk> References: <514327B9.9060207@kcl.ac.uk> <514333A8.40506@kcl.ac.uk> Message-ID: Did'nt realise this went offlist, my fault -- Bodsda ---------- Forwarded message ---------- From: Shall, Sydney Date: 15 March 2013 14:43 Subject: Re: [Tutor] converting upper case to lowercase and vice-versa To: Bod Soutar On 15/03/2013 14:30, Bod Soutar wrote: On 15 March 2013 13:52, Shall, Sydney wrote: I am just learning Python and my book does not solve my problem. I have not yet been successful in searching the Python 2.7.3 tutorial I am doing an encryption exercise. Python 2.7.3 MAC OS X 10.6.8 What is the correct syntax to covert English characters from uppercase to lowercase and from lowercase to uppercase? With many thanks, Sydney -- mystring = "THIS is A string" newstring = "" for item in mystring: if item.isupper(): newstring += item.upper() else: newstring += item.lower() print newstring Thanks Bod, This is most helpful. In fact, your syntax allows me to now simplify my code. Sydney -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk From __peter__ at web.de Fri Mar 15 17:22:34 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 15 Mar 2013 17:22:34 +0100 Subject: [Tutor] Fwd: converting upper case to lowercase and vice-versa References: <514327B9.9060207@kcl.ac.uk> <514333A8.40506@kcl.ac.uk> Message-ID: Bod Soutar wrote: > mystring = "THIS is A string" > newstring = "" > for item in mystring: > if item.isupper(): > newstring += item.upper() > else: > newstring += item.lower() > > print newstring This does nothing the hard way as newstring and mystring are equal ;) If you accidentally swapped the if-suite and the else-suite -- there's the swapcase() method: >>> mystring = "THIS is A string" >>> print mystring.swapcase() this IS a STRING From cpe.list at gmail.com Fri Mar 15 17:51:23 2013 From: cpe.list at gmail.com (Christopher Emery) Date: Fri, 15 Mar 2013 12:51:23 -0400 Subject: [Tutor] File-Fetcher (cmdline-parser) Message-ID: Hello All, OS = Raspbain Wheezy & Ubuntu 12.10 (both updated daily) Python Version = 3.2 & 3.3 Python Understanding = Beginner (very basic - just started) See paste bin for code, has 44 lines, code does not give any errors. http://pastebin.com/2tLHvUym Okay, I am writing to ask a few question and provide what I have done already. When using argparse.argument is it wise to use dest="" even if you don't mind having it set automatic to the arg option such as -u will become u="None" if it no arg is passed? Because there are options that can be added to each .add_argument such as help=, action= is it a good idea to set each one of them even if the default behavior is what you want? I thinking future proofing wise. In my formatting of my function which will be one of many, am I laying the code out in a way that will become a good habit or should I do it different? If so how? Based on my comments within the function am I understanding what is going on? At the end I use a print() to see if all is being passed or not being passed through the cmdline, my question for you is if I want to access the varibles that are passed through the return args, do I just take the function like this: outside_of_functions_var = cmdline_parser() Does this make outside_of_functions_var a dict or list or other? Thank you for your assistance and insight into learning. Also if I can format my emails to the list in a different way that would make it easier for those to help please do inform me too. Sincerely in Christ, Christopher From __peter__ at web.de Fri Mar 15 18:19:22 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 15 Mar 2013 18:19:22 +0100 Subject: [Tutor] File-Fetcher (cmdline-parser) References: Message-ID: Christopher Emery wrote: > Hello All, > > OS = Raspbain Wheezy & Ubuntu 12.10 (both updated daily) > > Python Version = 3.2 & 3.3 > Python Understanding = Beginner (very basic - just started) > > See paste bin for code, has 44 lines, code does not give any errors. > http://pastebin.com/2tLHvUym > > Okay, I am writing to ask a few question and provide what I have done > already. > > When using argparse.argument is it wise to use dest="" even if you > don't mind having it set automatic to the arg option such as -u will > become u="None" if it no arg is passed? dest determines the attribute name under which the option is stored. I rarely set it explicitly; instead I provide a --long-option: cmdline_parser.add_argument( "-u", "--url-source", help="the url of where the file can be downloaded.") > Because there are options that can be added to each .add_argument such > as help=, action= is it a good idea to set each one of them even if > the default behavior is what you want? I thinking future proofing > wise. To my eyes this is just noise. > In my formatting of my function which will be one of many, am I laying > the code out in a way that will become a good habit or should I do it > different? If so how? > > Based on my comments within the function am I understanding what is going > on? > > At the end I use a print() to see if all is being passed or not being > passed through the cmdline, my question for you is if I want to access > the varibles that are passed through the return args, do I just take > the function like this: > outside_of_functions_var = cmdline_parser() > Does this make outside_of_functions_var a dict or list or other? Neither a dict nor a list, it is an argparse.Namespace object. You can access commandline options as its attributes: args = cmdline_parser() print(args.url_source) From cpe.list at gmail.com Fri Mar 15 18:45:13 2013 From: cpe.list at gmail.com (Christopher Emery) Date: Fri, 15 Mar 2013 13:45:13 -0400 Subject: [Tutor] File-Fetcher (cmdline-parser) In-Reply-To: References: Message-ID: Hello Peter, First let me say thanks for your feedback, please see comments / question below, yours starting with PO and mine starting with CE. PO: dest determines the attribute name under which the option is stored. I rarely set it explicitly; instead I provide a --long-option: CE: Is there a advantage over on or the other? CE: Because there are options that can be added to each .add_argument such as help=, action= is it a good idea to set each one of them even if the default behavior is what you want? I thinking future proofing wise. PO: To my eyes this is just noise. CE: I would agree, to me less the better as long as it can be understood and your not going to break something in the near future that will change. CE: At the end I use a print() to see if all is being passed or not being passed through the cmdline, my question for you is if I want to access the varibles that are passed through the return args, do I just take the function like this: outside_of_functions_var = cmdline_parser() Does this make outside_of_functions_var a dict or list or other? PO: Neither a dict nor a list, it is an argparse.Namespace object. You can access commandline options as its attributes: CE: Okay, so when I use print(args.file_list) or better yet if I take list = args.file_list does it stay a Namespace object or does it change? if it stays the same how do I access the list of files inside it? Thank you ahead of time for your assistance in helping me to learn and understand. Sincerely in Christ, Christopher From __peter__ at web.de Fri Mar 15 19:18:37 2013 From: __peter__ at web.de (Peter Otten) Date: Fri, 15 Mar 2013 19:18:37 +0100 Subject: [Tutor] File-Fetcher (cmdline-parser) References: Message-ID: Christopher Emery wrote: > Hello Peter, > > First let me say thanks for your feedback, please see comments / > question below, yours starting with PO and mine starting with CE. > > PO: dest determines the attribute name under which the option is > stored. I rarely set it explicitly; instead I provide a --long-option: > CE: Is there a advantage over on or the other? The advantage is basically that you get a long option ;) This makes for calls in bash scripts, say, that are easier to understand. Also, if you make it a habit to keep long option and dest in sync (something you get for free if you only specify the option) you can deduce the attribute name used in the script from its commandline interface. If in a few months you want to make modifications you will know what to look for in the script. > CE: Because there are options that can be added to each .add_argument > such as help=, action= is it a good idea to set each one of them even > if the default behavior is what you want? I thinking future proofing > wise. > PO: To my eyes this is just noise. > CE: I would agree, to me less the better as long as it can be > understood and your not going to break something in the near future > that will change. > > CE: At the end I use a print() to see if all is being passed or not > being passed through the cmdline, my question for you is if I want to > access the varibles that are passed through the return args, do I just > take the function like this: > outside_of_functions_var = cmdline_parser() > Does this make outside_of_functions_var a dict or list or other? > PO: Neither a dict nor a list, it is an argparse.Namespace object. You > can access commandline options as its attributes: > CE: Okay, so when I use print(args.file_list) or better yet if I take > list = args.file_list does it stay a Namespace object or does it > change? if it stays the same how do I access the list of files inside > it? While args is a Namespace instance args.file_list is a list (if you provide the option at least once on the commandline): $ cat tmp_filefetcher.py import argparse parser = argparse.ArgumentParser() parser.add_argument('-l', "--file-list", action="append") args = parser.parse_args() print("args =", args) print("args.file_list = ", args.file_list) $ python3 tmp_filefetcher.py args = Namespace(file_list=None) args.file_list = None $ python3 tmp_filefetcher.py -l alpha -l beta args = Namespace(file_list=['alpha', 'beta']) args.file_list = ['alpha', 'beta'] From cpe.list at gmail.com Fri Mar 15 19:52:22 2013 From: cpe.list at gmail.com (Christopher Emery) Date: Fri, 15 Mar 2013 14:52:22 -0400 Subject: [Tutor] File-Fetcher (cmdline-parser) In-Reply-To: References: Message-ID: Hello Peter, Thank you this is much appreciated! It is much clear now. Thank you PO: Also, if you make it a habit to keep long option and dest in sync (something you get for free if you only specify the option) you can deduce the attribute name used in the script from its commandline interface. CE: Can you please explain this deeper please? I am not sure if I am getting it. Sincerely in Christ, Christopher From charles.leviton at gmail.com Fri Mar 15 20:42:15 2013 From: charles.leviton at gmail.com (Charles Leviton) Date: Fri, 15 Mar 2013 15:42:15 -0400 Subject: [Tutor] Script to generate statements Message-ID: I was recently given this task. it's a very IBM mainframe specific task so I'm not sure how to find equivalent terms in another environment. I will just use the mainframe terminology and hopefully y'all can figure out what I mean. Given a list of DBRM members create a JCL which has a series of bind statements for each DBRM. This is the tack I took. I have 3 input files a_ contains the fixed part of the JCL b_ contains the template for the bind statement. c_ contains the list of DBRMs This is the script I came up with...Would you critique it and let me know how I could have done it better? #create a series of bind statements fo = open('i:/text/jclout.txt', 'w') fi = open('i:/text/bindjclfirstpart.txt','rU') fibindjclvar = open('i:/text/bindjclvariable.txt','rU') filistofdbrms= open('i:/text/bindjcldbrmlist.txt','rU') varlines =[] varlines = fibindjclvar.readlines() for line in fi: #write out all the lines in the first part of JCL fo.write(line) fo.write('\n') varline = '' for dbrm in filistofdbrms: fo.write('\n') for index in range(0,9): if varlines[index].find('member') > 0: varline = varlines[index] + '('+ dbrm + ')' + ' -' else: varline = varlines[index] fo.write(varline) fo.close() fi.close() fibindjclvar.close() filistofdbrms.close() The "variable" part of the bind statement is where I have to include the DBRM name. I look for the word 'member' in the template. Template looks like this (content of bindjclvariable.txt) BIND PACKAGE(PROD) - MEMBER OWNER(PRODOWNR) - QUALIFIER(PRODTBLS) - ISOLATION(CS) - EXPLAIN(YES) - ACTION(REPLACE) - CURRENTDATA(YES) - VALIDATE(BIND) Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Fri Mar 15 21:30:37 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 15 Mar 2013 20:30:37 +0000 Subject: [Tutor] File-Fetcher (cmdline-parser) In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF47418249D7E@SCACMX008.exchad.jpmchase.net> Christopher Emery wrote: > Hello Peter, > > Thank you this is much appreciated! It is much clear now. Thank you > > PO: Also, if you make it a habit to keep long option and dest in sync > (something you get for free if you only specify the option) you can > deduce the attribute name used in the script from its commandline > interface. > CE: Can you please explain this deeper please? I am not sure if I am getting it. Don't take offense at the below, I am just making a suggestion that I think will help you communicate better on this list (and others). This is not really the style for this mailing list responses. Normally, you add an attribution header and quote level so people can see who is talking and who is being quoted. In addition, post your response in-line (or after) the quoted text. Quoting is indicated by prefixing "> " to the quoted text. Most (if not all) email/news reader programs have an option to do this for you. This makes it easy to understand the who said what and in response to what. An example is below (and I made up the conversation, not actually quoting anything). ================================= Christopher Emery wrote: > Peter wrote: > > Imaginary_Talker wrote: > > > I am Imaginary_Talker > > Hi Imaginary_Talker, I am Peter. > Hi Peter, I am Christopher. Hi Christopher, I am Ramit. ================================= > > Sincerely in Christ, > Christopher ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From cpe.list at gmail.com Fri Mar 15 21:47:09 2013 From: cpe.list at gmail.com (Christopher Emery) Date: Fri, 15 Mar 2013 16:47:09 -0400 Subject: [Tutor] File-Fetcher (cmdline-parser) In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47418249D7E@SCACMX008.exchad.jpmchase.net> References: <5B80DD153D7D744689F57F4FB69AF47418249D7E@SCACMX008.exchad.jpmchase.net> Message-ID: Hello Ramit, No offense taking. I guess I am now going to disclose information. I do this because I am blind and its not easy to follow people basing it off of > or >> or >>>>>>>> as people don't know how to clean up there mails,I try my best to and clean others trails all the time. However in a perfect world my taking extra time would not be needed to figure out and keep track of who is saying what. So please don't mind me adjusting information so I can follow the flow for future and even present. Hope you understand! Sincerely in Christ, Christopher On Fri, Mar 15, 2013 at 4:30 PM, Prasad, Ramit wrote: > Christopher Emery wrote: >> Hello Peter, >> >> Thank you this is much appreciated! It is much clear now. Thank you >> >> PO: Also, if you make it a habit to keep long option and dest in sync >> (something you get for free if you only specify the option) you can >> deduce the attribute name used in the script from its commandline >> interface. >> CE: Can you please explain this deeper please? I am not sure if I am getting it. > > Don't take offense at the below, I am just making a suggestion that I > think will help you communicate better on this list (and others). > > This is not really the style for this mailing list responses. > Normally, you add an attribution header and quote level so people > can see who is talking and who is being quoted. In addition, post > your response in-line (or after) the quoted text. Quoting is indicated > by prefixing "> " to the quoted text. Most (if not all) email/news > reader programs have an option to do this for you. This makes it easy > to understand the who said what and in response to what. > > An example is below (and I made up the conversation, not actually quoting > anything). > > ================================= > Christopher Emery wrote: >> Peter wrote: >> > Imaginary_Talker wrote: >> > > I am Imaginary_Talker >> > Hi Imaginary_Talker, I am Peter. >> Hi Peter, I am Christopher. > Hi Christopher, I am Ramit. > ================================= > >> >> Sincerely in Christ, >> Christopher > > > ~Ramit > > > > This email is confidential and subject to important disclaimers and > conditions including on offers for the purchase or sale of > securities, accuracy and completeness of information, viruses, > confidentiality, legal privilege, and legal entity disclaimers, > available at http://www.jpmorgan.com/pages/disclosures/email. From cpe.list at gmail.com Fri Mar 15 22:01:50 2013 From: cpe.list at gmail.com (Christopher Emery) Date: Fri, 15 Mar 2013 17:01:50 -0400 Subject: [Tutor] func-question_y_n.py Message-ID: Hello All, Okay, I have created a small function that will check to see if a user has answered with a Yes, No or other response. If the user puts yes or no the function ends, if they put anything but yes or no then the function will ask them the same question and tell them they either need to put yes or no for their response This is what I have as of now: ### Start of Code ### def question_y_n(question): answer = input(question) while(answer != "Yes"): if answer != "No": print("Please enter Yes or No for your response!") answer = input(question) else: answer = "No" break return answer answer = question_y_n("You want a drink of water? :") print("Your answer to the question was ", answer) ### End of Code ### Is this the best way to handle this? I would like to use this any time I have a yes or no question. In the future I will add to this and make it work with yes/no, true/false, 1/0 so that anytime there is anything that only has two answer I could use this instead of writing more code for each two answer type questions. Thank you for your advice ahead of time!!! PS: I hope don't mind me posting code that works to see if I can improve on it! Sincerely in Christ, Christopher From hugo.yoshi at gmail.com Fri Mar 15 22:03:13 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 15 Mar 2013 21:03:13 +0000 Subject: [Tutor] Script to generate statements In-Reply-To: References: Message-ID: On Fri, Mar 15, 2013 at 7:42 PM, Charles Leviton wrote: > I was recently given this task. it's a very IBM mainframe specific task > so I'm not sure how to find equivalent terms in another environment. I > will just use the mainframe terminology and hopefully y'all can figure out > what I mean. > > Given a list of DBRM members create a JCL which has a series of bind > statements for each DBRM. > > This is the tack I took. I have 3 input files > a_ contains the fixed part of the JCL > b_ contains the template for the bind statement. > c_ contains the list of DBRMs > > > This is the script I came up with...Would you critique it and let me know > how I could have done it better? > #create a series of bind statements > fo = open('i:/text/jclout.txt', 'w') > fi = open('i:/text/bindjclfirstpart.txt','rU') > fibindjclvar = open('i:/text/bindjclvariable.txt','rU') > filistofdbrms= open('i:/text/bindjcldbrmlist.txt','rU') > > varlines =[] > varlines = fibindjclvar.readlines() > for line in fi: #write out all the lines in the first part of JCL > fo.write(line) > fo.write('\n') > varline = '' > for dbrm in filistofdbrms: > fo.write('\n') > for index in range(0,9): > if varlines[index].find('member') > 0: > varline = varlines[index] + '('+ dbrm + ')' + ' -' > else: > varline = varlines[index] > fo.write(varline) > > fo.close() > fi.close() > fibindjclvar.close() > filistofdbrms.close() > > The "variable" part of the bind statement is where I have to include the > DBRM name. I look for the word 'member' in the template. > Template looks like this (content of bindjclvariable.txt) > BIND PACKAGE(PROD) - > MEMBER > OWNER(PRODOWNR) - > QUALIFIER(PRODTBLS) - > ISOLATION(CS) - > EXPLAIN(YES) - > ACTION(REPLACE) - > CURRENTDATA(YES) - > VALIDATE(BIND) > > Thanks! > I have a few comments * Does the script work? If yes, I'd say it's probably fine. Pretty short so easy to understand whatever you do, and I see no obviously crazy broken shit in there. I don't much like 'fi' and 'fo' for variable names because I have no idea what it means, but it's not a huge issue in a script this small. If anything, I'd suggest more descriptive variable names and just a tad more use of underscores in them to make it easier on the eyes. Google PEP 8 and check it out, it's the python style guide. * I have no clue what DBRM or JCL are, and what a bind statement is. Ideally, if you could give us some examples of what your input and output looks like, I have a much better idea of what the script is trying to do. * Not knowing what version of python you have greatly limits the amount of useful advice I can give you. More modern versions support stuff like with statements to simplify file handling and the str.format function which may be very useful in your template (you could also use % style formatting, perhaps?). But if you're still on 2.5, which wouldn't surprise me on a big mainframe, you don't have the cool stuff yet. Like I said in the first point though, the script is very small and everything looks quite reasonable. It seems readable enough *if* you know what kind of input and output date it's dealing with. HTH, Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Fri Mar 15 22:20:16 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 15 Mar 2013 21:20:16 +0000 Subject: [Tutor] func-question_y_n.py In-Reply-To: References: Message-ID: On Fri, Mar 15, 2013 at 9:01 PM, Christopher Emery wrote: > Hello All, > > Okay, I have created a small function that will check to see if a user > has answered with a Yes, No or other response. If the user puts yes > or no the function ends, if they put anything but yes or no then the > function will ask them the same question and tell them they either > need to put yes or no for their response > > This is what I have as of now: > ### Start of Code ### > def question_y_n(question): > answer = input(question) > while(answer != "Yes"): > if answer != "No": > print("Please enter Yes or No for your response!") > answer = input(question) > else: > answer = "No" > break > return answer > > answer = question_y_n("You want a drink of water? :") > print("Your answer to the question was ", answer) > ### End of Code ### > > Is this the best way to handle this? I would like to use this any > time I have a yes or no question. In the future I will add to this and > make it work with yes/no, true/false, 1/0 so that anytime there is > anything that only has two answer I could use this instead of writing > more code for each two answer type questions. > > Thank you for your advice ahead of time!!! > > PS: I hope don't mind me posting code that works to see if I can improve > on it! > Hey Christopher, posting code that works is totally fine! Let's see how we can improve this little function. The thing that is bugging me most about this code is that the structure of the code is kind of hard to understand, because it doesn't quite clearly match the description you gave of the purpose of the function. Your description was quite nice and simple already, I'm just going to slightly reformat it and put it in a numbered step-by-step format: 1. ask a question, receive an answer 2. if the answer is "Yes" or "No", return the answer 3. else, print a message and go back to step 1 That's a very clear description of the problem, and we like that. So ideally, the code should look as much as possible like that description and it will be very clear and simple as well! I could write the code for you now, but I think you will learn far better if first you try yourself. You might notice some words in the description are already very similar to python code structures. If you get stuck, don't hesitate to come back with whatever code you have, even if that's totally broken and not even valid python. We love seeing people who are trying to figure stuff out and don't want the solution handed to them :) HTH, Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From cmacleod170 at googlemail.com Fri Mar 15 22:21:54 2013 From: cmacleod170 at googlemail.com (Cameron Macleod) Date: Fri, 15 Mar 2013 21:21:54 +0000 Subject: [Tutor] __init__ doesn't seem to be running Message-ID: Hello everyone, I'm using Python 3.3 and am trying to write a simple to-do list program. I have a class which runs pretty much everything called todo and the __init__ method doesn't seem to be running. class todo(): def __init__(self): tasks = [] def writeTask(todoList): name = input("Please enter the task > ") desc = input("Please enter a short description (optional) > ") while True: try: imp = int(input("How important is this task? 1-100 > ")) break except TypeError: imp = int(input("How important is this task? 1-100 > ")) if imp > 100: imp = 100 elif imp < 1: imp = 1 todoList.write("\"" + name + "\",\"" + desc + "\",\"" + str(imp) + "\"") print("Task written!") try: todoList = open('todo.txt', 'r+') except IOError: todoList = open('todo.txt', 'w') for line in todoList: tasks.append(line.strip()) writeTask(todoList) todoList.close() main = todo() Whenever I run this, I get the error: Traceback (most recent call last): File "C:\Python33\todo.py", line 8, in class todo(): File "C:\Python33\todo.py", line 34, in todo tasks.append(line.strip()) NameError: name 'tasks' is not defined Indicating that __init__ hasn't run since that is the initialization for tasks. I had always understood that __init__ was the equivalent of a constructor, and should be run at the instantiation of any class. Any help would be much appreciated, Cameron -------------- next part -------------- An HTML attachment was scrubbed... URL: From msirenef at lightbird.net Fri Mar 15 22:28:29 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Fri, 15 Mar 2013 17:28:29 -0400 Subject: [Tutor] func-question_y_n.py In-Reply-To: References: Message-ID: <5143927D.1040709@lightbird.net> On 03/15/2013 05:01 PM, Christopher Emery wrote: > Hello All, > > Okay, I have created a small function that will check to see if a user > has answered with a Yes, No or other response. If the user puts yes > or no the function ends, if they put anything but yes or no then the > function will ask them the same question and tell them they either > need to put yes or no for their response > > This is what I have as of now: > ### Start of Code ### > def question_y_n(question): > answer = input(question) > while(answer != "Yes"): > if answer != "No": > print("Please enter Yes or No for your response!") > answer = input(question) > else: > answer = "No" > break > return answer > > answer = question_y_n("You want a drink of water? :") > print("Your answer to the question was ", answer) > ### End of Code ### > > Is this the best way to handle this? I would like to use this any > time I have a yes or no question. In the future I will add to this and > make it work with yes/no, true/false, 1/0 so that anytime there is > anything that only has two answer I could use this instead of writing > more code for each two answer type questions. > > Thank you for your advice ahead of time!!! > > PS: I hope don't mind me posting code that works to see if I can improve on it! > > Sincerely in Christ, > Christopher Hi Christopher, I've recently made a couple of functions that do this in a more general way. There are some usage examples at the end, including y/n input. The difference between them is that the 2nd function adds more options. import re def simpleinp(pattern, prompt="> ", convert=None, errmsg="Invalid Input", blank=False): """Keep asking user for input until it matches `pattern`.""" if pattern == "%d": pattern = "\d+"; convert = int if pattern == "%s": pattern = ".+" while True: i = input(prompt).strip() if blank and not i: return None if re.match('^'+pattern+'$', i): return convert(i) if convert and i else i else: print(errmsg) def getinp(pattern, prompt="> ", convert=None, errmsg="Invalid Input", ignorecase=False, lower=False, blank=True): """Keep asking user for input until it matches `pattern`.""" if pattern == "%d": pattern = "\d+" convert = int if pattern == "%f": pattern = "\d+.?\d*" convert = float if pattern == "%s": pattern = "\S+" while True: i = input(prompt).strip() if blank and not i: return None if lower: i = i.lower() flags = re.I if ignorecase else 0 if re.match('^'+pattern+'$', i, flags=flags): return convert(i) if convert else i else: print(errmsg) # print( getinp("%d", "integer: ") ) # print( getinp("%f", "float: ") ) # print( getinp("%s", "string: ") ) # print( getinp("(y|n)", "y/n: ", lower=True) ) # print( simpleinp("%d", "integer: ") ) # print( simpleinp("%s", "string: ") ) # print( simpleinp(".*", "string or blank: ") ) # print( simpleinp("[ynYN]", "y/n: ") ) HTH, -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ The dreamer can know no truth, not even about his dream, except by awaking out of it. George Santayana From hugo.yoshi at gmail.com Fri Mar 15 22:42:02 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 15 Mar 2013 21:42:02 +0000 Subject: [Tutor] __init__ doesn't seem to be running In-Reply-To: References: Message-ID: On Fri, Mar 15, 2013 at 9:21 PM, Cameron Macleod wrote: > Hello everyone, I'm using Python 3.3 and am trying to write a simple to-do > list program. I have a class which runs pretty much everything called todo > and the __init__ method doesn't seem to be running. > > class todo(): > def __init__(self): > tasks = [] > > def writeTask(todoList): > name = input("Please enter the task > ") > desc = input("Please enter a short description (optional) > ") > while True: > try: > imp = int(input("How important is this task? 1-100 > ")) > break > except TypeError: > imp = int(input("How important is this task? 1-100 > ")) > if imp > 100: > imp = 100 > elif imp < 1: > imp = 1 > todoList.write("\"" + name + "\",\"" + desc + "\",\"" + str(imp) + > "\"") > print("Task written!") > try: > todoList = open('todo.txt', 'r+') > except IOError: > todoList = open('todo.txt', 'w') > for line in todoList: > tasks.append(line.strip()) > writeTask(todoList) > todoList.close() > > main = todo() > > Whenever I run this, I get the error: > > Traceback (most recent call last): > File "C:\Python33\todo.py", line 8, in > class todo(): > File "C:\Python33\todo.py", line 34, in todo > tasks.append(line.strip()) > NameError: name 'tasks' is not defined > > Indicating that __init__ hasn't run since that is the initialization for > tasks. I had always understood that __init__ was the equivalent of a > constructor, and should be run at the instantiation of any class. > That's not what it indicates, you should assume less and debug more. If you add a print statement in __init__, I can guarantee that you will see it executed. Go, try it now, don't assume I'm right ;) Now, the only thing that this error actually indicates is that "tasks" doesn't exist when writeTask is being executed. In both __init__ and writeTask, the "tasks" variable is function-local: it exists only for the duration of the function. What you want is to attach tasks to your object instance, which you do through "self". self is the reference to the current instance, much like the this pointer in Java or C++. So if you do: class Todo: def __init__(self): self.tasks = [] def write_task(self, task): # other code around here self.tasks.append(line.strip()) everything will be fine. HTH, Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From cpe.list at gmail.com Fri Mar 15 22:47:30 2013 From: cpe.list at gmail.com (Christopher Emery) Date: Fri, 15 Mar 2013 17:47:30 -0400 Subject: [Tutor] func-question_y_n.py In-Reply-To: <5143927D.1040709@lightbird.net> References: <5143927D.1040709@lightbird.net> Message-ID: Hi Mitya, Thank for your example of code, however at this time its well over my head and I think its best if I slowly work on a function that provided only what I need and then add to it IF it works into it. Yours appears to do a whole lot more then process a Yes/No from a question and re-ask the question if the user does not provide a yes or no. I will save your code for future use as I understand it more (smile) Sincerely in Christ, Christopher > I've recently made a couple of functions that do this in a more general > way. There are some usage examples at the end, including y/n input. The > difference between them is that the 2nd function adds more options. From cpe.list at gmail.com Fri Mar 15 23:09:06 2013 From: cpe.list at gmail.com (Christopher Emery) Date: Fri, 15 Mar 2013 18:09:06 -0400 Subject: [Tutor] func-question_y_n.py In-Reply-To: References: Message-ID: Hello Hugo, # Defines the start of a function and its options (question) def question_y_n(question): #1. Ask Question from user, user enters either Yes, No or whatever (anything that is not Yes or No) answer = input(question) # prompts the user and assigns the answer to var answer #2. If the user had entered anything but Yes then a while loop starts and becomes True (meaning it is not a Yes) so it must be either No or something else while(answer != "Yes"): #3. If the answer is anything but a No then the user is prompted with statement and then the question asked again if answer != "No": #4. Print statement and ask question again. print("Please enter Yes or No for your response!") answer = input(question) #5. It is assumed that if the answer was not a Yes in the while loop and it was not a No in the if statement than it is assumed the only other choice would be a No for the else statement. else: answer = "No" break return answer answer = question_y_n("You want a drink of water? :") print("Your answer to the question was ", answer) This code works and produces the results that I am looking for, however I know there is a better way to do it and now you have me thinking about this again. I just spent about 3 hours doing this code. I was thinking of combining the Yes and No into one check however I was having trouble finding resource of how to do mulitiy checks in a statement for while. thinking like this: def question_y_n(question): answer = input(question) while(answer != "Yes" Or "No"): #This is wrong code print("Please enter Yes or No for your response!") answer = input(question) or # This one does not have ability to loop intill a Yes or No is given so my gut tells me the one above is better or the one I have at this time. def question_y_n(question): answer = input(question) if answer == "Yes" OR "No": #this didn't work either for me break else print("Please enter Yes or No for your response!") answer = input(question) return answer Sorry for this layout, I myself was getting a little dizzy reading it. Thank you for your assistance! Sincerely in Christ, Christopher From cmacleod170 at googlemail.com Fri Mar 15 23:25:33 2013 From: cmacleod170 at googlemail.com (Cameron Macleod) Date: Fri, 15 Mar 2013 22:25:33 +0000 Subject: [Tutor] __init__ doesn't seem to be running In-Reply-To: References: Message-ID: I added the "self." to both the references to tasks and then I added the print statement to the __init__ function and I got the dreaded NameError of death: Traceback (most recent call last): File "C:\Python33\todo.py", line 6, in class todo: File "C:\Python33\todo.py", line 31, in todo self.tasks.append(line.strip()) NameError: name 'self' is not defined I then moved the entirety of the code that appeared outside of the functions but within the class into the writeTask function, this produced the longed after print statement and no errors, but was inappropriate for the task in hand. So I re-jiggled most of it into the __init__ method and left the call to writeTask outside of the class, passing in the argument main.todoList . This gave me the print statement (the init is running now!) but also this error: Traceback (most recent call last): File "C:\Python33\todo.py", line 34, in main.writeTask(main.todoList) AttributeError: 'todo' object has no attribute 'todoList' I fixed this with an attachment to self on the todoList object, but then got this error instead. Traceback (most recent call last): File "C:\Python33\todo.py", line 34, in main = todo() File "C:\Python33\todo.py", line 14, in __init__ for line in todoList: NameError: global name 'todoList' is not defined My code now looks something like this: class todo(): def __init__(self): self.tasks = [] print("Hello") try: self.todoList = open('todo.txt', 'r+') except IOError: self.todoList = open('todo.txt', 'w') for line in todoList: self.tasks.append(line.strip()) def writeTask(todoList): name = input("Please enter the task > ") desc = input("Please enter a short description (optional) > ") while True: try: imp = int(input("How important is this task? 1-100 > ")) break except TypeError: imp = int(input("How important is this task? 1-100 > ")) if imp > 100: imp = 100 elif imp < 1: imp = 1 todoList.write("\"" + name + "\",\"" + desc + "\",\"" + str(imp) + "\"") print("Task written!") main = todo() main.writeTask(main.todoList) It's recognising todoList as global now which is better than not being acknowledged at all, but why would it not be defined? (Sorry if this came up twice, wasn't sure whether or not I'd replied to all) On Fri, Mar 15, 2013 at 9:42 PM, Hugo Arts wrote: > On Fri, Mar 15, 2013 at 9:21 PM, Cameron Macleod < > cmacleod170 at googlemail.com> wrote: > >> Hello everyone, I'm using Python 3.3 and am trying to write a simple >> to-do list program. I have a class which runs pretty much everything called >> todo and the __init__ method doesn't seem to be running. >> >> class todo(): >> def __init__(self): >> tasks = [] >> >> def writeTask(todoList): >> name = input("Please enter the task > ") >> desc = input("Please enter a short description (optional) > ") >> while True: >> try: >> imp = int(input("How important is this task? 1-100 > ")) >> break >> except TypeError: >> imp = int(input("How important is this task? 1-100 > ")) >> if imp > 100: >> imp = 100 >> elif imp < 1: >> imp = 1 >> todoList.write("\"" + name + "\",\"" + desc + "\",\"" + str(imp) >> + "\"") >> print("Task written!") >> try: >> todoList = open('todo.txt', 'r+') >> except IOError: >> todoList = open('todo.txt', 'w') >> for line in todoList: >> tasks.append(line.strip()) >> writeTask(todoList) >> todoList.close() >> >> main = todo() >> >> Whenever I run this, I get the error: >> >> Traceback (most recent call last): >> File "C:\Python33\todo.py", line 8, in >> class todo(): >> File "C:\Python33\todo.py", line 34, in todo >> tasks.append(line.strip()) >> NameError: name 'tasks' is not defined >> >> Indicating that __init__ hasn't run since that is the initialization for >> tasks. I had always understood that __init__ was the equivalent of a >> constructor, and should be run at the instantiation of any class. >> > > That's not what it indicates, you should assume less and debug more. If > you add a print statement in __init__, I can guarantee that you will see it > executed. Go, try it now, don't assume I'm right ;) > > Now, the only thing that this error actually indicates is that "tasks" > doesn't exist when writeTask is being executed. In both __init__ and > writeTask, the "tasks" variable is function-local: it exists only for the > duration of the function. What you want is to attach tasks to your object > instance, which you do through "self". self is the reference to the current > instance, much like the this pointer in Java or C++. So if you do: > > class Todo: > def __init__(self): > self.tasks = [] > > def write_task(self, task): > # other code around here > self.tasks.append(line.strip()) > > everything will be fine. > > HTH, > Hugo > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Fri Mar 15 23:31:51 2013 From: davea at davea.name (Dave Angel) Date: Fri, 15 Mar 2013 18:31:51 -0400 Subject: [Tutor] func-question_y_n.py In-Reply-To: References: Message-ID: <5143A157.6030803@davea.name> On 03/15/2013 06:09 PM, Christopher Emery wrote: ------ Hugo said: ---- ----1. ask a question, receive an answer ----2. if the answer is "Yes" or "No", return the answer ----3. else, print a message and go back to step 1 > Hello Hugo, > > # Defines the start of a function and its options (question) > def question_y_n(question): > > #1. Ask Question from user, user enters either Yes, No or whatever > (anything that is not Yes or No) > answer = input(question) # prompts the user and assigns the answer > to var answer > > #2. If the user had entered anything but Yes then a while loop starts > and becomes True (meaning it is not a Yes) so it must be either No or > something else > while(answer != "Yes"): Hugo's function description is perfectly symmetric with regard to Yes & No. But you've changed that, both in your new description, and in your code. Why is the "while" checking only for "Yes" when it should be checking for either/both? > > > I was thinking of combining the Yes and No into one check however I > was having trouble finding resource of how to do mulitiy checks in a > statement for while. > > thinking like this: > > def question_y_n(question): > answer = input(question) > while(answer != "Yes" Or "No"): #This is wrong code > print("Please enter Yes or No for your response!") > answer = input(question) > or Do you understand about compound if/while expressions? You can combine boolean expressions with 'and' and 'or' . For example, if you had wanted to check for either 4 or 12, you might do something like: if myint == 4 or myint == 12: do something else: do something else -- DaveA From breamoreboy at yahoo.co.uk Fri Mar 15 23:34:34 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 15 Mar 2013 22:34:34 +0000 Subject: [Tutor] func-question_y_n.py In-Reply-To: References: Message-ID: On 15/03/2013 22:09, Christopher Emery wrote: > Hello Hugo, > > # Defines the start of a function and its options (question) > def question_y_n(question): > > #1. Ask Question from user, user enters either Yes, No or whatever > (anything that is not Yes or No) > answer = input(question) # prompts the user and assigns the answer > to var answer > > #2. If the user had entered anything but Yes then a while loop starts > and becomes True (meaning it is not a Yes) so it must be either No or > something else > while(answer != "Yes"): Why the unneeded parenthesis? What about 'yes'? > > #3. If the answer is anything but a No then the user is prompted with > statement and then the question asked again > if answer != "No": What about 'no'? > > #4. Print statement and ask question again. > print("Please enter Yes or No for your response!") > answer = input(question) > > #5. It is assumed that if the answer was not a Yes in the while loop > and it was not a No in the if statement than it is assumed the only > other choice would be a No for the else statement. > else: > answer = "No" > break > return answer > > answer = question_y_n("You want a drink of water? :") > print("Your answer to the question was ", answer) > > This code works and produces the results that I am looking for, > however I know there is a better way to do it and now you have me > thinking about this again. I just spent about 3 hours doing this > code. > > I was thinking of combining the Yes and No into one check however I > was having trouble finding resource of how to do mulitiy checks in a > statement for while. > > thinking like this: > > def question_y_n(question): > answer = input(question) > while(answer != "Yes" Or "No"): #This is wrong code while answer not in ('yes', 'no'): > print("Please enter Yes or No for your response!") > answer = input(question) > or > > # This one does not have ability to loop intill a Yes or No is given > so my gut tells me the one above is better or the one I have at this > time. > > def question_y_n(question): > answer = input(question) > if answer == "Yes" OR "No": #this didn't work either for me > break > else > print("Please enter Yes or No for your response!") > answer = input(question) > return answer > > Sorry for this layout, I myself was getting a little dizzy reading it. > > Thank you for your assistance! > > Sincerely in Christ, > Christopher -- Cheers. Mark Lawrence From hugo.yoshi at gmail.com Fri Mar 15 23:38:25 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 15 Mar 2013 22:38:25 +0000 Subject: [Tutor] __init__ doesn't seem to be running In-Reply-To: References: Message-ID: On Fri, Mar 15, 2013 at 10:25 PM, Cameron Macleod < cmacleod170 at googlemail.com> wrote: > I added the "self." to both the references to tasks and then I added the > print statement to the __init__ function and I got the dreaded NameError of > death: > > > Traceback (most recent call last): > File "C:\Python33\todo.py", line 6, in > class todo: > File "C:\Python33\todo.py", line 31, in todo > self.tasks.append(line.strip()) > NameError: name 'self' is not defined > > I must apologize. I did not notice you omitted it. In python, the "self" does *not* exist implicitly like "this" in Java or C++. In class methods, the first argument to a method is *always* the current instance, and python passes it in automatically. By convention, this is called self, but it could have any name. In other words, when you write this: main.writeTask(todoList) python actually interprets it like so: todo.writeTask(main, todoList) As you can see, the main instance object is the first argument to the method, which should be defined like this: def writeTask(self, todoList): # code here can use self.stuff To repeat, the name "self" is not special in Python, it's just that the first argument to every method called is always the current instance, and by convention this is always called "self" by programmers. You should add self to every method in a class, unless it is a @classmethod or @staticmethod, but those are relatively rare exceptions. HTH, Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From joshjwilkerson at yahoo.com Fri Mar 15 23:46:29 2013 From: joshjwilkerson at yahoo.com (Joshua Wilkerson) Date: Fri, 15 Mar 2013 15:46:29 -0700 (PDT) Subject: [Tutor] __init__ argument Message-ID: <1363387589.54002.YahooMailNeo@web121602.mail.ne1.yahoo.com> The program keeps telling me that the __init__ in Rock takes two arguments and only one is given. Ideas? The point of the game is to dodge falling rocks. Two more appear every time one reaches the bottom of the screen. # Avalanche, a dodging game # Written by Josh Wilkerson # Dodge falling rocks, two new rocks appear every time a rock hits the bottom. from livewires import games, color import random games.init(screen_width = 640, screen_height = 480, fps = 50) class Chef(games.Sprite): ? ? """ ? ? A chef controlled by the player to dodge falling rocks. ? ? """ ? ? image = games.load_image("chef.jpg") ? ? def __init__(self, y = 450): ? ? ? ? """ Initialize Chef object and create Text object for score. """ ? ? ? ? super(Chef, self).__init__(image = Chef.image, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?x = games.mouse.x, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?bottom = games.screen.height) ? ? ? ? self.score = games.Text(value = 0, size = 25, color = color.black, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? top = 5, right = games.screen.width - 10) ? ? ? ? games.screen.add(self.score) def update(self): ? ? """ Move to mouse position x. """ ? ? self.x = games.mouse.x ? ? if self.left < 0: ? ? ? ? self.left = 0 ? ? if self.right > games.screen.width: ? ? ? ? self.right = games.screen.width ? ? self.check_catch() ? ? def check_hit(self): ? ? ? ? """ Check if hit by rcok. """ ? ? ? ? for rock in self.overlapping_sprites: ? ? ? ? ? ? self.end_game() ? ? ? ? ? ? self.destroy() class Rock(games.Sprite): ? ? """ ? ? A rock which falls to the ground. ? ? """ ? ? image = games.load_image("rock.jpg") ? ? speed = 1 ? ? def __init__(self, x, y = 90): ? ? ? ? """ Initiate a rock object. """ ? ? ? ? super(Rock, self).__init__(image = Rock.image, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?x = x, y = y, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?dy = rock.speed) ? ? def update(self): ? ? ? ? """ Check if bottom edge has reached screen bottom. """ ? ? ? ? if self.bottom > games.screen.height: ? ? ? ? ? ? SPAWN = 2 ? ? ? ? ? ? Rock.SPAWN ? ? ? ? ? ?? ? ? def handle_hit(self): ? ? ? ? """ Destroy self if hits chef. """ ? ? ? ? self.destroy() ? ? def end_game(self): ? ? ? ? """ End the game. """ ? ? ? ? end_message = games.Message(value = "Game Over", ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? size = 90, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? color = color.red, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? x = games.screen.width / 2, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? y = games.screen.height / 2, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? lifetime = 5 * games.screen.fps, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? after_death = games.screen.quit) ? ? ? ? games.screen.add(end_message) class Dropper(games.Sprite): ? ? """ ? ? An invisible object that drops the rocks. ? ? """ ? ? def __init___(self, y = 55, speed = 2, odds_change = 200): ? ? ? ? """ Initialize the Dropper object. """ ? ? ? ? super(Dropper, self).__init__(x = games.screen.width / 2, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? y = y, ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? dx = speed) ? ? ? ? self.odds_change = odds_change ? ? ? ? self.time_til_drop = 0 ? ? def update(self): ? ? ? ? """ Determines if direction needs to be reversed. """ ? ? ? ? if self.left < 0 or self.right > games.screen.width: ? ? ? ? ? ? self.dx = -self.dx ? ? ? ? elif random.randrange(self.odds_change) == 0: ? ? ? ? ? ? self.dx = -self.dx ? ? ? ? self.check_drop() ? ? def check_drop(self): ? ? ? ? """ Decreases countdown or drop rock and reset countdown. """ ? ? ? ? if self.time_til_drop > 0: ? ? ? ? ? ? self.time_til_drop -= 1 ? ? ? ? else: ? ? ? ? ? ? new_rock = Rock(x = self.x) ? ? ? ? ? ? games.screen.add(new_rock) ? ? ? ? # set buffer to approx 30% of rock height, regardless of pizza speed ? ? ? ? self.time_til_drop = int(new_rock.height * 1.3 / Rock.speed) + 1 def main(): ? ? """ Play the game. """ ? ? backround_image = games.load_image("backround.jpg", transparent = False) ? ? games.screen.backround = backround_image ? ? the_chef = Chef() ? ? games.screen.add(the_chef) ? ? the_rock = Rock() ? ? games.screen.add(the_rock) ? ? the_dropper = Dropper() ? ? games.screen.add(the_dropper) ? ? games.mouse.is_visible = False ? ?? ? ? games.screen.event_grab = True ? ? gsmes.screen.mainloop() # start it up main() This is the error. Exception AttributeError: "'Rock' object has no attribute '_gone'" in > ignored Traceback (most recent call last): ? File "C:\Users\Joshua\Projects\Avalanche\Avalanche.py", line 129, in ? ? main() ? File "C:\Users\Joshua\Projects\Avalanche\Avalanche.py", line 117, in main ? ? the_rock = Rock() TypeError: __init__() takes at least 2 arguments (1 given) >>>? -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Fri Mar 15 23:52:20 2013 From: davea at davea.name (Dave Angel) Date: Fri, 15 Mar 2013 18:52:20 -0400 Subject: [Tutor] __init__ doesn't seem to be running In-Reply-To: References: Message-ID: <5143A624.2040705@davea.name> (By top-posting, you lost all the context. Next time, post your responses AFTER the part you're quoting. And don't just quote it all, only the part that's relevant.) On 03/15/2013 06:25 PM, Cameron Macleod wrote: > I added the "self." to both the references to tasks and then I added the > print statement to the __init__ function and I got the dreaded NameError of > death: > > > Traceback (most recent call last): > File "C:\Python33\todo.py", line 6, in > class todo: > File "C:\Python33\todo.py", line 31, in todo > self.tasks.append(line.strip()) > NameError: name 'self' is not defined Every one of your methods should normally start with a 'self' parameter. You have one in __init__(), but you forgot it in writeTasks(). And your indentation of the original code is trashed, with a number of lines (starting with the try statement) that are NOT in the writeTask() method. Thus they're considered part of the class definition, and are interpreted in a very different way. Please capitalize the class name, so we won't be confused by the code -- I interpreted the above stacktrace as reporting a problem in the todo() method, when it's actually in the class itself because of the above indentation bug. > > I then moved the entirety of the code that appeared outside of the > functions but within the class into the writeTask function, this produced > the longed after print statement and no errors, but was inappropriate for > the task in hand. So I re-jiggled most of it into the __init__ method and > left the call to writeTask outside of the class, passing in the argument > main.todoList . This gave me the print statement (the init is running now!) > but also this error: > > > Traceback (most recent call last): > File "C:\Python33\todo.py", line 34, in > main.writeTask(main.todoList) > AttributeError: 'todo' object has no attribute 'todoList' > > I fixed this with an attachment to self on the todoList object, but then > got this error instead. > > Traceback (most recent call last): > File "C:\Python33\todo.py", line 34, in > main = todo() > File "C:\Python33\todo.py", line 14, in __init__ > for line in todoList: > NameError: global name 'todoList' is not defined > > My code now looks something like this: > > class todo(): > def __init__(self): > self.tasks = [] > print("Hello") > try: > self.todoList = open('todo.txt', 'r+') > except IOError: > self.todoList = open('todo.txt', 'w') > for line in todoList: > self.tasks.append(line.strip()) > > > def writeTask(todoList): that needs to be def writeTask(self, todoList): > name = input("Please enter the task > ") > desc = input("Please enter a short description (optional) > ") > while True: > try: > imp = int(input("How important is this task? 1-100 > ")) > break > except TypeError: > imp = int(input("How important is this task? 1-100 > ")) > if imp > 100: > imp = 100 > elif imp < 1: > imp = 1 > todoList.write("\"" + name + "\",\"" + desc + "\",\"" + str(imp) + > "\"") > print("Task written!") > > > main = todo() > main.writeTask(main.todoList) That line is trying to access an attribute of the main object called todoList. Wouldn't it be much clearer if you just used self.todoList in this method, and NOT have such an argument. That way, the definition would be def writeTask(self): .... and the toplevel code would be: main = todo() main.writeTask() > > It's recognising todoList as global now which is better than not being > acknowledged at all, but why would it not be defined? > todoList isn't a global in any case. > (Sorry if this came up twice, wasn't sure whether or not I'd replied to all) > > Please start over with a set of code that we can see in its entirety, and report an error traceback for that particular code. As this message appears now, some errors are in the earlier code, some in code we haven't seen, and some in the new code posted here. -- DaveA From hugo.yoshi at gmail.com Fri Mar 15 23:54:34 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Fri, 15 Mar 2013 22:54:34 +0000 Subject: [Tutor] func-question_y_n.py In-Reply-To: References: Message-ID: On Fri, Mar 15, 2013 at 10:09 PM, Christopher Emery wrote: > > This code works and produces the results that I am looking for, > however I know there is a better way to do it and now you have me > thinking about this again. I just spent about 3 hours doing this > code. Yes! learning is happening :D I was thinking of combining the Yes and No into one check however I > was having trouble finding resource of how to do mulitiy checks in a > statement for while. > > thinking like this: > > def question_y_n(question): > answer = input(question) > while(answer != "Yes" Or "No"): #This is wrong code > print("Please enter Yes or No for your response!") > answer = input(question) > or > > This is an excellent thought! Nice work, this looks already much, much better and simpler than the previous version, don't you agree? The only problem of course is that you have some wrong code in it, but that's okay. The idea is correct, you just need to write it a little differently so it is valid python :) Dave already gave you the answer on how to combine multiple checks in one statement, with the "and" and "or", and Mark gave you what is called the "idiomatic" way, which is perhaps a little harder to read at first but really elegant once you get used to it. I'll put them both together down here: if a == 5 or a == 6: print("a is 5 or 6!") if a in (5, 6): print("a is 5 or 6!") The second way is a lot shorter, especially if you need to check many values. It uses the "in" operator, which allows you to check if a value is in a list (or more technically, a sequence. Any sequence like tuples, lists, strings, dictionaries, all support the "in" operator). But if you don't quite grasp it yet, the first way is fine too. NOTE: It's important not to confuse these two: # this doesn't work like you think it does if a == 1 or 0: # this is the right way if a == 1 or a == 0: the "or" and "and" operator can only connect *comparisons*, nothing else. The top if statement will be interpreted like this: if (a == 1) or (0): which basically means "execute the code below if "a equals 1" is True OR "the value 0" is True. That's not what you want, even though if you read it like it's English it sounds right (the lesson is, don't read code like it's English, because it isn't even close). You're almost to a working function that can accept any amount of possible answers, which is really nice. Keep it up! HTH, Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Fri Mar 15 23:58:11 2013 From: davea at davea.name (Dave Angel) Date: Fri, 15 Mar 2013 18:58:11 -0400 Subject: [Tutor] __init__ argument In-Reply-To: <1363387589.54002.YahooMailNeo@web121602.mail.ne1.yahoo.com> References: <1363387589.54002.YahooMailNeo@web121602.mail.ne1.yahoo.com> Message-ID: <5143A783.5050607@davea.name> On 03/15/2013 06:46 PM, Joshua Wilkerson wrote: > The program keeps telling me that the __init__ in Rock takes two arguments and only one is given. Ideas? > The point of the game is to dodge falling rocks. Two more appear every time one reaches the bottom of the screen. > > # Avalanche, a dodging game > # Written by Josh Wilkerson > # Dodge falling rocks, two new rocks appear every time a rock hits the bottom. > > from livewires import games, color > import random > > games.init(screen_width = 640, screen_height = 480, fps = 50) > > class Chef(games.Sprite): > """ > A chef controlled by the player to dodge falling rocks. > """ > image = games.load_image("chef.jpg") > > def __init__(self, y = 450): > """ Initialize Chef object and create Text object for score. """ > super(Chef, self).__init__(image = Chef.image, > x = games.mouse.x, > bottom = games.screen.height) > > self.score = games.Text(value = 0, size = 25, color = color.black, > top = 5, right = games.screen.width - 10) > games.screen.add(self.score) > This following update() is probably indented wrong. Currently it's a regular function, not a method, so having a paramter 'self' is just weird. If you want it to be part of the class, you'd better indent it to match the other defs. > def update(self): > """ Move to mouse position x. """ > self.x = games.mouse.x > > if self.left < 0: > self.left = 0 > > if self.right > games.screen.width: > self.right = games.screen.width > > self.check_catch() > > def check_hit(self): > """ Check if hit by rcok. """ > for rock in self.overlapping_sprites: > self.end_game() > self.destroy() > > class Rock(games.Sprite): > """ > A rock which falls to the ground. > """ > image = games.load_image("rock.jpg") > speed = 1 > def __init__(self, x, y = 90): This defines a method that can take either two or three arguments. The third one has a default value. > """ Initiate a rock object. """ > super(Rock, self).__init__(image = Rock.image, > x = x, y = y, > dy = rock.speed) > > def update(self): > """ Check if bottom edge has reached screen bottom. """ > if self.bottom > games.screen.height: > SPAWN = 2 > Rock.SPAWN > > > def handle_hit(self): > """ Destroy self if hits chef. """ > self.destroy() > > def end_game(self): > """ End the game. """ > end_message = games.Message(value = "Game Over", > size = 90, > color = color.red, > x = games.screen.width / 2, > y = games.screen.height / 2, > lifetime = 5 * games.screen.fps, > after_death = games.screen.quit) > games.screen.add(end_message) > > class Dropper(games.Sprite): > """ > An invisible object that drops the rocks. > """ > def __init___(self, y = 55, speed = 2, odds_change = 200): > """ Initialize the Dropper object. """ > super(Dropper, self).__init__(x = games.screen.width / 2, > y = y, > dx = speed) > self.odds_change = odds_change > self.time_til_drop = 0 > > def update(self): > """ Determines if direction needs to be reversed. """ > if self.left < 0 or self.right > games.screen.width: > self.dx = -self.dx > elif random.randrange(self.odds_change) == 0: > self.dx = -self.dx > > self.check_drop() > > def check_drop(self): > """ Decreases countdown or drop rock and reset countdown. """ > if self.time_til_drop > 0: > self.time_til_drop -= 1 > else: > new_rock = Rock(x = self.x) > games.screen.add(new_rock) > # set buffer to approx 30% of rock height, regardless of pizza speed > self.time_til_drop = int(new_rock.height * 1.3 / Rock.speed) + 1 > > def main(): > """ Play the game. """ > backround_image = games.load_image("backround.jpg", transparent = False) > games.screen.backround = backround_image > > the_chef = Chef() > games.screen.add(the_chef) > > the_rock = Rock() When creating a new instance of a class, there is an implied 'self' argument, and you supply no others. So you're missing the 'x' argument. It needs to get self & x, and you're only passing self. > games.screen.add(the_rock) > > the_dropper = Dropper() > games.screen.add(the_dropper) > > games.mouse.is_visible = False > > games.screen.event_grab = True > gsmes.screen.mainloop() > > # start it up > main() > > This is the error. > > Exception AttributeError: "'Rock' object has no attribute '_gone'" in > ignored > > Traceback (most recent call last): > File "C:\Users\Joshua\Projects\Avalanche\Avalanche.py", line 129, in > main() > File "C:\Users\Joshua\Projects\Avalanche\Avalanche.py", line 117, in main > the_rock = Rock() > TypeError: __init__() takes at least 2 arguments (1 given) >>>> >>>> -- DaveA From cpe.list at gmail.com Sat Mar 16 00:37:40 2013 From: cpe.list at gmail.com (Christopher Emery) Date: Fri, 15 Mar 2013 19:37:40 -0400 Subject: [Tutor] func-question_y_n.py In-Reply-To: References: Message-ID: Hello Hugo, Mark, Dave, First thank you all greatly, you all have given me food for thought and bytes to chew! I now would like to say please don't take offense at what I say below, however because we are all people and this IS a learning list I would like to give feedback of the last three response I gotten. For Hugo: You have explained stuff clearly to me, that allowed me to learn without making feel like I should already know xyz when I am only beginning. Thank you for this! PLEASE continue this gentle but effective way of teaching. For Dave: As much as you have given me the answers I unfortunately didn't get to learn as much from this information as it felt like I was completely wrong and that I should of know better, this in turn makes people not learn, after all this is a list for learning. I have in a post or two did state that I was very new to python or for that fact any program language. I guess I need to write this in every email I send out. For Mark: Thank you for your answer at the end of your email. If you don't mind me stating for future can you explain things a little more so I may understand the why to your statement "WHy the unneeded parenthesis? What about 'yes'?" Do you mind explaining the unneeded part? I am VERY new to learning programming in general. Sincerely in Christ, Christopher From msirenef at lightbird.net Sat Mar 16 01:30:26 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Fri, 15 Mar 2013 20:30:26 -0400 Subject: [Tutor] func-question_y_n.py In-Reply-To: References: <5143927D.1040709@lightbird.net> Message-ID: <5143BD22.3010009@lightbird.net> On 03/15/2013 05:47 PM, Christopher Emery wrote: > Hi Mitya, > > Thank for your example of code, however at this time its well over my > head and I think its best if I slowly work on a function that provided > only what I need and then add to it IF it works into it. Yours > appears to do a whole lot more then process a Yes/No from a question > and re-ask the question if the user does not provide a yes or no. > > I will save your code for future use as I understand it more (smile) Ok, sorry if it was too much.. in short, the advantage is that it can accept yes/no but you can also specify any other pattern, e.g. to accept a number or a string that's not shorter or longer than specified, or accept a blank response; it uses regular expressions to match pattern: http://docs.python.org/3.3/library/re.html -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ From breamoreboy at yahoo.co.uk Sat Mar 16 01:44:53 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 16 Mar 2013 00:44:53 +0000 Subject: [Tutor] func-question_y_n.py In-Reply-To: References: Message-ID: On 15/03/2013 23:37, Christopher Emery wrote: > Hello Hugo, Mark, Dave, > For Mark: Thank you for your answer at the end of your email. If you > don't mind me stating for future can you explain things a little more > so I may understand the why to your statement "WHy the unneeded > parenthesis? What about 'yes'?" Do you mind explaining the unneeded > part? I am VERY new to learning programming in general. > > Sincerely in Christ, > Christopher Why the unneeded parenthesis? Why bother typing something that isn't needed in Python? To me this is just clutter that further strains my aging eye sight. The following is perfectly valid Python. while answer != "Yes": Why not use it, apart from the fact that it won't match 'yes'? :) -- Cheers. Mark Lawrence From alan.gauld at btinternet.com Sat Mar 16 01:53:17 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 16 Mar 2013 00:53:17 +0000 Subject: [Tutor] Script to generate statements In-Reply-To: References: Message-ID: On 15/03/13 19:42, Charles Leviton wrote: > Given a list of DBRM members create a JCL which has a series of bind > statements for each DBRM. Ah, the joys of JCL. I haven't read a JCL script in about 15 years! :-) > This is the tack I took. I have 3 input files > a_ contains the fixed part of the JCL > b_ contains the template for the bind statement. > c_ contains the list of DBRMs Yep, that's fine. > This is the script I came up with...Would you critique it and let me > know how I could have done it better? > #create a series of bind statements > fo = open('i:/text/jclout.txt', 'w') > fi = open('i:/text/bindjclfirstpart.txt','rU') > fibindjclvar = open('i:/text/bindjclvariable.txt','rU') > filistofdbrms= open('i:/text/bindjcldbrmlist.txt','rU') > > varlines =[] You don't need this since the next line initialises the list anyway. Python rarely requires initialising to null values, you can usually initialise to the actual data directly. > varlines = fibindjclvar.readlines() > for line in fi: #write out all the lines in the first part of JCL > fo.write(line) > fo.write('\n') > varline = '' Again you don't need this since you always initialise varline below. > for dbrm in filistofdbrms: > fo.write('\n') > for index in range(0,9): > if varlines[index].find('member') > 0: > varline = varlines[index] + '('+ dbrm + ')' + ' -' > else: > varline = varlines[index] > fo.write(varline) > > fo.close() > fi.close() > fibindjclvar.close() > filistofdbrms.close() And that's all, the rest looks fine to me. PS. Note to Hugo. JCL = Job Control language. Its like a Unix shell script that specifically used to set up a programs runtime environment (how much disk, RAM, CPU it's allowed to consume, start/end times etc etc.) One of the most powerful things about a mainframe that makes them so much more robust than Unix boxes is the fine grained control offered by JCL... HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Mar 16 02:06:26 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 16 Mar 2013 01:06:26 +0000 Subject: [Tutor] func-question_y_n.py In-Reply-To: References: Message-ID: On 15/03/13 23:37, Christopher Emery wrote: > so I may understand the why to your statement " > WHy the unneeded parenthesis? Mark was pointing out that parentheses are not needed in a while statement. So why add them? They just add visual clutter. > What about 'yes'?" And here he was alluding to the fact that your code requires a capitalised 'Yes', but in practice it should be OK to enter lower case, or even all caps, input too. ie. yes Yes YES should all be valid and yES, yeS and yEs won't be too bad either. The solution is usually to convert input to all lower (or upper) before checking its value. answer = input(question).lower() Now we can test for 'yes' regardless of what combination of case the user actually typed. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at davea.name Sat Mar 16 02:37:50 2013 From: davea at davea.name (Dave Angel) Date: Fri, 15 Mar 2013 21:37:50 -0400 Subject: [Tutor] Script to generate statements In-Reply-To: References: Message-ID: <5143CCEE.7000105@davea.name> On 03/15/2013 08:53 PM, Alan Gauld wrote: > On 15/03/13 19:42, Charles Leviton wrote: > >> Given a list of DBRM members create a JCL which has a series of bind >> statements for each DBRM. > > Ah, the joys of JCL. > I haven't read a JCL script in about 15 years! :-) > Been over 40 years for me, so I may not remember it too well. > PS. > Note to Hugo. JCL = Job Control language. > Its like a Unix shell script that specifically used to set up a programs > runtime environment (how much disk, RAM, CPU it's allowed to consume, > start/end times etc etc.) One of the most powerful things about a > mainframe that makes them so much more robust than Unix boxes is the > fine grained control offered by JCL... > You even get to specify how many cylinders a file will occupy, so you don't run out of contiguous space. -- DaveA From steve at pearwood.info Sat Mar 16 03:34:28 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 16 Mar 2013 13:34:28 +1100 Subject: [Tutor] __init__ argument In-Reply-To: <1363387589.54002.YahooMailNeo@web121602.mail.ne1.yahoo.com> References: <1363387589.54002.YahooMailNeo@web121602.mail.ne1.yahoo.com> Message-ID: <5143DA34.6050503@pearwood.info> On 16/03/13 09:46, Joshua Wilkerson wrote: > The program keeps telling me that the __init__ in Rock takes two arguments and only one is given. Ideas? Yes. You need to look at the arguments required when you construct a Rock() instance, and compare it to the arguments actually given. [snip irrelevant code] > class Rock(games.Sprite): > """ > A rock which falls to the ground. > """ > image = games.load_image("rock.jpg") > speed = 1 > def __init__(self, x, y = 90): > """ Initiate a rock object. """ Here you define the constructor (to be precise: actually the *initialiser*) for a Rock. It takes three arguments, the magic "self" argument that Python automatically provides, x, and an optional y argument. So when you create a Rock instance, the method *requires* two arguments: self and x. Since Python provides the self, you *must* provide an x. So let's see what you do: > def main(): > """ Play the game. """ [...] > the_rock = Rock() You don't provide an x, and so Python complains that it expects two arguments but only receives one (the self argument that it provides for you). > Traceback (most recent call last): > File "C:\Users\Joshua\Projects\Avalanche\Avalanche.py", line 129, in > main() > File "C:\Users\Joshua\Projects\Avalanche\Avalanche.py", line 117, in main > the_rock = Rock() > TypeError: __init__() takes at least 2 arguments (1 given) Notice that the exception tells you exactly *where* the problem is, and *what* the problem is. The only thing you actually need think about about is that, being a method rather than an ordinary function, behind the scenes Python slips in a "self" argument, thus the "1 given" part. -- Steven From steve at pearwood.info Sat Mar 16 04:25:29 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 16 Mar 2013 14:25:29 +1100 Subject: [Tutor] Script to generate statements In-Reply-To: References: Message-ID: <5143E629.8090702@pearwood.info> On 16/03/13 06:42, Charles Leviton wrote: > This is the script I came up with...Would you critique it and let me know > how I could have done it better? > > #create a series of bind statements > fo = open('i:/text/jclout.txt', 'w') > fi = open('i:/text/bindjclfirstpart.txt','rU') > fibindjclvar = open('i:/text/bindjclvariable.txt','rU') > filistofdbrms= open('i:/text/bindjcldbrmlist.txt','rU') The comment appears to be irrelevant and/or misleading, although maybe that is just because I don't understand your terminology. You say you create a "series of bind statements", but you don't seem to do anything of the sort. You actually open four files instead. > varlines =[] > varlines = fibindjclvar.readlines() You don't need to pre-initialise a variable to an empty list before reading lines. > for line in fi: #write out all the lines in the first part of JCL > fo.write(line) > fo.write('\n') > varline = '' The above variable name is not helpful. "varline" -- what does it represent? It's very similar to "varlines" defined above, so much so that the first time I read it I thought you had overridden the same variable. Can you think of a more descriptive name for this? Also, again, there's no need to pre-initialise it. > for dbrm in filistofdbrms: > fo.write('\n') > for index in range(0,9): Is this correct? You only care about the first nine lines of the fibindjclvar file? What if it has fewer than nine lines? What if it has more? By the way, it is normal to write that as range(9) rather than range(0, 9). > if varlines[index].find('member') > 0: > varline = varlines[index] + '('+ dbrm + ')' + ' -' > else: > varline = varlines[index] > fo.write(varline) Since you never use the index except as a way of extracting a line from varlines, perhaps this snippet will be better: for dbrm in filistofdbrms: fo.write('\n') for line in varlines[:9]: # Process only the first 9 lines. if line.find('member') > 0: line += '('+ dbrm + ')' + ' -' fo.write(line) > fo.close() > fi.close() > fibindjclvar.close() > filistofdbrms.close() This bit is fine :-) -- Steven From vincentbalmori at yahoo.com Sat Mar 16 05:08:48 2013 From: vincentbalmori at yahoo.com (Vincent Balmori) Date: Fri, 15 Mar 2013 21:08:48 -0700 (PDT) Subject: [Tutor] Loop Exception Handles Message-ID: <1363406928.65180.YahooMailNeo@web164905.mail.bf1.yahoo.com> I am trying to loop a simple exception. I tried to put a while loop, but I keep getting syntax issues. I also tried to alternatively use?something?on the lines of "while number != int" also with no avail. ?? def main(): ? ? print("\t\tWelcome to Blackjack!\n") ? ?? ? ? names = [] ? ? try: ? ? ? ? number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8) ? ? except (ValueError, TypeError): ? ? ? ? print("That is not a number!") ? ? ? ? number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8) ? ? ? ? continue ? ? for i in range(number): ? ? ? ? name = input("Enter player name: ") ? ? ? ? names.append(name) ? ? print() -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Sat Mar 16 05:16:14 2013 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Sat, 16 Mar 2013 05:16:14 +0100 Subject: [Tutor] Loop Exception Handles In-Reply-To: <1363406928.65180.YahooMailNeo@web164905.mail.bf1.yahoo.com> References: <1363406928.65180.YahooMailNeo@web164905.mail.bf1.yahoo.com> Message-ID: On 16 March 2013 05:08, Vincent Balmori wrote: > I am trying to loop a simple exception. I tried to put a while loop, but I > keep getting syntax issues. I also tried to alternatively use something on > the lines of "while number != int" also with no avail. It would help if you: a) didn't send HTML emails b) actually gave us the error message, as it says a lot about your error other than "syntax error". [snipped code] Since we can't see your games class, nor your error message, we can't really help you. -- best regards, Robert S. From breamoreboy at yahoo.co.uk Sat Mar 16 05:36:24 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 16 Mar 2013 04:36:24 +0000 Subject: [Tutor] Loop Exception Handles In-Reply-To: <1363406928.65180.YahooMailNeo@web164905.mail.bf1.yahoo.com> References: <1363406928.65180.YahooMailNeo@web164905.mail.bf1.yahoo.com> Message-ID: On 16/03/2013 04:08, Vincent Balmori wrote: > I am trying to loop a simple exception. I tried to put a while loop, but > I keep getting syntax issues. I also tried to alternatively use > something on the lines of "while number != int" also with no avail. Please help us to help you. What did your while loop look like and what were the syntax issues? Tell us precisely what your alternative was and what went wrong, syntax error, value error, power cut, atom bomb dropped? > > def main(): > print("\t\tWelcome to Blackjack!\n") > names = [] > try: > number = games.ask_number("How many players? (1 - 7): ", low = > 1, high = 8) > except (ValueError, TypeError): > print("That is not a number!") > number = games.ask_number("How many players? (1 - 7): ", low = > 1, high = 8) > continue This must be a syntax error as continue is only valid in a loop of some kind. Try (awful I know) something like number = 0 while not number: try: number = games.ask_number("How many players? (1 - 7): ", low = 1, high = 8) except (ValueError, TypeError): print("That is not a number!") > for i in range(number): > name = input("Enter player name: ") > names.append(name) > print() > > Assuming that you get your while loop to work correctly, how many times will the for loop above run if you enter 1? -- Cheers. Mark Lawrence From __peter__ at web.de Sat Mar 16 11:05:41 2013 From: __peter__ at web.de (Peter Otten) Date: Sat, 16 Mar 2013 11:05:41 +0100 Subject: [Tutor] Script to generate statements References: Message-ID: Charles Leviton wrote: > I was recently given this task. it's a very IBM mainframe specific task > so > I'm not sure how to find equivalent terms in another environment. I will > just use the mainframe terminology and hopefully y'all can figure out what > I mean. > > Given a list of DBRM members create a JCL which has a series of bind > statements for each DBRM. > > This is the tack I took. I have 3 input files > a_ contains the fixed part of the JCL > b_ contains the template for the bind statement. > c_ contains the list of DBRMs > > > This is the script I came up with...Would you critique it and let me know > how I could have done it better? Incremental changes that have not been mentioned: You can use with open(...) as fo: ... instead of fo = open(...) ... fo.close() > #create a series of bind statements > fo = open('i:/text/jclout.txt', 'w') > fi = open('i:/text/bindjclfirstpart.txt','rU') > fibindjclvar = open('i:/text/bindjclvariable.txt','rU') > filistofdbrms= open('i:/text/bindjcldbrmlist.txt','rU') > > varlines =[] > varlines = fibindjclvar.readlines() > for line in fi: #write out all the lines in the first part of JCL > fo.write(line) > fo.write('\n') > varline = '' > for dbrm in filistofdbrms: dbrm will have a trailing newline that you probably need to strip: dbrm = dbrm.strip() > fo.write('\n') > for index in range(0,9): > if varlines[index].find('member') > 0: find() is case-sensitive; you probably need find("MEMBER"). Also, find() returns -1 when the token is not in the line. Because of the leeading spaces in > MEMBER it doesn't matter here, but you should make it a habit to test some_string.find(token) >= 0 or use the less errorprone variant token in some_string > varline = varlines[index] + '('+ dbrm + ')' + ' -' > else: > varline = varlines[index] > fo.write(varline) > > fo.close() > fi.close() > fibindjclvar.close() > filistofdbrms.close() > > The "variable" part of the bind statement is where I have to include the > DBRM name. I look for the word 'member' in the template. > Template looks like this (content of bindjclvariable.txt) > BIND PACKAGE(PROD) - > MEMBER > OWNER(PRODOWNR) - > QUALIFIER(PRODTBLS) - > ISOLATION(CS) - > EXPLAIN(YES) - > ACTION(REPLACE) - > CURRENTDATA(YES) - > VALIDATE(BIND) > > Thanks! Finally, throwing in some guesswork as I don't know JCL, here's how I would attack your problem: Given $ cat bindjcldbrmlist.txt alpha beta $ cat bindjclfirstpart.txt fixed header $ cat bindjclvariable.txt BIND PACKAGE(PROD) - MEMBER({0}) - OWNER(PRODOWNR) - QUALIFIER(PRODTBLS) - ISOLATION(CS) - EXPLAIN(YES) - ACTION(REPLACE) - CURRENTDATA(YES) - VALIDATE(BIND) $ the script $ cat generate.py with open('jclout.txt', 'w') as fo: with open('bindjclfirstpart.txt','rU') as header: fo.writelines(header) with open('bindjclvariable.txt','rU') as fibindjclvar: template = fibindjclvar.read() with open('bindjcldbrmlist.txt','rU') as dbrms: for dbrm in dbrms: dbrm = dbrm.strip() fo.write(template.format(dbrm)) produces the following output: $ cat jclout.txt fixed header BIND PACKAGE(PROD) - MEMBER(alpha) - OWNER(PRODOWNR) - QUALIFIER(PRODTBLS) - ISOLATION(CS) - EXPLAIN(YES) - ACTION(REPLACE) - CURRENTDATA(YES) - VALIDATE(BIND) BIND PACKAGE(PROD) - MEMBER(beta) - OWNER(PRODOWNR) - QUALIFIER(PRODTBLS) - ISOLATION(CS) - EXPLAIN(YES) - ACTION(REPLACE) - CURRENTDATA(YES) - VALIDATE(BIND) $ From __peter__ at web.de Sat Mar 16 11:19:05 2013 From: __peter__ at web.de (Peter Otten) Date: Sat, 16 Mar 2013 11:19:05 +0100 Subject: [Tutor] File-Fetcher (cmdline-parser) References: Message-ID: Christopher Emery wrote: > Hello Peter, > > Thank you this is much appreciated! It is much clear now. Thank you > > PO: Also, if you make it a habit to keep long option and dest in sync > (something you get for free if you only specify the option) you can > deduce the attribute name used in the script from its commandline > interface. > CE: Can you please explain this deeper please? I am not sure if I am > getting it. Suppose a have a script doit.py that accepts a flag -f. You have not used it for a while, then you try it again and decide you want to make a modification related to the -f option or fix some cornercase where it doesn't work as you expect. If the script was written by me you can run ./doit -h to find out that the long name for -f is --enable-foo, open the sript with an editor and search for the string args.enable_foo to find the entry point to the code related to the -f/--enable-foo option. It's no big deal, but I find it convenient. From kendy at kendy.org Sat Mar 16 20:04:42 2013 From: kendy at kendy.org (kendy at kendy.org) Date: Sat, 16 Mar 2013 12:04:42 PDT Subject: [Tutor] Fixing Globals Message-ID: <58823.1363460682@speakeasy.net> Dear Tutor Global constants and variables are bad. But what's better? I've heard some suggestions, but haven't seen much actual code showing how to improve globals. I don't like: * Passing a lot of individual arguments. * Creating a structure with unrelated elements. * Passing a structure, as an argument, through a function that uses only one (or none of the) elements in the structure. I created an example (below), that could be written with global constants and variables. How would you suggest handling something like this? (I don't need you to stick to my example.) #!/usr/bin/python START = '<' END = '>' def getargs(): getops() if in_filename_1 = in_filename_2 = out_filename_1 = out_filename_2 = flag1 = verbose = def this(): open_for_read() stuff() def open_for_read(filename): in_filehandle = open( return in_filehandle def stuff(): if c == START or c == END: foo_the_bar = def that(): things() write_status(out_filename_1) def things(): bar_the_foo = foo_the_bar if verbose: print(flag1) def write_status(out_filename_1): getargs() this() that() I very much appreciate the help that you have given me! Thanks Ken From kwpolska at gmail.com Sat Mar 16 20:11:19 2013 From: kwpolska at gmail.com (Kwpolska) Date: Sat, 16 Mar 2013 20:11:19 +0100 Subject: [Tutor] Fixing Globals In-Reply-To: <58823.1363460682@speakeasy.net> References: <58823.1363460682@speakeasy.net> Message-ID: On Sat, Mar 16, 2013 at 8:04 PM, wrote: > Dear Tutor > > Global constants and variables are bad. But what's better? I've heard some > suggestions, but haven't seen much actual code showing how to improve globals. I > don't like: > > * Passing a lot of individual arguments. > * Creating a structure with unrelated elements. > * Passing a structure, as an argument, through a function that uses only one (or > none of the) elements in the structure. > > I created an example (below), that could be written with global constants and > variables. How would you suggest handling something like this? (I don't need you > to stick to my example.) > > #!/usr/bin/python > > START = '<' > END = '>' > [snip] > def stuff(): > if c == START or c == END: > foo_the_bar = Ugh, you don?t need variables for this. You should do: if c == '<' or c == '>' Or, even more Pythonically: if c in '<>' Now, for other cases, I suggest OOP and class member values or stuff like that. -- Kwpolska | GPG KEY: 5EAAEA16 stop html mail | always bottom-post http://asciiribbon.org | http://caliburn.nl/topposting.html From davea at davea.name Sat Mar 16 20:52:07 2013 From: davea at davea.name (Dave Angel) Date: Sat, 16 Mar 2013 15:52:07 -0400 Subject: [Tutor] Fixing Globals In-Reply-To: <58823.1363460682@speakeasy.net> References: <58823.1363460682@speakeasy.net> Message-ID: <5144CD67.1070301@davea.name> On 03/16/2013 03:04 PM, kendy at kendy.org wrote: > Dear Tutor > > Global constants and variables are bad. First, let me define my own "rule." Global constants should be all uppercase, and global variables should be avoided. Trivial and buggy scripts may ignore both rules. A trivial script is typically anything under 30 lines. Buggy scripts are those which you delete as soon as you ran them once. So what's a global constant? It's something that's set once, soon after the script starts, and *usually* not changed later in the run. For example, cmdline arguments and things directly derived from them. Special numbers (such as math.pi which is global in that module, and should have been capitalized). OS-specific details. > But what's better? I've heard some > suggestions, but haven't seen much actual code showing how to improve globals. I > don't like: > > * Passing a lot of individual arguments. I don't know how many you consider 'a lot.' Consider factoring the function into simpler components. > * Creating a structure with unrelated elements. Presumably you mean a class instance with unrelated attributes. And yes, certainly if you're creating a singleton class just as a holder for a pile of globals, then you might as well use the globals() collection in a given module. rather than writing your own. On the other hand, things that are unrelated in one context may very well be related in another. Smart dividing up of the problem is one of the things that helps makes code readable and reusable. > * Passing a structure, as an argument, through a function that uses only one (or > none of the) elements in the structure. Here, I have to disagree entirely. If the class is intelligently designed, the instance is holding a bunch of interconnected data. If the function needs one thing from it, no harm done passing the whole instance. An example is a gui 'listbox' instance. It has lots of data that the gui will use in painting it, positioning it, and generating events about it. But an individual portion of the code may be only interested in the selected item in the list, not in the title, nor the horizontal size, nor ... > > I created an example (below), that could be written with global constants and > variables. How would you suggest handling something like this? (I don't need you > to stick to my example.) > > #!/usr/bin/python > > START = '<' > END = '>' > > def getargs(): > getops() > if > in_filename_1 = > in_filename_2 = > out_filename_1 = > out_filename_2 = > flag1 = > verbose = Take a look at the modules in the standard library that do this sort of thing. They return an object which contains all the parsed parameters. > > def this(): > open_for_read() > stuff() And if you decide to open two files instead of one, and process them both in a similar way? Suddenly you'll need to pass a filename into this function. Why not start that way, so the function is readable? > > def open_for_read(filename): > in_filehandle = open( > return in_filehandle Looks good. > > def stuff(): def stuff(c, foo): """ interpret the character c and set the flag that will control how the rest of the program works """ > if c == START or c == END: > foo_the_bar = if c in START+END: foo.BAR = > > def that(): > things() > write_status(out_filename_1) Why are these in one function, if they're unrelated? The rest of the examples were too abstracted to be able to comment on. > > def things(): > bar_the_foo = foo_the_bar > if verbose: > print(flag1) > > def write_status(out_filename_1): > > getargs() > this() > that() > > > I very much appreciate the help that you have given me! > > Thanks > Ken > When you start writing code that's big enough to have reusable pieces, you'll begin to appreciate how writing parameterized code makes it more reusable. And when you try to debug stuff where a change in one function's use of a global breaks another function far away, you'll start to appreciate how it's handy to have each function have a (somewhat) reduced space it can damage, or be damaged by. My biggest disasters were "trivial" programs that grew beyond their original scope, and I never changed the mindset in rewriting them. I had once such program recently which had many authors and was a real mess. (Besides, it was written in perl, which it makes it much easier to write unmaintainable hacks) I wanted to make a substantial change and wound up writing a new program that invoked the first. That first couldn't walk on my globals once it was in a separate process. -- DaveA From msirenef at lightbird.net Sat Mar 16 21:01:53 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Sat, 16 Mar 2013 16:01:53 -0400 Subject: [Tutor] Fixing Globals In-Reply-To: <58823.1363460682@speakeasy.net> References: <58823.1363460682@speakeasy.net> Message-ID: <5144CFB1.1060001@lightbird.net> On 03/16/2013 03:04 PM, kendy at kendy.org wrote: > START = '<' > END = '>' > > def getargs(): > getops() > if > in_filename_1 = > in_filename_2 = > out_filename_1 = > out_filename_2 = > flag1 = > verbose = > > def this(): > open_for_read() > stuff() > > def open_for_read(filename): > in_filehandle = open( > return in_filehandle > > def stuff(): > if c == START or c == END: > foo_the_bar = > > def that(): > things() > write_status(out_filename_1) > > def things(): > bar_the_foo = foo_the_bar > if verbose: > print(flag1) > > def write_status(out_filename_1): > > getargs() > this() > that() Create a class or a few, instantiate them and all of your data will be instance properties. -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Each religion, by the help of more or less myth, which it takes more or less seriously, proposes some method of fortifying the human soul and enabling it to make its peace with its destiny. George Santayana From kendy at kendy.org Sat Mar 16 21:17:22 2013 From: kendy at kendy.org (kendy at kendy.org) Date: Sat, 16 Mar 2013 13:17:22 PDT Subject: [Tutor] Fixing Globals Message-ID: <59955.1363465042@speakeasy.net> Wow! Quick response. I'll study the responses. THANK YOU! Ken From abhishek.vit at gmail.com Sat Mar 16 22:14:30 2013 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Sat, 16 Mar 2013 14:14:30 -0700 Subject: [Tutor] help with itertools.izip_longest Message-ID: Hey Guys I am trying to use itertools.izip_longest to read a large file in chunks based on the examples I was able to find on the web. However I am not able to understand the behaviour of the following python code. (contrived form of example) for x in itertools.izip_longest(*[iter([1,2,3])]*2): print x ###output: (1, 2) (3, None) It gives me the right answer but I am not sure how it is doing it. I also referred to the itertools doc but could not comprehend much. In essence I am trying to understand the intracacies of the following documentation from the itertools package. "The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using izip(*[iter(s)]*n)." How is *n able to group the data and the meaning of '*' in the beginning just after izip. Thanks! -Abhi From oscar.j.benjamin at gmail.com Sat Mar 16 22:32:54 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Sat, 16 Mar 2013 21:32:54 +0000 Subject: [Tutor] help with itertools.izip_longest In-Reply-To: References: Message-ID: On 16 March 2013 21:14, Abhishek Pratap wrote: > Hey Guys > > I am trying to use itertools.izip_longest to read a large file in > chunks based on the examples I was able to find on the web. However I > am not able to understand the behaviour of the following python code. > (contrived form of example) > > for x in itertools.izip_longest(*[iter([1,2,3])]*2): > print x > > > ###output: > (1, 2) > (3, None) > > > It gives me the right answer but I am not sure how it is doing it. I > also referred to the itertools doc but could not comprehend much. In > essence I am trying to understand the intracacies of the following > documentation from the itertools package. > > "The left-to-right evaluation order of the iterables is guaranteed. > This makes possible an idiom for clustering a data series into > n-length groups using izip(*[iter(s)]*n)." > > How is *n able to group the data and the meaning of '*' in the > beginning just after izip. The '*n' part is to multiply the list so that it repeats. This works for most sequence types in Python: >>> a = [1,2,3] >>> a * 2 [1, 2, 3, 1, 2, 3] In this particular case we multiply a list containing only one item, the iterator over s. This means that the new list contains the same element twice: >>> it = iter(a) >>> [it] [] >>> [it] * 2 [, ] So if every element of the list is the same iterator, then we can call next() on any of them to get the same values in the same order: >>> d = [it]*2 >>> d [, ] >>> next(d[1]) 1 >>> next(d[0]) 2 >>> next(d[0]) 3 >>> next(d[0]) Traceback (most recent call last): File "", line 1, in StopIteration >>> next(d[1]) Traceback (most recent call last): File "", line 1, in StopIteration The * just after izip is for argument unpacking. This allows you to call a function with arguments unpacked from a list: >>> def f(x, y): ... print('x is %s' % x) ... print('y is %s' % y) ... >>> f(1, 2) x is 1 y is 2 >>> args = [1,2] >>> f(args) Traceback (most recent call last): File "", line 1, in TypeError: f() takes exactly 2 arguments (1 given) >>> f(*args) x is 1 y is 2 So the original expression, izip(*[iter(s)]*2), is another way of writing it = iter(s) izip(it, it) And izip(*[iter(s)]*10) is equivalent to izip(it, it, it, it, it, it, it, it, it, it) Obviously writing it out like this will get a bit unwieldy if we want to do izip(*[iter(s)]*100) so the preferred method is izip(*[iter(s)]*n) which also allows us to choose what value to give for n without changing anything else in the code. Oscar From abhishek.vit at gmail.com Sat Mar 16 22:45:03 2013 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Sat, 16 Mar 2013 14:45:03 -0700 Subject: [Tutor] help with itertools.izip_longest In-Reply-To: References: Message-ID: On Sat, Mar 16, 2013 at 2:32 PM, Oscar Benjamin wrote: > On 16 March 2013 21:14, Abhishek Pratap wrote: >> Hey Guys >> >> I am trying to use itertools.izip_longest to read a large file in >> chunks based on the examples I was able to find on the web. However I >> am not able to understand the behaviour of the following python code. >> (contrived form of example) >> >> for x in itertools.izip_longest(*[iter([1,2,3])]*2): >> print x >> >> >> ###output: >> (1, 2) >> (3, None) >> >> >> It gives me the right answer but I am not sure how it is doing it. I >> also referred to the itertools doc but could not comprehend much. In >> essence I am trying to understand the intracacies of the following >> documentation from the itertools package. >> >> "The left-to-right evaluation order of the iterables is guaranteed. >> This makes possible an idiom for clustering a data series into >> n-length groups using izip(*[iter(s)]*n)." >> >> How is *n able to group the data and the meaning of '*' in the >> beginning just after izip. > > The '*n' part is to multiply the list so that it repeats. This works > for most sequence types in Python: > >>>> a = [1,2,3] >>>> a * 2 > [1, 2, 3, 1, 2, 3] > > In this particular case we multiply a list containing only one item, > the iterator over s. This means that the new list contains the same > element twice: >>>> it = iter(a) >>>> [it] > [] >>>> [it] * 2 > [, ] > > So if every element of the list is the same iterator, then we can call > next() on any of them to get the same values in the same order: >>>> d = [it]*2 >>>> d > [, ] >>>> next(d[1]) > 1 >>>> next(d[0]) > 2 >>>> next(d[0]) > 3 >>>> next(d[0]) > Traceback (most recent call last): > File "", line 1, in > StopIteration >>>> next(d[1]) > Traceback (most recent call last): > File "", line 1, in > StopIteration > > The * just after izip is for argument unpacking. This allows you to > call a function with arguments unpacked from a list: > >>>> def f(x, y): > ... print('x is %s' % x) > ... print('y is %s' % y) > ... >>>> f(1, 2) > x is 1 > y is 2 >>>> args = [1,2] >>>> f(args) > Traceback (most recent call last): > File "", line 1, in > TypeError: f() takes exactly 2 arguments (1 given) >>>> f(*args) > x is 1 > y is 2 > > So the original expression, izip(*[iter(s)]*2), is another way of writing > > it = iter(s) > izip(it, it) > > And izip(*[iter(s)]*10) is equivalent to > > izip(it, it, it, it, it, it, it, it, it, it) > > Obviously writing it out like this will get a bit unwieldy if we want > to do izip(*[iter(s)]*100) so the preferred method is > izip(*[iter(s)]*n) which also allows us to choose what value to give > for n without changing anything else in the code. > > > Oscar Thanks a bunch Oscar. This is why I love this community. It is absolutely clear now. It is funny I am getting the solution over the mailing list while I am at pycon :) best, -Abhi From __peter__ at web.de Sat Mar 16 22:53:12 2013 From: __peter__ at web.de (Peter Otten) Date: Sat, 16 Mar 2013 22:53:12 +0100 Subject: [Tutor] help with itertools.izip_longest References: Message-ID: Abhishek Pratap wrote: > I am trying to use itertools.izip_longest to read a large file in > chunks based on the examples I was able to find on the web. However I > am not able to understand the behaviour of the following python code. > (contrived form of example) > > > > for x in itertools.izip_longest(*[iter([1,2,3])]*2): > print x > > > ###output: > (1, 2) > (3, None) > > > It gives me the right answer but I am not sure how it is doing it. I > also referred to the itertools doc but could not comprehend much. In > essence I am trying to understand the intracacies of the following > documentation from the itertools package. > > "The left-to-right evaluation order of the iterables is guaranteed. > This makes possible an idiom for clustering a data series into > n-length groups using izip(*[iter(s)]*n)." > > How is *n able to group the data and the meaning of '*' in the > beginning just after izip. Break the expression into smaller chunks: items = [1, 2, 3] it = iter(items) args = [it] * 2 # same as [it, it] chunks = itertools.izip_longest(*args) # same as izip_longest(it, it) As a consequence of passing the same iterator twice getting the first item from the "first" iterator will advance the "second" iterator (which is actually the same as the first iterator) to the second item which will in turn advance the "first" iterator to the third item. Try to understand the implementation given for izip() at http://docs.python.org/2/library/itertools.html#itertools.izip before you proceed to izip_longest(). From abhishek.vit at gmail.com Sat Mar 16 23:03:09 2013 From: abhishek.vit at gmail.com (Abhishek Pratap) Date: Sat, 16 Mar 2013 15:03:09 -0700 Subject: [Tutor] help with itertools.izip_longest In-Reply-To: References: Message-ID: On Sat, Mar 16, 2013 at 2:53 PM, Peter Otten <__peter__ at web.de> wrote: > Abhishek Pratap wrote: > >> I am trying to use itertools.izip_longest to read a large file in >> chunks based on the examples I was able to find on the web. However I >> am not able to understand the behaviour of the following python code. >> (contrived form of example) >> >> >> >> for x in itertools.izip_longest(*[iter([1,2,3])]*2): >> print x >> >> >> ###output: >> (1, 2) >> (3, None) >> >> >> It gives me the right answer but I am not sure how it is doing it. I >> also referred to the itertools doc but could not comprehend much. In >> essence I am trying to understand the intracacies of the following >> documentation from the itertools package. >> >> "The left-to-right evaluation order of the iterables is guaranteed. >> This makes possible an idiom for clustering a data series into >> n-length groups using izip(*[iter(s)]*n)." >> >> How is *n able to group the data and the meaning of '*' in the >> beginning just after izip. > > Break the expression into smaller chunks: > > items = [1, 2, 3] > it = iter(items) > args = [it] * 2 # same as [it, it] > chunks = itertools.izip_longest(*args) # same as izip_longest(it, it) > > As a consequence of passing the same iterator twice getting the first item > from the "first" iterator will advance the "second" iterator (which is > actually the same as the first iterator) to the second item which will in > turn advance the "first" iterator to the third item. Try to understand the > implementation given for izip() at > Thanks Peter. I guess I missed the trick on how each iterator will be moved ahead automatically as the are basically same, replicated N times. -Abhi > http://docs.python.org/2/library/itertools.html#itertools.izip > > before you proceed to izip_longest(). > > _______________________________________________ > 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 Mar 17 00:07:31 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 16 Mar 2013 23:07:31 +0000 Subject: [Tutor] Fixing Globals In-Reply-To: <58823.1363460682@speakeasy.net> References: <58823.1363460682@speakeasy.net> Message-ID: On 16/03/13 19:04, kendy at kendy.org wrote: > Global constants and variables are bad. Really? Do you know why? If you understand why then the measures to avoid them become more palatable - the lesser of 2 evils. Read-only globals are much less of a problem than read/write ones. And in Python we limit the damage by restricting globals to a single module's scope. class variables do a similar job in OOP. > * Passing a lot of individual arguments. What's a lot? 30 or 40 is too many (and I've seen it done!). But usually those 30 or 40 can be factored down to a few groups which can be put in records(objects or dictionaries etc). Less than 10 is probably OK. If you find yourself looking at lots of globals then you need to step back and look at the overall structure of the code - the coupling between your functions and the data model. There is a school of thought that says you should design your data structures first and make the functions follow the structure of the data. That approach eliminates many of the problems people have with globals which are often caused by adding them ad-hoc as they are 'discovered' during coding. > * Creating a structure with unrelated elements. That's usually a bad idea but not necessarily terrible especially if it's a dictionary or object or similar 'named attribute' packaging tool. > * Passing a structure, as an argument, through a function that uses only one (or > none of the) elements in the structure. That may be OK too, provided the functions below that one use the elements. There is a natural dependency tree there so passing in the package of required data into the top level is not necessarily bad if it preserves the cohesion of the function group. If that is the case the group of functions probably belong in a class and the data can either be instance or class attributes. > I created an example (below), that could be written with global constants and > variables. How would you suggest handling something like this? > #!/usr/bin/python > > START = '<' > END = '>' Well these appear to be the only explicit globals and as read only contstants they are OKish. They could also be moved into a separate module which you import. > def getargs(): > getops() This is a good example why globals are bad. What does getops do? What has changed as a result of calling it? It doesn't return anything so all impact on the program is invisible and unpredictable. ops = getops() # ops could be a dictionary populated by getops is more manageable and allows for multiple instances to exist > if > in_filename_1 = > in_filename_2 = > out_filename_1 = > out_filename_2 = > flag1 = > verbose = Not sure what the 'if' is doing, I assume you imply that the assignments are all from global values? If so its better to pass the filenames in or read them from a config file or somesuch. Makes the code more flexible and reusable. Or they could all be in the ops dictionary we created above? > def this(): > open_for_read() > stuff() again by relying on a global side-effect in open... you limit this function to only being used with one file. And if used in any other program you need to ensure you create a global in it that has the exact same name - and hope nobody else already used it... > def open_for_read(filename): > in_filehandle = open( > return in_filehandle This is much better but notice above you don't pass the filename in and you don't assign the returned filehandle... > def stuff(): > if c == START or c == END: > foo_the_bar = Potentially OK but you don't pass anything back. That implies foo... is changing global values, again bad for all the usual reasons. Better to capture the changes and pass them back. Or at least give an indication if the changes worked! > def that(): > things() > write_status(out_filename_1) same as above. If the file were part of an object the status would be part of that same object and we could access it that way. You don't mention OOP but OOP is one of the biggest and best tools we have in removing globals. Nothing new to add for the other code samples. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cpe.list at gmail.com Sun Mar 17 01:22:35 2013 From: cpe.list at gmail.com (Christopher Emery) Date: Sat, 16 Mar 2013 20:22:35 -0400 Subject: [Tutor] func-question_y_n.py In-Reply-To: References: Message-ID: Hello Alan and Mark, Thank you, I didn't realize that it was not needed, I had seen some other code on the net that showed it with, however its like the if or for statement they don't need () thank you. Thanks Alan for your tip, once I had my code working in the best way I was going to add the .lower() I had seen it used in another person post and figured that would assist me in getting a mixed of typed word of yes/YES/... Thanks again it is appreciated! On Fri, Mar 15, 2013 at 9:06 PM, Alan Gauld wrote: > On 15/03/13 23:37, Christopher Emery wrote: >> >> so I may understand the why to your statement " > > >> WHy the unneeded parenthesis? > > Mark was pointing out that parentheses are not needed in a while statement. > So why add them? They just add visual clutter. > >> What about 'yes'?" > > > And here he was alluding to the fact that your code requires a capitalised > 'Yes', but in practice it should be OK to enter > lower case, or even all caps, input too. > > ie. > yes > Yes > YES > > should all be valid > > and yES, yeS and yEs won't be too bad either. > > The solution is usually to convert input to all > lower (or upper) before checking its value. > > answer = input(question).lower() > > Now we can test for 'yes' regardless of what combination > of case the user actually typed. > > HTH, > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ From cpe.list at gmail.com Sun Mar 17 03:03:14 2013 From: cpe.list at gmail.com (Christopher Emery) Date: Sat, 16 Mar 2013 22:03:14 -0400 Subject: [Tutor] func-question_y_n.py In-Reply-To: References: Message-ID: Hello All, OS = Raspbain Wheezy & Ubuntu 12.10 (both updated daily) Python Version = 3.2 & 3.3 Python Understanding = Beginner (very basic - just started) Code does not give any errors. Okay here is my code for func-question_P_N() it has three args to pass though the function "question", "Positive" (Yes, True, etc) and last "Negative" (No, False, etc) 1. Take question from argument and present to user 2. Get user response to question and check if match argument to see if P or N if True then exist function. 3. If False go back to step 1. ask question again as user didn't enter either the P or N ### Start of Code ### def question_P_N(question, p, n): p = p.upper() n = n.upper() answer = input(question).upper() while answer not in (p, n): print("Your response was", answer + "!", "Please enter", p, "or", n, "for your response!") answer = input(question).upper() return answer answer = question_P_N("You want a drink of water? :", 'YES', 'no') print("Your answer to the question was ", answer) ### End of Code ### Any improvements I should consider and why? I didn't realize that even for the most basic function of a program can be a learning experience. Notice I added another part to this program because I realize what if the arguments was enter as lower case or mix case then it would try and match the users response that was convert to upper case to the argument of the program designer (func-question_P_N("Is 1 + 1 = 3? ", 'yEs', 'nO') this would never work without adding a converter to the var of p and n before matching to the upper case string Thank ahead of time for any advise! Sincerely in Christ, Christopher From alan.gauld at btinternet.com Sun Mar 17 17:29:15 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Mar 2013 16:29:15 +0000 Subject: [Tutor] func-question_y_n.py In-Reply-To: References: Message-ID: On 17/03/13 02:03, Christopher Emery wrote: > ### Start of Code ### > def question_P_N(question, p, n): > p = p.upper() > n = n.upper() > answer = input(question).upper() > while answer not in (p, n): > print("Your response was", answer + "!", "Please enter", p, > "or", n, "for your response!") > answer = input(question).upper() > return answer Looks reasonable to me. You could use string formatting instead of the addition/concatenation in the print line but otherwise it's OK. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cpe.list at gmail.com Sun Mar 17 18:40:44 2013 From: cpe.list at gmail.com (Christopher Emery) Date: Sun, 17 Mar 2013 13:40:44 -0400 Subject: [Tutor] func-question_y_n.py In-Reply-To: References: Message-ID: Hello Alan, Thank you for your response! Could you point me to a really good and easy to under about string formatting? I am what I would say in programming a baby still on milk. (smile) Sincerely in Christ, Christopher > On 17/03/13 02:03, Christopher Emery wrote: > > Looks reasonable to me. > You could use string formatting instead of the addition/concatenation in the > print line but otherwise it's OK. From charles.leviton at gmail.com Sun Mar 17 19:24:29 2013 From: charles.leviton at gmail.com (Charles Leviton) Date: Sun, 17 Mar 2013 14:24:29 -0400 Subject: [Tutor] Script to generate statements In-Reply-To: References: Message-ID: Hi thanks for the response On Fri, Mar 15, 2013 at 5:43 PM, Hugo Arts wrote: > On Fri, Mar 15, 2013 at 9:03 PM, Hugo Arts wrote: > >> >> I have a few comments >> >> * Does the script work? If yes, I'd say it's probably fine. Pretty short >> so easy to understand whatever you do, and I see no obviously crazy broken >> s**t in there. I don't much like 'fi' and 'fo' for variable names because I >> have no idea what it means, but it's not a huge issue in a script this >> small. If anything, I'd suggest more descriptive variable names and just a >> tad mor >> > e use of underscores in them to make it easier on the eyes. Google PEP 8 >> and check it out, it's the python style guide. >> >> > Sure- will do that going forward. as you can see for two of the files I have gone with descriptive names. > >> >> * I have no clue what DBRM or JCL are, and what a bind statement is. >> Ideally, if you could give us some examples of what your input and output >> looks like, I have a much better idea of what the script is trying to do. >> >> > I already provided the example of the "template". The other file has a list of the DBRMs like so bindjcldbrmlist.txt BBDTMC10 BBLAMC06 BBLAMC07 BBLAMC16 BBLAMC24 BBLAMC25 BBLBMC02 BBMTLC01 E5623941 F0829057 F0829073 Output would look like this (first 11 lines are the "fixed" part of the output) //SC10D01B JOB (SCM,RBSTC),'COOLGEN',MSGCLASS=A,CLASS=P, // COND=(4,LT) //* //BIND EXEC PGM=IKJEFT01,DYNAMNBR=50 //SYSTSPRT DD SYSOUT=* //SYSPRINT DD SYSOUT=* //DBRMLIB DD DSN=SCLM.PROD.DBRMLIB,DISP=SHR // DD DSN=SCLM.EMER.DBRMLIB,DISP=SHR // DD DSN=JOYCE,DISP=SHR //SYSTSIN DD * DSN SYSTEM(DSN) BIND PACKAGE(PROD) - MEMBER(BBDTMC10) - OWNER(SYSDB2) - QUALIFIER(PRODDB2) - ISOLATION(CS) - EXPLAIN(YES) - ACTION(REPLACE) - CURRENTDATA(YES) - VALIDATE(BIND) BIND PACKAGE(PROD) - MEMBER(BBLAMC06) - OWNER(SYSDB2) - QUALIFIER(PRODDB2) - ISOLATION(CS) - EXPLAIN(YES) - ACTION(REPLACE) - CURRENTDATA(YES) - VALIDATE(BIND) etc..etc > >> >> >> * Not knowing what version of python you have greatly limits the amount >> of useful advice I can give you. More modern versions support stuff like >> with statements to simplify file handling and the str.format function which >> may be very useful in your template (you could also use % style formatting, >> perhaps?). But if you're still on 2.5, which wouldn't surprise me on a big >> mainframe, you don't have the cool stuff yet. >> >> > I am not doing this on the mainframe. IBM mainframe doesn't have Python (at least not on z/OS), it has its own scripting language called REXX which is what I'd normally have written this in. I am doing this with Python 2.7 on windows after downloading the necessary input files from the mainframe and I'll upload the output back to the mainframe to run the job that was created > Like I said in the first point though, the script is very small and >> everything looks quite reasonable. It seems readable enough *if* you know >> what kind of input and output date it's dealing with. >> >> HTH, >> Hugo >> > > just fyi, my previous mail to you (quoted above) was blocked by leeds > learning for "unacceptable language." The only thing I could think of in it > that triggered the filter is s**t (I've also censored it out above). But > you might want to consider using a different address for communications > with public mailing lists. We're all here on our free time volunteering to > help out, and I'm not keen on going through the trouble of re-sending > e-mails and censoring myself just so I can help a stranger. No bad feelings > or anything, just pointing this out :) > > Happy to oblige, but not sure I fully understand. I'm using a gmail account and sending a mail to tutor at python.org What should I be doing differently? > Hugo > -------------- next part -------------- An HTML attachment was scrubbed... URL: From charles.leviton at gmail.com Sun Mar 17 19:58:19 2013 From: charles.leviton at gmail.com (Charles Leviton) Date: Sun, 17 Mar 2013 14:58:19 -0400 Subject: [Tutor] Script to generate statements Message-ID: Many thanks to Peter, Steven, Dave and Alan as well. Especially Peter's hints about using the "with construct". I discovered the missing strip() the hard way! -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Mar 17 20:41:32 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 17 Mar 2013 19:41:32 +0000 Subject: [Tutor] func-question_y_n.py In-Reply-To: References: Message-ID: On 17/03/13 17:40, Christopher Emery wrote: > Could you point me to a really good and easy to under about string > formatting? I am what I would say in programming a baby still on > milk. (smile) You'll find an introduction to old style formatting in my tutorial topic "Simple Sequences". In that style you would write your print statement as: print("Your response was %s! Please enter %s or %s for your response!" % (answer, p, n) ) # note can be one line... I only wrapped the line for email formatting... In new style (V3) formatting your line looks like: print("Your response was {0}! \ Please enter {1} or {2} for your response!".format(answer, p, n) ) Again it should be one line. V3 formatting is described here: http://docs.python.org/3/library/string.html#formatstrings And to make it more real, here are the examples: http://docs.python.org/3/library/string.html#formatexamples -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From kendy at kendy.org Mon Mar 18 06:28:11 2013 From: kendy at kendy.org (kendy at kendy.org) Date: Sun, 17 Mar 2013 22:28:11 PDT Subject: [Tutor] Fixing Globals Message-ID: <37348.1363584491@speakeasy.net> Thanks to everyone who responded. I learned from each person's response. The example code that I emailed was representative of many large programs that I've written in other languages. I've written many small Python scripts and I'm about to write a more complex Python script, much like the example -- needing help with globals. Thanks for your help!!! Alan's response was particularly interesting. On Sat Mar 16 16:07 , Alan Gauld sent: >On 16/03/13 19:04, kendy at kendy.org wrote: > >> Global constants and variables are bad. > >Really? Do you know why? >If you understand why then the measures to avoid them >become more palatable - the lesser of 2 evils. > >Read-only globals are much less of a problem than read/write ones. >And in Python we limit the damage by restricting globals to a single >module's scope. class variables do a similar job in OOP. Why are they bad? Hmmm. Because people say so? Hmmm. It's best to restrict dependencies. It's not fun to change one thing that affects many, far-away places. I actually don't mind globals if they're done well. I think passing a long list of arguments is the worst -- it becomes a big management issue and it clutters. Better programming helps minimize globals and long argument lists, but I don't see how they can always be eliminated. Books and teachers usually don't go into much detail about globals. I think that this is an important topic and I want to learn more. I now have more confidence but don't have a total grasp. Best regards, Ken From dave_bradshaw at talk21.com Mon Mar 18 10:32:51 2013 From: dave_bradshaw at talk21.com (David Bradshaw) Date: Mon, 18 Mar 2013 09:32:51 +0000 (GMT) Subject: [Tutor] Text Processing - Questions/Help. In-Reply-To: References: <1363257051.53559.YahooMailNeo@web87405.mail.ir2.yahoo.com> Message-ID: <1363599171.42286.YahooMailNeo@web87404.mail.ir2.yahoo.com> Alan, Thanks. See below [Dave] ________________________________ From: Alan Gauld To: tutor at python.org Sent: Thursday, 14 March 2013, 12:14 Subject: Re: [Tutor] Text Processing - Questions/Help. On 14/03/13 10:30, David Bradshaw wrote: > I have written some code that logs into a list of hosts and runs a > couple of commands to find out some information. Which I then save to a > file and process. > > A cut down version of the information I generate and save can be found > here - http://pastebin.com/4ePz3Z7m > > The code I have written to process this file can be found here - > http://pastebin.com/WBbKydLg Its fine to use pastebin for long programs. But... > information to generate a dhcpd.conf file. I have written the code to do > it, but it suffers the same problem. It's not totally clear what the problem is? > Currently when I run my code I get this as the output - > >? ? ? BBC21-14.ZONE21.WORK >? ? ? 178.28.185.89 > 6? ? vm14-6 >? ? ? 06BNBB6 >? ? ? 5C:F3:FC:C2:08:0C > 7? ? vm14-7 >? ? ? 06BNBM3 >? ? ? 5C:F3:FC:C2:0D:48 > 8? ? s21-04 >? ? ? 06KKY20 >? ? ? 5C:F3:FC:79:53:50 >? 00:10:18:E4:EA:EC > 9? ? ps41.p33 >? ? ? 06CZHR8 >? ? ? 34:40:B5:DC:2C:50 >? ? ? 00:10:18:E4:F3:2C > 10? ? vm14-8 >? ? ? 06BNBN6 >? ? ? 5C:F3:FC:C1:F3:10 > > Any pointers as to how in the cases where 2 MACs are displayed I only > display/output the second? Also there is no guarantee that in the future > the second MAC will start with 00:10. See the other thread about text processing. You need top use a flag, or sentinel. In your case the flag tells you when you stop getting MAC addresses, so in pseudo code inMacs = False for line in inputfile: ? if not inMacs and isMac(line):? # your function to identify a MAC ? ? ? inMacs = True ? if inMacs: ? ? ? if isMac(line): ? ? ? ? ? lastMac = line ? ? ? else: ? ? ? ? ? print lastMac ? ? ? ? ? inMacs = False [Dave] - Thanks, I will give this a go and see if it works, and report back. > From my code was it a fluke that I got the output formatted as it is > and I actually need to rethink how I process the information? Probably not, it'll be because that's how you processed it. But without reading your code I can't tell what that was. Whether the formatting is due to an explicit decision on your part or a result of some default Python behaviour I don't know, but it almost certainly won't be a fluke. (The exception is if its down to the order/structure of your input data) > Finally the information on pastebin, is it better or preferred that I > add it all in this thread, rather the putting it in pastebin? Its best if you can either post the relevant snippet from your code (with optional link to the full listing) or recreate the situation using a small example program. Having nothing in the mail puts too much onus on the reader to do all the work. If they are busy, lazy, or both, they won't bother. [Dave] - Will remember this for the next time I post. -- Alan G 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 dave_bradshaw at talk21.com Mon Mar 18 10:37:57 2013 From: dave_bradshaw at talk21.com (David Bradshaw) Date: Mon, 18 Mar 2013 09:37:57 +0000 (GMT) Subject: [Tutor] Text Processing - Questions/Help. References: <1363257051.53559.YahooMailNeo@web87405.mail.ir2.yahoo.com> Message-ID: <1363599477.62494.YahooMailNeo@web87405.mail.ir2.yahoo.com> Alan, Thanks. See below [Dave] ________________________________ From: Alan Gauld To: tutor at python.org Sent: Thursday, 14 March 2013, 12:14 Subject: Re: [Tutor] Text Processing - Questions/Help. On 14/03/13 10:30, David Bradshaw wrote: > I have written some code that logs into a list of hosts and runs a > couple of commands to find out some information. Which I then save to a > file and process. > > A cut down version of the information I generate and save can be found > here - http://pastebin.com/4ePz3Z7m > > The code I have written to process this file can be found here - > http://pastebin.com/WBbKydLg Its fine to use pastebin for long programs. But... > information to generate a dhcpd.conf file. I have written the code to do > it, but it suffers the same problem. It's not totally clear what the problem is? > Currently when I run my code I get this as the output - > >? ? ? BBC21-14.ZONE21.WORK >? ? ? 178.28.185.89 > 6? ? vm14-6 >? ? ? 06BNBB6 >? ? ? 5C:F3:FC:C2:08:0C > 7? ? vm14-7 >? ? ? 06BNBM3 >? ? ? 5C:F3:FC:C2:0D:48 > 8? ? s21-04 >? ? ? 06KKY20 >? ? ? 5C:F3:FC:79:53:50 >? 00:10:18:E4:EA:EC > 9? ? ps41.p33 >? ? ? 06CZHR8 >? ? ? 34:40:B5:DC:2C:50 >? ? ? 00:10:18:E4:F3:2C > 10? ? vm14-8 >? ? ? 06BNBN6 >? ? ? 5C:F3:FC:C1:F3:10 > > Any pointers as to how in the cases where 2 MACs are displayed I only > display/output the second? Also there is no guarantee that in the future > the second MAC will start with 00:10. See the other thread about text processing. You need top use a flag, or sentinel. In your case the flag tells you when you stop getting MAC addresses, so in pseudo code inMacs = False for line in inputfile: ? if not inMacs and isMac(line):? # your function to identify a MAC ? ? ? inMacs = True ? if inMacs: ? ? ? if isMac(line): ? ? ? ? ? lastMac = line ? ? ? else: ? ? ? ? ? print lastMac ? ? ? ? ? inMacs = False [Dave] - Thanks, I will give this a go and see if it works, and report back. > From my code was it a fluke that I got the output formatted as it is > and I actually need to rethink how I process the information? Probably not, it'll be because that's how you processed it. But without reading your code I can't tell what that was. Whether the formatting is due to an explicit decision on your part or a result of some default Python behaviour I don't know, but it almost certainly won't be a fluke. (The exception is if its down to the order/structure of your input data) > Finally the information on pastebin, is it better or preferred that I > add it all in this thread, rather the putting it in pastebin? Its best if you can either post the relevant snippet from your code (with optional link to the full listing) or recreate the situation using a small example program. Having nothing in the mail puts too much onus on the reader to do all the work. If they are busy, lazy, or both, they won't bother. [Dave] - Will remember this for the next time I post. -- Alan G 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 jf_byrnes at comcast.net Mon Mar 18 17:18:10 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Mon, 18 Mar 2013 11:18:10 -0500 Subject: [Tutor] Scripting Calligra sheets with Python Message-ID: I am trying to script Calligra Sheets (formerly KSpread) with python. I have gotten some of the included example scripts to run so I know python scripting is running. I found the following snippet on their website: import KSpread sheet = KSpread.view().sheet() # swap text of B5 and C6 t1 = sheet.text("B5") t2 = sheet.text(6,3) sheet.setText("B5", t2) sheet.setText(6, 3, t1) # swap value of D7 and E8 v1 = sheet.value("D7") v2 = sheet.value(8,5) sheet.setValue("D7", v2) sheet.setValue(8, 5, v1) Error: 'str' object has no attribute 'text' File "file:///usr/share/kde4/apps/sheets/scripts/extensions/myswap.py", line 4, in This error message appeared in a dialog box. I've taught myself some Python but I don't understand what is happening here. Shouldn't t1 be a sheet object? What would cause it to be a str instead? Thanks, Jim From hugo.yoshi at gmail.com Mon Mar 18 17:38:31 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Mon, 18 Mar 2013 17:38:31 +0100 Subject: [Tutor] Scripting Calligra sheets with Python In-Reply-To: References: Message-ID: On Mon, Mar 18, 2013 at 5:18 PM, Jim Byrnes wrote: > I am trying to script Calligra Sheets (formerly KSpread) with python. I > have gotten some of the included example scripts to run so I know python > scripting is running. > > I found the following snippet on their website: > > import KSpread > sheet = KSpread.view().sheet() > # swap text of B5 and C6 > t1 = sheet.text("B5") > t2 = sheet.text(6,3) > sheet.setText("B5", t2) > sheet.setText(6, 3, t1) > # swap value of D7 and E8 > v1 = sheet.value("D7") > v2 = sheet.value(8,5) > sheet.setValue("D7", v2) > sheet.setValue(8, 5, v1) > > Error: 'str' object has no attribute 'text' > File "file:///usr/share/kde4/apps/**sheets/scripts/extensions/**myswap.py", > line 4, in > > > This error message appeared in a dialog box. > > I've taught myself some Python but I don't understand what is happening > here. Shouldn't t1 be a sheet object? What would cause it to be a str > instead? > You'd be much better off asking the Calligra guys directly I think, somewhere at http://www.calligra.org/get-help/. It looks like KSpread.view().sheet() is returning a str object, as you correctly diagnose, but I'm not familiar enough with their API to say anything about the root cause. There will be a lot more expertise and knowledge available from their website than from this mailing list since this list's topic is far more general. I'd check the forums. Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Tue Mar 19 01:54:59 2013 From: davea at davea.name (Dave Angel) Date: Mon, 18 Mar 2013 20:54:59 -0400 Subject: [Tutor] Scripting Calligra sheets with Python In-Reply-To: References: Message-ID: <5147B763.3040103@davea.name> On 03/18/2013 12:18 PM, Jim Byrnes wrote: > I am trying to script Calligra Sheets (formerly KSpread) with python. I > have gotten some of the included example scripts to run so I know python > scripting is running. > > I found the following snippet on their website: > > import KSpread > sheet = KSpread.view().sheet() > # swap text of B5 and C6 > t1 = sheet.text("B5") > t2 = sheet.text(6,3) > sheet.setText("B5", t2) > sheet.setText(6, 3, t1) > # swap value of D7 and E8 > v1 = sheet.value("D7") > v2 = sheet.value(8,5) > sheet.setValue("D7", v2) > sheet.setValue(8, 5, v1) > > Error: 'str' object has no attribute 'text' > File > "file:///usr/share/kde4/apps/sheets/scripts/extensions/myswap.py", line > 4, in > > > This error message appeared in a dialog box. > > I've taught myself some Python but I don't understand what is happening > here. Shouldn't t1 be a sheet object? What would cause it to be a str > instead? > Since somebody has censored the rest of the error traceback, we can't even tell what line is giving the error. Assuming you know it's t1 = sheet.text("85") then it has nothing to do with the type of t1, but with the type of sheet. If that's the case, then print out type(sheet) and see what it actually is. Then consult the documentation for the KSpread.view().sheet() function and see what it's documented to return. > Thanks, Jim > > -- DaveA From jf_byrnes at comcast.net Tue Mar 19 02:56:30 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Mon, 18 Mar 2013 20:56:30 -0500 Subject: [Tutor] Scripting Calligra sheets with Python In-Reply-To: <5147B763.3040103@davea.name> References: <5147B763.3040103@davea.name> Message-ID: On 03/18/2013 07:54 PM, Dave Angel wrote: > On 03/18/2013 12:18 PM, Jim Byrnes wrote: >> I am trying to script Calligra Sheets (formerly KSpread) with python. I >> have gotten some of the included example scripts to run so I know python >> scripting is running. >> >> I found the following snippet on their website: >> >> import KSpread >> sheet = KSpread.view().sheet() >> # swap text of B5 and C6 >> t1 = sheet.text("B5") >> t2 = sheet.text(6,3) >> sheet.setText("B5", t2) >> sheet.setText(6, 3, t1) >> # swap value of D7 and E8 >> v1 = sheet.value("D7") >> v2 = sheet.value(8,5) >> sheet.setValue("D7", v2) >> sheet.setValue(8, 5, v1) >> >> Error: 'str' object has no attribute 'text' >> File >> "file:///usr/share/kde4/apps/sheets/scripts/extensions/myswap.py", line >> 4, in >> >> >> This error message appeared in a dialog box. >> >> I've taught myself some Python but I don't understand what is happening >> here. Shouldn't t1 be a sheet object? What would cause it to be a str >> instead? >> > > Since somebody has censored the rest of the error traceback, we can't > even tell what line is giving the error. Assuming you know it's > t1 = sheet.text("85") I think line wrapping obscured that it is line 4 t1 = sheet.text("B5"). > then it has nothing to do with the type of t1, but with the type of > sheet. If that's the case, then print out type(sheet) and see what it > actually is. Then consult the documentation for the > KSpread.view().sheet() function and see what it's documented to return. > The docs say: Returns the KSpread::ViewAdaptor object in which the document is displayed. I would like to follow your advice and print out type(sheet) but right now I don't know how. This is all running inside Calligra sheets and so far the only thing I have gotten out if it is the error message. Thanks for the suggestion, now I can be a little more focused trying to figure this out, which is why I asked here first. I have since taken Hugo's advise and posted to the Calligra list also. Regards, Jim >> Thanks, Jim >> >> > > From davea at davea.name Tue Mar 19 05:25:18 2013 From: davea at davea.name (Dave Angel) Date: Tue, 19 Mar 2013 00:25:18 -0400 Subject: [Tutor] Scripting Calligra sheets with Python In-Reply-To: References: <5147B763.3040103@davea.name> Message-ID: <5147E8AE.7020401@davea.name> On 03/18/2013 09:56 PM, Jim Byrnes wrote: > On 03/18/2013 07:54 PM, Dave Angel wrote: >> On 03/18/2013 12:18 PM, Jim Byrnes wrote: >>> I am trying to script Calligra Sheets (formerly KSpread) with python. I >>> have gotten some of the included example scripts to run so I know python >>> scripting is running. >>> >>> I found the following snippet on their website: >>> >>> import KSpread >>> sheet = KSpread.view().sheet() >>> # swap text of B5 and C6 >>> t1 = sheet.text("B5") >>> t2 = sheet.text(6,3) >>> sheet.setText("B5", t2) >>> sheet.setText(6, 3, t1) >>> # swap value of D7 and E8 >>> v1 = sheet.value("D7") >>> v2 = sheet.value(8,5) >>> sheet.setValue("D7", v2) >>> sheet.setValue(8, 5, v1) >>> >>> Error: 'str' object has no attribute 'text' >>> File >>> "file:///usr/share/kde4/apps/sheets/scripts/extensions/myswap.py", line >>> 4, in >>> >>> >>> This error message appeared in a dialog box. >>> >>> I've taught myself some Python but I don't understand what is happening >>> here. Shouldn't t1 be a sheet object? What would cause it to be a str >>> instead? >>> >> >> Since somebody has censored the rest of the error traceback, we can't >> even tell what line is giving the error. Assuming you know it's >> t1 = sheet.text("85") > > I think line wrapping obscured that it is line 4 t1 = sheet.text("B5"). I saw the line 4, but didn't see anyplace where it showed me line 4. So i had to guess. And for all I knew, the error isn't happening on that line, but on some line called indirectly by that one. The full stack trace would be reassuring. But apparently your Calligra environment is censoring it. > >> then it has nothing to do with the type of t1, but with the type of >> sheet. If that's the case, then print out type(sheet) and see what it >> actually is. Then consult the documentation for the >> KSpread.view().sheet() function and see what it's documented to return. >> > > The docs say: Returns the KSpread::ViewAdaptor object in which the > document is displayed. > > I would like to follow your advice and print out type(sheet) but right > now I don't know how. This is all running inside Calligra sheets and so > far the only thing I have gotten out if it is the error message. Are you permitted to edit this myswap.py file? If so, add a line that prints the useful information immediately before the line which causes the exception. And if print is also swallowed by your helpful environment, then write to a file. > > Thanks for the suggestion, now I can be a little more focused trying to > figure this out, which is why I asked here first. I have since taken > Hugo's advise and posted to the Calligra list also. > > import KSpread sheet = KSpread.view().sheet() # swap text of B5 and C6 print "Calling a method on the sheet object, of type", type(sheet) t1 = sheet.text("B5") -- DaveA From jf_byrnes at comcast.net Wed Mar 20 03:16:36 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Tue, 19 Mar 2013 21:16:36 -0500 Subject: [Tutor] Scripting Calligra sheets with Python In-Reply-To: <5147E8AE.7020401@davea.name> References: <5147B763.3040103@davea.name> <5147E8AE.7020401@davea.name> Message-ID: On 03/18/2013 11:25 PM, Dave Angel wrote: > On 03/18/2013 09:56 PM, Jim Byrnes wrote: >> On 03/18/2013 07:54 PM, Dave Angel wrote: >>> On 03/18/2013 12:18 PM, Jim Byrnes wrote: >>>> I am trying to script Calligra Sheets (formerly KSpread) with >>>> python. I >>>> have gotten some of the included example scripts to run so I know >>>> python >>>> scripting is running. >>>> >>>> I found the following snippet on their website: >>>> >>>> import KSpread >>>> sheet = KSpread.view().sheet() >>>> # swap text of B5 and C6 >>>> t1 = sheet.text("B5") >>>> t2 = sheet.text(6,3) >>>> sheet.setText("B5", t2) >>>> sheet.setText(6, 3, t1) >>>> # swap value of D7 and E8 >>>> v1 = sheet.value("D7") >>>> v2 = sheet.value(8,5) >>>> sheet.setValue("D7", v2) >>>> sheet.setValue(8, 5, v1) >>>> >>>> Error: 'str' object has no attribute 'text' >>>> File >>>> "file:///usr/share/kde4/apps/sheets/scripts/extensions/myswap.py", line >>>> 4, in >>>> >>>> >>>> This error message appeared in a dialog box. >>>> >>>> I've taught myself some Python but I don't understand what is happening >>>> here. Shouldn't t1 be a sheet object? What would cause it to be a str >>>> instead? >>>> >>> >>> Since somebody has censored the rest of the error traceback, we can't >>> even tell what line is giving the error. Assuming you know it's >>> t1 = sheet.text("85") >> >> I think line wrapping obscured that it is line 4 t1 = sheet.text("B5"). > > I saw the line 4, but didn't see anyplace where it showed me line 4. So > i had to guess. And for all I knew, the error isn't happening on that > line, but on some line called indirectly by that one. The full stack > trace would be reassuring. But apparently your Calligra environment is > censoring it. > >> >>> then it has nothing to do with the type of t1, but with the type of >>> sheet. If that's the case, then print out type(sheet) and see what it >>> actually is. Then consult the documentation for the >>> KSpread.view().sheet() function and see what it's documented to return. >>> >> >> The docs say: Returns the KSpread::ViewAdaptor object in which the >> document is displayed. >> >> I would like to follow your advice and print out type(sheet) but right >> now I don't know how. This is all running inside Calligra sheets and so >> far the only thing I have gotten out if it is the error message. > > Are you permitted to edit this myswap.py file? If so, add a line that > prints the useful information immediately before the line which causes > the exception. And if print is also swallowed by your helpful > environment, then write to a file. Yes I can and it does swallow it, so I redirected to a file and it says . Same as the error message. So now I need to figure out why it's not returning the object expected. I can run the sample scripts that were installed but not something I originate. I guess I must be missing something procedural that is keeping them from running properly. Thanks for you help. Regards, Jim From phil_lor at bigpond.com Wed Mar 20 03:54:46 2013 From: phil_lor at bigpond.com (Phil) Date: Wed, 20 Mar 2013 12:54:46 +1000 Subject: [Tutor] Dictionary get method Message-ID: <514924F6.8020204@bigpond.com> Thank you for reading this. I'm working my way through a series of exercises where the author only provides a few solutions. The reader is asked to modify the histogram example so that it uses the get method thereby eliminating the if and else statements. Histogram2 is my effort. The resulting dictionary only contains the default value provided by "get" and I cannot see how the value can be incremented without an if statement. def histogram(s): d = dict() for c in s: if c not in d: d[c] = 1 else: d[c] += 1 return d def histogram2(s): d = dict() for c in s: d[c]= d.get(c, 0) return d h = histogram("brontosaurs") print h print print "histogram2" h = histogram2("brontosaurs") print h -- Regards, Phil From msirenef at lightbird.net Wed Mar 20 05:54:29 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Wed, 20 Mar 2013 00:54:29 -0400 Subject: [Tutor] Dictionary get method In-Reply-To: <514924F6.8020204@bigpond.com> References: <514924F6.8020204@bigpond.com> Message-ID: <51494105.4070103@lightbird.net> On 03/19/2013 10:54 PM, Phil wrote: > Thank you for reading this. > > I'm working my way through a series of exercises where the author only provides a few solutions. > > The reader is asked to modify the histogram example so that it uses the get method thereby eliminating the if and else statements. Histogram2 is my effort. > > The resulting dictionary only contains the default value provided by "get" and I cannot see how the value can be incremented without an if statement. > > def histogram(s): > d = dict() > for c in s: > if c not in d: > d[c] = 1 > else: > d[c] += 1 > return d > > def histogram2(s): > d = dict() > for c in s: > d[c]= d.get(c, 0) > > return d > > h = histogram("brontosaurs") > > print h > > print > > print "histogram2" > > h = histogram2("brontosaurs") > > print h > Add + 1 -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Whenever you find yourself on the side of the majority, it is time to pause and reflect. Mark Twain From amitsaha.in at gmail.com Wed Mar 20 05:54:15 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Wed, 20 Mar 2013 14:54:15 +1000 Subject: [Tutor] Dictionary get method In-Reply-To: <514924F6.8020204@bigpond.com> References: <514924F6.8020204@bigpond.com> Message-ID: Hello Phil, On Wed, Mar 20, 2013 at 12:54 PM, Phil wrote: > Thank you for reading this. > > I'm working my way through a series of exercises where the author only > provides a few solutions. > > The reader is asked to modify the histogram example so that it uses the get > method thereby eliminating the if and else statements. Histogram2 is my > effort. > > The resulting dictionary only contains the default value provided by "get" > and I cannot see how the value can be incremented without an if statement. You are almost there. Note that all you have to do is increment 1 to the current 'value' for the key denoted by c. If you change the line with get() to the following, it works as you want it to: d[c]= 1 + d.get(c, 0) Output: {'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 1, 't': 1} histogram2 {'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 1, 't': 1} You were almost there. Good Luck. -Amit. -- http://amitsaha.github.com/ From msirenef at lightbird.net Wed Mar 20 06:09:38 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Wed, 20 Mar 2013 01:09:38 -0400 Subject: [Tutor] Dictionary get method In-Reply-To: <514924F6.8020204@bigpond.com> References: <514924F6.8020204@bigpond.com> Message-ID: <51494492.6000902@lightbird.net> On 03/19/2013 10:54 PM, Phil wrote: > Thank you for reading this. > > I'm working my way through a series of exercises where the author only provides a few solutions. > > The reader is asked to modify the histogram example so that it uses the get method thereby eliminating the if and else statements. Histogram2 is my effort. > > The resulting dictionary only contains the default value provided by "get" and I cannot see how the value can be incremented without an if statement. > > def histogram(s): > d = dict() > for c in s: > if c not in d: > d[c] = 1 > else: > d[c] += 1 > return d > > def histogram2(s): > d = dict() > for c in s: > d[c]= d.get(c, 0) > > return d > > h = histogram("brontosaurs") > > print h > > print > > print "histogram2" > > h = histogram2("brontosaurs") > > print h > By the way, you can further simplify it by doing: def histogram2(s): return {c: d.get(c,0)+1 for c in s} That will work in python 3, in python 2 you need: return dict((c: d.get(c,0)+1) for c in s) -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Those who can make you believe absurdities can make you commit atrocities. Voltaire From msirenef at lightbird.net Wed Mar 20 06:26:23 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Wed, 20 Mar 2013 01:26:23 -0400 Subject: [Tutor] Dictionary get method In-Reply-To: <51494492.6000902@lightbird.net> References: <514924F6.8020204@bigpond.com> <51494492.6000902@lightbird.net> Message-ID: <5149487F.8030607@lightbird.net> On 03/20/2013 01:09 AM, Mitya Sirenef wrote: > > > By the way, you can further simplify it by doing: > > def histogram2(s): > return {c: d.get(c,0)+1 for c in s} > > > That will work in python 3, in python 2 you need: > > return dict((c: d.get(c,0)+1) for c in s) > > Sorry, it should use a comma: return dict((c, d.get(c,0)+1) for c in s) -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ From phil_lor at bigpond.com Wed Mar 20 06:05:23 2013 From: phil_lor at bigpond.com (Phil) Date: Wed, 20 Mar 2013 15:05:23 +1000 Subject: [Tutor] Dictionary get method In-Reply-To: References: <514924F6.8020204@bigpond.com> Message-ID: <51494393.2030108@bigpond.com> On 20/03/13 14:54, Amit Saha wrote: > Hello Phil, > > On Wed, Mar 20, 2013 at 12:54 PM, Phil wrote: >> Thank you for reading this. >> >> I'm working my way through a series of exercises where the author only >> provides a few solutions. >> >> The reader is asked to modify the histogram example so that it uses the get >> method thereby eliminating the if and else statements. Histogram2 is my >> effort. >> >> The resulting dictionary only contains the default value provided by "get" >> and I cannot see how the value can be incremented without an if statement. > > You are almost there. Note that all you have to do is increment 1 to > the current 'value' for the key denoted by c. If you change the line > with get() to the following, it works as you want it to: > > d[c]= 1 + d.get(c, 0) > > Output: > > {'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 1, 't': 1} > > histogram2 > {'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 1, 't': 1} > > You were almost there. Good Luck. > > -Amit. > Thanks Amit and Mitya, I thought I must have been close. I've played with C++ since the mid 90s and I'm finding Python very refreshing. -- Regards, Phil From phil_lor at bigpond.com Wed Mar 20 06:59:25 2013 From: phil_lor at bigpond.com (Phil) Date: Wed, 20 Mar 2013 15:59:25 +1000 Subject: [Tutor] Dictionary get method In-Reply-To: <51494492.6000902@lightbird.net> References: <514924F6.8020204@bigpond.com> <51494492.6000902@lightbird.net> Message-ID: <5149503D.70803@bigpond.com> On 20/03/13 15:09, Mitya Sirenef wrote: > > By the way, you can further simplify it by doing: > > def histogram2(s): > return {c: d.get(c,0)+1 for c in s} > > > That will work in python 3, in python 2 you need: > > return dict((c: d.get(c,0)+1) for c in s) > Thanks again Mitya, although I'm not sure it's a simplification at my present level. -- Regards, Phil From __peter__ at web.de Wed Mar 20 09:21:13 2013 From: __peter__ at web.de (Peter Otten) Date: Wed, 20 Mar 2013 09:21:13 +0100 Subject: [Tutor] Dictionary get method References: <514924F6.8020204@bigpond.com> <51494492.6000902@lightbird.net> <5149503D.70803@bigpond.com> Message-ID: Phil wrote: > On 20/03/13 15:09, Mitya Sirenef wrote: > > >> >> By the way, you can further simplify it by doing: >> >> def histogram2(s): >> return {c: d.get(c,0)+1 for c in s} >> >> >> That will work in python 3, in python 2 you need: >> >> return dict((c: d.get(c,0)+1) for c in s) >> > > Thanks again Mitya, although I'm not sure it's a simplification at my > present level. Especially as Mitya's code doesn't work. >>> {k: v for k, v in [(1, "a"), (2, "b")]} {1: 'a', 2: 'b'} is called "dict comprehension", it builds a dict from a list of key-value pairs. However, there is no way to reference the resulting dict while it is being built, and that is necessary for a histogram. It is possible to use dict.update() with a generator expression >>> d = {} >>> d.update((c, d.get(c, 0)+1) for c in "abba") >>> d {'a': 2, 'b': 2} but frankly, I don't see how that is better than the for loop. So as your experience with Python grows you may continue to use a loop or switch to the standard library's collections.Counter (Python3 only). From nishithareddy0011 at gmail.com Wed Mar 20 12:38:49 2013 From: nishithareddy0011 at gmail.com (nishitha reddy) Date: Wed, 20 Mar 2013 17:08:49 +0530 Subject: [Tutor] help related to unicode using python Message-ID: Hi all i'm working with unicode using python i have some txt files in telugu i want to split all the lines of that text files in to words of telugu and i need to classify all of them using some identifiers.can any one send solution for that thank u From breamoreboy at yahoo.co.uk Wed Mar 20 14:05:39 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 20 Mar 2013 13:05:39 +0000 Subject: [Tutor] help related to unicode using python In-Reply-To: References: Message-ID: On 20/03/2013 11:38, nishitha reddy wrote: > Hi all > i'm working with unicode using python > i have some txt files in telugu i want to split all the lines of that > text files in to words of telugu > and i need to classify all of them using some identifiers.can any one > send solution for that > thank u > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Sorry but we don't work like that. You write some code and when you get problems ask for help. I'd strongly suggest using Python 3.3 if you can for your processing. It's vastly superior to earlier, buggy unicode implementations in Python. -- Cheers. Mark Lawrence From msirenef at lightbird.net Wed Mar 20 14:13:28 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Wed, 20 Mar 2013 09:13:28 -0400 Subject: [Tutor] Dictionary get method In-Reply-To: References: <514924F6.8020204@bigpond.com> <51494492.6000902@lightbird.net> <5149503D.70803@bigpond.com> Message-ID: <5149B5F8.7060208@lightbird.net> On 03/20/2013 04:21 AM, Peter Otten wrote: > Phil wrote: > >> On 20/03/13 15:09, Mitya Sirenef wrote: >> >> >>> By the way, you can further simplify it by doing: >>> >>> def histogram2(s): >>> return {c: d.get(c,0)+1 for c in s} >>> >>> >>> That will work in python 3, in python 2 you need: >>> >>> return dict((c: d.get(c,0)+1) for c in s) >>> >> Thanks again Mitya, although I'm not sure it's a simplification at my >> present level. > Especially as Mitya's code doesn't work. Ah, yes - I messed up here.. I agree the loop is the best option here, vs. the example below. -m >>>> d = {} >>>> d.update((c, d.get(c, 0)+1) for c in "abba") >>>> d > {'a': 2, 'b': 2} > > but frankly, I don't see how that is better than the for loop. > > So as your experience with Python grows you may continue to use a loop or > switch to the standard library's collections.Counter (Python3 only). > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ From steve at pearwood.info Wed Mar 20 19:48:29 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 21 Mar 2013 05:48:29 +1100 Subject: [Tutor] help related to unicode using python In-Reply-To: References: Message-ID: <514A047D.8010600@pearwood.info> On 20/03/13 22:38, nishitha reddy wrote: > Hi all > i'm working with unicode using python > i have some txt files in telugu i want to split all the lines of that > text files in to words of telugu > and i need to classify all of them using some identifiers.can any one > send solution for that Probably not. I would be surprised if anyone here knows what Telugu is, or the rules for splitting Telugu text into words. The Natural Language Toolkit (NLTK) may be able to handle it. You could try doing the splitting and classifying yourself. If Telugu uses space-delimited words like English, you can do it easily: data = u"??? ??? ????" words = data.split() As for classifying the words, I have no idea, sorry. -- Steven From trvsjeanfrancois12 at gmail.com Wed Mar 20 20:57:50 2013 From: trvsjeanfrancois12 at gmail.com (travis jeanfrancois) Date: Wed, 20 Mar 2013 15:57:50 -0400 Subject: [Tutor] Help Message-ID: Hello, I am a beginning python student and I am having trouble with a program I am writing . The problem requires me to use "while" and that I create a function that allows the user to a create sentence by inputing a string and to end the sentence with a period meaning inputing "." .The problem is while keeps overwriting the previuos input and it still asks for a string even after it prints out . Here is the output I am getting Enter the first word in your sentence: I Enter the next word in your sentence: am Enter the next word in your sentence: a Enter the next word in your sentence: novice Enter the next word in your sentence: . I . . Enter the next word in your sentence: Here is the desired output: : Enter the first word in your sentence: I Enter the next word in your sentence: am Enter the next word in your sentence: a Enter the next word in your sentence: novice Enter the next word in your sentence: . I am a novice. Here is my code: def B1(): #Creates a function called B1 period = "." # The variable period is assigned first = input("Enter the first word in your sentence ") #The variable first is assigned next1 = input("Enter the next word in you sentence or enter period:") #The variable next 1 is assigned # I need store the value so when while overwrites next1 with the next input the previous input is stored and will print output when I call it later along with last one # I believe the solution is some how implenting this expression x = x+ variable while next1 != (period) : next1 = input("Enter the next word in you sentence or enter period:") if next1 == (period): next1 = next1 + period print ("Your sentence is:",first,next1,period) PS : The" #" is I just type so I can understand what each line does -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Wed Mar 20 21:39:35 2013 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Wed, 20 Mar 2013 21:39:35 +0100 Subject: [Tutor] Help In-Reply-To: References: Message-ID: > Hello, I am a beginning python student and I am having trouble with a > program I am writing. Hello, and welcome. Since you don't say if this is an assignment or not, I will just point you in the right direction, and point out a few things you might make use of. > def B1(): > period = "." You don't actually need to store a period anywhere, because when your while loop initiates, you can just do: while next1 != "." A word of advice: next is a keyword in python, so 'next1' might not be a great variable name. > # I need store the value so when while overwrites next1 with the next input > the previous input is stored and will print output when I call it later > along with last one > # I believe the solution is some how implenting this expression x = x+ > variable > while next1 != (period) : > > next1 = input("Enter the next word in you sentence or enter period:") > > if next1 == (period): > next1 = next1 + period > print ("Your sentence is:",first,next1,period) Your code will never terminate, because: program initiates. while loop begins. Enter a few words, then decide to end with a period. if-branch executes, because next1 is a period. next1 becomes next1 + period #which is .. while loop checks to see if next1 is a period, which it isn't, and runs again. Furthermore, you are continually overwriting next1 until you type a period. Consider the following output (I have added some spaces to the important parts, so as to make them stand out): >>> Enter the first word in your sentence I Enter the next word in you sentence or enter period:am Entering while loop. next1 is: am Enter the next word in you sentence or enter period:a next1 is: a Entering while loop. next1 is: a Enter the next word in you sentence or enter period:novice next1 is: novice Entering while loop. next1 is: novice Enter the next word in you sentence or enter period:. next1 is: . next1 is a period, now running next1 + period line: .. Entering while loop. next1 is: .. If you don't have to use strings for this program, I would suggest you check out lists, and especially list.append(). It is possible to write a program that does what you want, but it'd be a convoluted solution. -- best regards, Robert S. From davea at davea.name Wed Mar 20 21:53:19 2013 From: davea at davea.name (Dave Angel) Date: Wed, 20 Mar 2013 16:53:19 -0400 Subject: [Tutor] Help In-Reply-To: References: Message-ID: <514A21BF.9030303@davea.name> On 03/20/2013 03:57 PM, travis jeanfrancois wrote: > Hello, I am a beginning python student and I am having trouble with a > program I am writing . The problem requires me to use "while" and that I > create a function that allows the user to a create sentence by inputing a > string and to end the sentence with a period meaning inputing "." .The > problem is while keeps overwriting the previuos input and it still asks for > a string even after it prints out . > > Here is the output I am getting > > > Enter the first word in your sentence: I > Enter the next word in your sentence: am > Enter the next word in your sentence: a > Enter the next word in your sentence: novice > Enter the next word in your sentence: . > I . . > Enter the next word in your sentence: > > > Here is the desired output: > : > Enter the first word in your sentence: I > Enter the next word in your sentence: am > Enter the next word in your sentence: a > Enter the next word in your sentence: novice > Enter the next word in your sentence: . > I am a novice. > > Here is my code: > > > > > > def B1(): > #Creates a function called B1 > period = "." > # The variable period is assigned > first = input("Enter the first word in your sentence ") > #The variable first is assigned > next1 = input("Enter the next word in you sentence or enter period:") > #The variable next 1 is assigned > > # I need store the value so when while overwrites next1 with the next > input the previous input is stored and will print output when I call it > later along with last one > # I believe the solution is some how implenting this expression x = x+ > variable You need a new variable that accumulates the whole sentence. I'd use a list, but many people would use a string. Since I don't know what concepts you know yet, I'll stick to string here. Anyway, you have to initialize it before the loop, and then you can print it after the loop. sentence = "" > > while next1 != (period) : > > next1 = input("Enter the next word in you sentence or enter period:") At this point, add the word to the sentence. > > if next1 == (period): > next1 = next1 + period > print ("Your sentence is:",first,next1,period) No need for these three lines inside the loop, since the loop will end when next1 is equal to the period. So put the print after the end of the loop, and I'll let you figure out what it should print. > > PS : The" #" is I just type so I can understand what each line does > > -- DaveA From thudfoo at gmail.com Wed Mar 20 22:47:39 2013 From: thudfoo at gmail.com (xDog Walker) Date: Wed, 20 Mar 2013 14:47:39 -0700 Subject: [Tutor] Help In-Reply-To: References: Message-ID: <201303201447.39643.thudfoo@gmail.com> On Wednesday 2013 March 20 13:39, Robert Sjoblom wrote: > A word of advice: next is a keyword in python ~/Packages/Python/Notable-0.1.5b> python Python 2.5 (r25:51908, May 25 2007, 16:14:04) [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import keyword >>> keyword.iskeyword('next') False >>> 14:44 Wed 2013 Mar 20 ~/Packages/Python/Notable-0.1.5b> python2.7 Python 2.7.2 (default, Oct 10 2011, 10:47:36) [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import keyword >>> keyword.iskeyword('next') False >>> 14:44 Wed 2013 Mar 20 ~/Packages/Python/Notable-0.1.5b> python3.3 Python 3.3.0 (default, Sep 30 2012, 09:02:56) [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import keyword >>> keyword.iskeyword('next') False >>> -- Yonder nor sorghum stenches shut ladle gulls stopper torque wet strainers. From robert.sjoblom at gmail.com Wed Mar 20 22:59:04 2013 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Wed, 20 Mar 2013 22:59:04 +0100 Subject: [Tutor] Help In-Reply-To: <201303201447.39643.thudfoo@gmail.com> References: <201303201447.39643.thudfoo@gmail.com> Message-ID: On Mar 20, 2013 10:49 p.m., "xDog Walker" wrote: > > On Wednesday 2013 March 20 13:39, Robert Sjoblom wrote: > > A word of advice: next is a keyword in python > > ~/Packages/Python/Notable-0.1.5b> python > Python 2.5 (r25:51908, May 25 2007, 16:14:04) > [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import keyword > >>> keyword.iskeyword('next') > False > >>> > 14:44 Wed 2013 Mar 20 > ~/Packages/Python/Notable-0.1.5b> python2.7 > Python 2.7.2 (default, Oct 10 2011, 10:47:36) > [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import keyword > >>> keyword.iskeyword('next') > False > >>> > 14:44 Wed 2013 Mar 20 > ~/Packages/Python/Notable-0.1.5b> python3.3 > Python 3.3.0 (default, Sep 30 2012, 09:02:56) > [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux > Type "help", "copyright", "credits" or "license" for more information. > >>> import keyword > >>> keyword.iskeyword('next') > False > >>> > > -- > Yonder nor sorghum stenches shut ladle gulls stopper torque wet > strainers. Fine, it's a method, my bad. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jf_byrnes at comcast.net Thu Mar 21 01:26:54 2013 From: jf_byrnes at comcast.net (Jim Byrnes) Date: Wed, 20 Mar 2013 19:26:54 -0500 Subject: [Tutor] Scripting Calligra sheets with Python In-Reply-To: References: <5147B763.3040103@davea.name> <5147E8AE.7020401@davea.name> Message-ID: On 03/19/2013 09:16 PM, Jim Byrnes wrote: > On 03/18/2013 11:25 PM, Dave Angel wrote: >> On 03/18/2013 09:56 PM, Jim Byrnes wrote: >>> On 03/18/2013 07:54 PM, Dave Angel wrote: >>>> On 03/18/2013 12:18 PM, Jim Byrnes wrote: >>>>> I am trying to script Calligra Sheets (formerly KSpread) with >>>>> python. I >>>>> have gotten some of the included example scripts to run so I know >>>>> python >>>>> scripting is running. >>>>> >>>>> I found the following snippet on their website: >>>>> >>>>> import KSpread >>>>> sheet = KSpread.view().sheet() >>>>> # swap text of B5 and C6 >>>>> t1 = sheet.text("B5") >>>>> t2 = sheet.text(6,3) >>>>> sheet.setText("B5", t2) >>>>> sheet.setText(6, 3, t1) >>>>> # swap value of D7 and E8 >>>>> v1 = sheet.value("D7") >>>>> v2 = sheet.value(8,5) >>>>> sheet.setValue("D7", v2) >>>>> sheet.setValue(8, 5, v1) >>>>> >>>>> Error: 'str' object has no attribute 'text' >>>>> File >>>>> "file:///usr/share/kde4/apps/sheets/scripts/extensions/myswap.py", >>>>> line >>>>> 4, in >>>>> >>>>> >>>>> This error message appeared in a dialog box. >>>>> >>>>> I've taught myself some Python but I don't understand what is >>>>> happening >>>>> here. Shouldn't t1 be a sheet object? What would cause it to be a >>>>> str >>>>> instead? >>>>> >>>> >>>> Since somebody has censored the rest of the error traceback, we can't >>>> even tell what line is giving the error. Assuming you know it's >>>> t1 = sheet.text("85") >>> >>> I think line wrapping obscured that it is line 4 t1 = sheet.text("B5"). >> >> I saw the line 4, but didn't see anyplace where it showed me line 4. So >> i had to guess. And for all I knew, the error isn't happening on that >> line, but on some line called indirectly by that one. The full stack >> trace would be reassuring. But apparently your Calligra environment is >> censoring it. >> >>> >>>> then it has nothing to do with the type of t1, but with the type of >>>> sheet. If that's the case, then print out type(sheet) and see what it >>>> actually is. Then consult the documentation for the >>>> KSpread.view().sheet() function and see what it's documented to return. >>>> >>> >>> The docs say: Returns the KSpread::ViewAdaptor object in which the >>> document is displayed. >>> >>> I would like to follow your advice and print out type(sheet) but right >>> now I don't know how. This is all running inside Calligra sheets and so >>> far the only thing I have gotten out if it is the error message. >> >> Are you permitted to edit this myswap.py file? If so, add a line that >> prints the useful information immediately before the line which causes >> the exception. And if print is also swallowed by your helpful >> environment, then write to a file. > > Yes I can and it does swallow it, so I redirected to a file and it says > . Same as the error message. So now I need to figure out > why it's not returning the object expected. > > I can run the sample scripts that were installed but not something I > originate. I guess I must be missing something procedural that is > keeping them from running properly. > > Thanks for you help. > > Regards, Jim > > Just a follow up for completeness in case some else finds this and has the same problem. Replace line 2 sheet = KSpread.view().sheet() with sheetname = KSpread.currentSheet().sheetName() sheet = KSpread.sheetByName(sheetname) Then it will run with no errors. Regards, Jim From alan.gauld at btinternet.com Thu Mar 21 01:26:56 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Mar 2013 00:26:56 +0000 Subject: [Tutor] Help In-Reply-To: References: Message-ID: On 20/03/13 19:57, travis jeanfrancois wrote: > I create a function that allows the user to a create sentence by > inputing a string and to end the sentence with a period meaning > inputing "." .The problem is while keeps overwriting the previuos input 'While' does not do any such thing. Your code is doing that all by itself. What while does is repeat your code until a condition becomes false or you explicitly break out of the loop. > Here is my code: > > def B1(): Try to give your functions names that describe what they do. B1() is meaningless, readSentence() would be better. > period = "." > # The variable period is assigned Its normal programming practice to put the comment above the code not after it. Also comments should indicate why you are doing something not what you are doing - we can see that from the code. > first = input("Enter the first word in your sentence ") > next1 = input("Enter the next word in you sentence or enter period:") > # I need store the value so when while overwrites next1 with the next > input the previous input is stored and will print output when I call it > later along with last one > # I believe the solution is some how implenting this expression x = x+ > variable You could be right. Addition works for strings as well as numbers. Although there are other (better) options but you may not have covered them in your class yet. > while next1 != (period) : You don;t need the parentheses around period. Also nextWord might be a better name than next1. Saving 3 characters of typing is not usually worthwhile. > next1 = input("Enter the next word in you sentence or enter period:") Right, here you are overwriting next1. It's not the while's fault - it is just repeating your code. It is you who are overwriting the variable. Notice that you are not using the first that you captured? Maybe you should add next1 to first at some point? Then you can safely overwrite next1 as much as you like? > if next1 == (period): Again you don;t need the parentheses around period > next1 = next1 + period Here, you add the period to next1 which the 'if' has already established is now a period. > print ("Your sentence is:",first,next1,period) And now you print out the first word plus next1 (= 2 periods) plus a period = 3 periods in total... preceded by the phrase "Your sentence is:" This tells us that the sample output you posted is not from this program... Always match the program and the output when debugging or you will be led seriously astray! > PS : The" #" is I just type so I can understand what each line does The # is a comment marker. Comments are a very powerful tool that programmers use to explain to themselves and other programmers why they have done what they have. When trying to debug faults like this it is often worthwhile grabbing a pen and drawing a chart of your variables and their values after each time round the loop. In this case it would have looked like iteration period first next1 0 . I am 1 . I a 2 . I novice 3 . I .. If you aren't sure of the values insert a print statement and get the program to tell you, but working it out in your head is more likely to show you the error. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From shantanoo at gmail.com Thu Mar 21 05:08:36 2013 From: shantanoo at gmail.com (=?UTF-8?B?4KS24KSC4KSk4KSo4KWC?=) Date: Thu, 21 Mar 2013 09:38:36 +0530 Subject: [Tutor] help related to unicode using python In-Reply-To: <514A047D.8010600@pearwood.info> References: <514A047D.8010600@pearwood.info> Message-ID: <514A87C4.7010101@gmail.com> Reply inline. On 21/03/13 12:18 AM, Steven D'Aprano wrote: > On 20/03/13 22:38, nishitha reddy wrote: >> Hi all >> i'm working with unicode using python >> i have some txt files in telugu i want to split all the lines of that >> text files in to words of telugu >> and i need to classify all of them using some identifiers.can any one >> send solution for that > > > Probably not. I would be surprised if anyone here knows what Telugu is, > or the rules for splitting Telugu text into words. The Natural Language > Toolkit (NLTK) may be able to handle it. > > You could try doing the splitting and classifying yourself. If Telugu > uses > space-delimited words like English, you can do it easily: > > data = u"??? ??? ????" > words = data.split() Unicode characters for telugu: http://en.wikipedia.org/wiki/Telugu_alphabet#Unicode On python 3.x, >>> import re >>> a='??? ??? ????' >>> print(a) ??? ??? ???? >>> re.split('[^\u0c01-\u0c7f]', a) ['???', '???', '????'] Similar logic can be used for any other Indic script. HTH. -- ????? From arijit.ukil at tcs.com Thu Mar 21 11:42:05 2013 From: arijit.ukil at tcs.com (Arijit Ukil) Date: Thu, 21 Mar 2013 16:12:05 +0530 Subject: [Tutor] Please Help In-Reply-To: References: Message-ID: I am new to python. I like to calculate average of the numbers by reading the file 'digi_2.txt'. I have written the following code: def average(s): return sum(s) * 1.0 / len(s) f = open ("digi_2.txt", "r+") list_of_lists1 = f.readlines() for index in range(len(list_of_lists1)): tt = list_of_lists1[index] print 'Current value :', tt avg =average (tt) This gives an error: def average(s): return sum(s) * 1.0 / len(s) TypeError: unsupported operand type(s) for +: 'int' and 'str' I also attach the file i am reading. Please help to rectify. Regards, Arijit Ukil Tata Consultancy Services Mailto: arijit.ukil at tcs.com Website: http://www.tcs.com ____________________________________________ Experience certainty. IT Services Business Solutions Outsourcing ____________________________________________ From: Alan Gauld To: tutor at python.org Date: 03/21/2013 06:00 AM Subject: Re: [Tutor] Help Sent by: "Tutor" On 20/03/13 19:57, travis jeanfrancois wrote: > I create a function that allows the user to a create sentence by > inputing a string and to end the sentence with a period meaning > inputing "." .The problem is while keeps overwriting the previuos input 'While' does not do any such thing. Your code is doing that all by itself. What while does is repeat your code until a condition becomes false or you explicitly break out of the loop. > Here is my code: > > def B1(): Try to give your functions names that describe what they do. B1() is meaningless, readSentence() would be better. > period = "." > # The variable period is assigned Its normal programming practice to put the comment above the code not after it. Also comments should indicate why you are doing something not what you are doing - we can see that from the code. > first = input("Enter the first word in your sentence ") > next1 = input("Enter the next word in you sentence or enter period:") > # I need store the value so when while overwrites next1 with the next > input the previous input is stored and will print output when I call it > later along with last one > # I believe the solution is some how implenting this expression x = x+ > variable You could be right. Addition works for strings as well as numbers. Although there are other (better) options but you may not have covered them in your class yet. > while next1 != (period) : You don;t need the parentheses around period. Also nextWord might be a better name than next1. Saving 3 characters of typing is not usually worthwhile. > next1 = input("Enter the next word in you sentence or enter period:") Right, here you are overwriting next1. It's not the while's fault - it is just repeating your code. It is you who are overwriting the variable. Notice that you are not using the first that you captured? Maybe you should add next1 to first at some point? Then you can safely overwrite next1 as much as you like? > if next1 == (period): Again you don;t need the parentheses around period > next1 = next1 + period Here, you add the period to next1 which the 'if' has already established is now a period. > print ("Your sentence is:",first,next1,period) And now you print out the first word plus next1 (= 2 periods) plus a period = 3 periods in total... preceded by the phrase "Your sentence is:" This tells us that the sample output you posted is not from this program... Always match the program and the output when debugging or you will be led seriously astray! > PS : The" #" is I just type so I can understand what each line does The # is a comment marker. Comments are a very powerful tool that programmers use to explain to themselves and other programmers why they have done what they have. When trying to debug faults like this it is often worthwhile grabbing a pen and drawing a chart of your variables and their values after each time round the loop. In this case it would have looked like iteration period first next1 0 . I am 1 . I a 2 . I novice 3 . I .. If you aren't sure of the values insert a print statement and get the program to tell you, but working it out in your head is more likely to show you the error. HTH, -- Alan G 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 =====-----=====-----===== Notice: The information contained in this e-mail message and/or attachments to it may contain confidential or privileged information. If you are not the intended recipient, any dissemination, use, review, distribution, printing or copying of the information contained in this e-mail message and/or attachments to it are strictly prohibited. If you have received this communication in error, please notify us by reply e-mail or telephone and immediately and permanently delete the message and any attachments. Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: digi_2.txt URL: From svenito at gmail.com Thu Mar 21 11:58:56 2013 From: svenito at gmail.com (Sven) Date: Thu, 21 Mar 2013 10:58:56 +0000 Subject: [Tutor] Please Help In-Reply-To: References: Message-ID: Please trim unrelated text from emails. On 21 March 2013 10:42, Arijit Ukil wrote: > I am new to python. I like to calculate average of the numbers by reading > the file 'digi_2.txt'. I have written the following code: > > def average(s): return sum(s) * 1.0 / len(s) > > f = open ("digi_2.txt", "r+") > > list_of_lists1 = f.readlines() > > > for index in range(len(list_of_lists1)): > > > tt = list_of_lists1[index] > > print 'Current value :', tt > > avg =average (tt) > > > This gives an error: > > def average(s): return sum(s) * 1.0 / len(s) > TypeError: unsupported operand type(s) for +: 'int' and 'str' > tt is a string as it's read from the file. int(tt) would fix the problem. But in addition you're also not actually calculating the average. def average(s): return sum(s) / len(s) # convert the list of strings to a list of floats tt = [float(x) for x in list_of_lists1] avg = average(tt) -- ./Sven -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Thu Mar 21 12:54:50 2013 From: davea at davea.name (Dave Angel) Date: Thu, 21 Mar 2013 07:54:50 -0400 Subject: [Tutor] Please Help In-Reply-To: References: Message-ID: <514AF50A.5090309@davea.name> On 03/21/2013 06:42 AM, Arijit Ukil wrote: > I am new to python. Since you're new to Python, I won't try to supply you an answer using list comprehensions, since you've probably not learned them yet. > I like to calculate average of the numbers by reading > the file 'digi_2.txt'. I have written the following code: > > def average(s): return sum(s) * 1.0 / len(s) This function presumably expects to be passed a list (or iterable) of ints or a list of floats as its argument. It'll fail if given a list of strings. A comment or docstring to that effect would be useful to remind yourself. > > f = open ("digi_2.txt", "r+") Why is there a "plus sign" in the mode string? Not necessary, since you're just going to read the file straight through. > > list_of_lists1 = f.readlines() > Not a good name, since that's not what readlines() returns. It'll return a list of strings, each string representing one line of the file. > > for index in range(len(list_of_lists1)): Since your file is only one line long, this loop doesn't do much. > > > tt = list_of_lists1[index] > > print 'Current value :', tt > At this point, It is the string read from the last line of the file. The other lines are not represented in any way. > avg =average (tt) > > > This gives an error: > > def average(s): return sum(s) * 1.0 / len(s) > TypeError: unsupported operand type(s) for +: 'int' and 'str' > > I also attach the file i am reading. > You shouldn't assume everyone can read the "attached" data. Since it's short, you should just include it in your message. It's MUCH shorter than all the irrelevant data you included at the end of your message. For those others who may be reading this portion of the hijacked thread, here's the one line in digi_2.txt 1350696461, 448.0, 538660.0, 1350696466, 448.0 Now to try to solve the problem. First, you don't specify what the numbers in the file will look like. Looking at your code, I naturally assumed you had one value per line. Instead I see a single line with multiple numbers separated by commas. I'll assume that the data will always be in a single line, or that if there are multiple lines, every line but the last will end with a comma, and that the last one will NOT have a trailing comma. If I don't assume something, the problem can't be solved. Since we don't care about newlines, we can read the whole file into one string, with the read() function. f = open ("digi_2.txt", "r") filedata = f.read() f.close() Now we have to separate the data by the commas. numstsrings = filedata.split(",") And now we have to convert each of these "numstring" values from a string into a float. nums = [] for numstring in numstrings: nums.append(float(numstring)) Now we can call the average function, since we have a list of floats. avg = average(nums) Completely untested, so there may be typos in it. -- DaveA From amitsaha.in at gmail.com Thu Mar 21 12:59:16 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Thu, 21 Mar 2013 21:59:16 +1000 Subject: [Tutor] Please Help In-Reply-To: References: Message-ID: Hi Arijit, On Thu, Mar 21, 2013 at 8:42 PM, Arijit Ukil wrote: > > I am new to python. I like to calculate average of the numbers by reading > the file 'digi_2.txt'. I have written the following code: > > def average(s): return sum(s) * 1.0 / len(s) > > f = open ("digi_2.txt", "r+") > > list_of_lists1 = f.readlines() > > > for index in range(len(list_of_lists1)): > > > tt = list_of_lists1[index] > > print 'Current value :', tt > > avg =average (tt) > > > This gives an error: > > def average(s): return sum(s) * 1.0 / len(s) > TypeError: unsupported operand type(s) for +: 'int' and 'str' > > I also attach the file i am reading. > > > > Please help to rectify. The main issue here is that when you are reading from a file, to Python, its all strings. And although, 'abc' + 'def' is valid, 'abc' + 5 isn't (for example). Hence, besides the fact that your average calculation is not right, you will have to 'convert' the string to an integer/float to do any arithmetic operation on them. (If you know C, this is similar to typecasting). So, coming back to your program, I will first demonstrate you a few things and then you can write the program yourself. If you were to break down this program into simple steps, they would be: 1. Read the lines from a file (Assume a generic case, where you have more than one line in the file, and you have to calculate the average for each such row) 2. Create a list of floating point numbers for each of those lines 3. And call your average function on each of these lists You could of course do 2 & 3 together, so you create the list and call the average function. So, here is step 1: with open('digi.txt','r') as f: lines = f.readlines() Please refer to http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects for an explanation of the advantage of using 'with'. Now, you have *all* the lines of the file in 'lines'. Now, you want to perform step 2 for each line in this file. Here you go: for line in lines: number_list = [] for number in line.split(','): number_list.append(float(number)) (To learn more about Python lists, see http://effbot.org/zone/python-list.htm). It is certainly possible to use the index of an element to access elements from a list, but this is more Pythonic way of doing it. To understand this better, in the variable 'line', you will have a list of numbers on a single line. For example: 1350696461, 448.0, 538660.0, 1350696466, 448.0. Note how they are separated by a ',' ? To get each element, we use the split( ) function, which returns a list of the individual numbers. (See: http://docs.python.org/2/library/stdtypes.html#str.split). And then, we use the .append() method to create the list. Now, you have a number_list which is a list of floating point numbers for each line. Now, step 2 & 3 combined: for line in lines: number_list = [] for number in line.split(','): number_list.append(float(number)) print average(number_list) Where average( ) is defined as: def average(num_list): return sum(num_list)/len(num_list) There may be a number of unknown things I may have talked about, but i hope the links will help you learn more and write your program now. Good Luck. -Amit. -- http://amitsaha.github.com/ From davea at davea.name Thu Mar 21 13:48:54 2013 From: davea at davea.name (Dave Angel) Date: Thu, 21 Mar 2013 08:48:54 -0400 Subject: [Tutor] Please Help In-Reply-To: References: <514AF50A.5090309@davea.name> Message-ID: <514B01B6.8040605@davea.name> On 03/21/2013 08:09 AM, Arijit Ukil wrote: > Thanks for the help. > You're welcome. You replied privately, instead of including the list, so I'm forwarding the response so everyone can see it. You also top-posted, so the context is backwards. > After running your code, I am getting the following error: > > Traceback (most recent call last): > File "C:\Documents and Settings\207564\Desktop\Imp privacy analyzer\New > Folder\test\src\test.py", line 53, in ? > nums.append(float(numstsrings)) > TypeError: float() argument must be a string or a number > Check carefully, apparently the copy/paste on your machine inserts extra letters. -- DaveA From sydney.shall at kcl.ac.uk Thu Mar 21 14:43:02 2013 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Thu, 21 Mar 2013 13:43:02 +0000 Subject: [Tutor] Importing data from a file. Message-ID: <514B0E66.1020102@kcl.ac.uk> I have an elementary question provoked by another post today. 1. Is it the case that ALL imported data from a file is a string? 2. Does this therefor imply that said data has to be processed appropriately to generate the data in the form required by the program? 3. Are there defined procedures for doing the required processing? With many thanks, Sydney -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: From amitsaha.in at gmail.com Thu Mar 21 14:54:31 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Thu, 21 Mar 2013 23:54:31 +1000 Subject: [Tutor] Importing data from a file. In-Reply-To: <514B0E66.1020102@kcl.ac.uk> References: <514B0E66.1020102@kcl.ac.uk> Message-ID: On Thu, Mar 21, 2013 at 11:43 PM, Shall, Sydney wrote: > I have an elementary question provoked by another post today. > > 1. Is it the case that ALL imported data from a file is a string? > 2. Does this therefor imply that said data has to be processed appropriately > to generate the data in the form required by the program? To the best of my knowledge, yes to both of your queries. Once you have the element you want to process, you can make use of the type converting functions (int(), float().. ) and use them appropriately. > 3. Are there defined procedures for doing the required processing? If you meant conversion functions, int() and float() are examples of those. You of course (most of the times) have to make use of string manipulation functions (strip(), rstrip(), etc) to extract the exact data item you might be looking for. So, they would be the building blocks for your processing functions. I hope that makes some things clear. -Amit. -- http://amitsaha.github.com/ From sydney.shall at kcl.ac.uk Thu Mar 21 14:59:06 2013 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Thu, 21 Mar 2013 13:59:06 +0000 Subject: [Tutor] Importing data from a file. In-Reply-To: References: <514B0E66.1020102@kcl.ac.uk> Message-ID: <514B122A.4080807@kcl.ac.uk> On 21/03/2013 13:54, Amit Saha wrote: > On Thu, Mar 21, 2013 at 11:43 PM, Shall, Sydney wrote: >> I have an elementary question provoked by another post today. >> >> 1. Is it the case that ALL imported data from a file is a string? >> 2. Does this therefor imply that said data has to be processed appropriately >> to generate the data in the form required by the program? > To the best of my knowledge, yes to both of your queries. Once you > have the element you want to process, you can make use of the type > converting functions (int(), float().. ) and use them appropriately. > >> 3. Are there defined procedures for doing the required processing? > If you meant conversion functions, int() and float() are examples of > those. You of course (most of the times) have to make use of string > manipulation functions (strip(), rstrip(), etc) to extract the exact > data item you might be looking for. So, they would be the building > blocks for your processing functions. > > I hope that makes some things clear. > > -Amit. > Yes, Thanks. This is now quite clear. Sydney -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Thu Mar 21 15:03:45 2013 From: davea at davea.name (Dave Angel) Date: Thu, 21 Mar 2013 10:03:45 -0400 Subject: [Tutor] Importing data from a file. In-Reply-To: <514B0E66.1020102@kcl.ac.uk> References: <514B0E66.1020102@kcl.ac.uk> Message-ID: <514B1341.7080807@davea.name> On 03/21/2013 09:43 AM, Shall, Sydney wrote: > I have an elementary question provoked by another post today. > > 1. Is it the case that ALL imported data from a file is a string? No, the imported data is a module. For example import sys print type(sys) At this point, sys is a object of type module. Perhaps you really mean data returned by the readline() method of the file object. In that case, it's a list of strings. Or data returned from the readline() method of the file object. That is a string. Or data returned from the read() method of the file object. The return type of that depends on the version of Python. Be more specific, since the answer greatly depends on how you read this data. > 2. Does this therefor imply that said data has to be processed > appropriately to generate the data in the form required by the program? Again, you have to be specific. The program might well want exactly what one of these methods returns. > 3. Are there defined procedures for doing the required processing? > Sure, hundreds of thousands of them, most of them to be found in other people's programs. Sorry, but your questions are so vague as to defy definitive answers. -- DaveA From robert.sjoblom at gmail.com Thu Mar 21 15:03:58 2013 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Thu, 21 Mar 2013 15:03:58 +0100 Subject: [Tutor] Importing data from a file. In-Reply-To: References: <514B0E66.1020102@kcl.ac.uk> Message-ID: >> 3. Are there defined procedures for doing the required processing? > > If you meant conversion functions, int() and float() are examples of > those. You of course (most of the times) have to make use of string > manipulation functions (strip(), rstrip(), etc) to extract the exact > data item you might be looking for. Let's add the pickle module though. Pickle converts (most) Python objects into string representations, when you unpickle these string representations you get back your object. A dictionary object becomes a dictionary object and so on. Read more here: http://docs.python.org/3.3/library/pickle.html#module-pickle -- best regards, Robert S. From davea at davea.name Thu Mar 21 15:08:36 2013 From: davea at davea.name (Dave Angel) Date: Thu, 21 Mar 2013 10:08:36 -0400 Subject: [Tutor] Importing data from a file. In-Reply-To: <514B1341.7080807@davea.name> References: <514B0E66.1020102@kcl.ac.uk> <514B1341.7080807@davea.name> Message-ID: <514B1464.2050502@davea.name> On 03/21/2013 10:03 AM, Dave Angel wrote: A typo below; sorry. > On 03/21/2013 09:43 AM, Shall, Sydney wrote: >> I have an elementary question provoked by another post today. >> >> 1. Is it the case that ALL imported data from a file is a string? > > No, the imported data is a module. For example > import sys > print type(sys) > > > > > At this point, sys is a object of type module. > > Perhaps you really mean data returned by the readline() method of the Perhaps you really mean data returned by the readlines() method of the > file object. In that case, it's a list of strings. > > Or data returned from the readline() method of the file object. That is > a string. > > Or data returned from the read() method of the file object. The return > type of that depends on the version of Python. > > Be more specific, since the answer greatly depends on how you read this > data. > > >> 2. Does this therefor imply that said data has to be processed >> appropriately to generate the data in the form required by the program? > > Again, you have to be specific. The program might well want exactly > what one of these methods returns. > > >> 3. Are there defined procedures for doing the required processing? >> > > Sure, hundreds of thousands of them, most of them to be found in other > people's programs. > > Sorry, but your questions are so vague as to defy definitive answers. > > -- DaveA From alan.gauld at btinternet.com Thu Mar 21 17:17:28 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 21 Mar 2013 16:17:28 +0000 Subject: [Tutor] Importing data from a file. In-Reply-To: <514B0E66.1020102@kcl.ac.uk> References: <514B0E66.1020102@kcl.ac.uk> Message-ID: On 21/03/13 13:43, Shall, Sydney wrote: > I have an elementary question provoked by another post today. > > 1. Is it the case that ALL imported data from a file is a string? Assuming you mean data read from a file rather than modules imported using 'import' then the answer is 'it depends'. Most files are text files and the data is stored as strings and therefore when you read them back they will be strings. You then convert them to the native data using int(), float() etc. Some files are binary files and then the data read back will be bytes and need to be decoded into the original data. This is often done using the struct module. Either way if you use the Python read() operation on a file you will get back a bunch of bytes. What those bytes represent depends on how they were written. How they are interpreted is down to the programmer. > 2. Does this therefor imply that said data has to be processed > appropriately to generate the data in the form required by the program? Yes, always. > 3. Are there defined procedures for doing the required processing? Yes, for the standard types. For custom types and arbitrary binary data you need to find out what the original encoding was and reverse it. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sydney.shall at kcl.ac.uk Thu Mar 21 18:36:24 2013 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Thu, 21 Mar 2013 17:36:24 +0000 Subject: [Tutor] Importing data from a file. In-Reply-To: References: <514B0E66.1020102@kcl.ac.uk> Message-ID: <514B4518.2010404@kcl.ac.uk> On 21/03/2013 16:17, Alan Gauld wrote: > On 21/03/13 13:43, Shall, Sydney wrote: >> I have an elementary question provoked by another post today. >> >> 1. Is it the case that ALL imported data from a file is a string? > > Assuming you mean data read from a file rather than modules imported > using 'import' then the answer is 'it depends'. > > Most files are text files and the data is stored as strings and > therefore when you read them back they will be strings. You then > convert them to the native data using int(), float() etc. > > Some files are binary files and then the data read back will be bytes > and need to be decoded into the original data. This is often done > using the struct module. > > Either way if you use the Python read() operation on a file > you will get back a bunch of bytes. What those bytes represent depends > on how they were written. How they are interpreted is down to the > programmer. > > >> 2. Does this therefor imply that said data has to be processed >> appropriately to generate the data in the form required by the program? > > Yes, always. > >> 3. Are there defined procedures for doing the required processing? > > Yes, for the standard types. For custom types and arbitrary binary > data you need to find out what the original encoding was and reverse it. > > HTH, > Thank you Alan, That was most useful. Cheers, Sydney -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: From mcooganj at gmail.com Fri Mar 22 01:39:03 2013 From: mcooganj at gmail.com (Matthew Johnson) Date: Fri, 22 Mar 2013 08:39:03 +0800 Subject: [Tutor] Help with iterators Message-ID: <8437506927015511836@unknownmsgid> Dear list, I have been trying to understand out how to use iterators and in particular groupby statements. I am, however, quite lost. I wish to subset the below list, selecting the observations that have an ID ('realtime_start') value that is greater than some date (i've used the variable name maxDate), and in the case that there is more than one such record, returning only the one that has the largest ID ('realtime_start'). The code below does the job, however i have the impression that it might be done in a more python way using iterators and groupby statements. could someone please help me understand how to go from this code to the pythonic idiom? thanks in advance, Matt Johnson _________________ ## Code example import pprint obs = [{'date': '2012-09-01', 'realtime_end': '2013-02-18', 'realtime_start': '2012-10-15', 'value': '231.951'}, {'date': '2012-09-01', 'realtime_end': '2013-02-18', 'realtime_start': '2012-11-15', 'value': '231.881'}, {'date': '2012-10-01', 'realtime_end': '2013-02-18', 'realtime_start': '2012-11-15', 'value': '231.751'}, {'date': '2012-10-01', 'realtime_end': '9999-12-31', 'realtime_start': '2012-12-19', 'value': '231.623'}, {'date': '2013-02-01', 'realtime_end': '9999-12-31', 'realtime_start': '2013-03-21', 'value': '231.157'}, {'date': '2012-11-01', 'realtime_end': '2013-02-18', 'realtime_start': '2012-12-14', 'value': '231.025'}, {'date': '2012-11-01', 'realtime_end': '9999-12-31', 'realtime_start': '2013-01-19', 'value': '231.071'}, {'date': '2012-12-01', 'realtime_end': '2013-02-18', 'realtime_start': '2013-01-16', 'value': '230.979'}, {'date': '2012-12-01', 'realtime_end': '9999-12-31', 'realtime_start': '2013-02-19', 'value': '231.137'}, {'date': '2012-12-01', 'realtime_end': '9999-12-31', 'realtime_start': '2013-03-19', 'value': '231.197'}, {'date': '2013-01-01', 'realtime_end': '9999-12-31', 'realtime_start': '2013-02-21', 'value': '231.198'}, {'date': '2013-01-01', 'realtime_end': '9999-12-31', 'realtime_start': '2013-03-21', 'value': '231.222'}] maxDate = "2013-03-21" dobs = dict([(d, []) for d in set([e['date'] for e in obs])]) for o in obs: dobs[o['date']].append(o) dobs_subMax = dict([(k, [d for d in v if d['realtime_start'] <= maxDate]) for k, v in dobs.items()]) rts = lambda x: x['realtime_start'] mmax = [sorted(e, key=rts)[-1] for e in dobs_subMax.values() if e] mmax.sort(key = lambda x: x['date']) pprint.pprint(mmax) From msirenef at lightbird.net Fri Mar 22 02:39:12 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Thu, 21 Mar 2013 21:39:12 -0400 Subject: [Tutor] Help with iterators In-Reply-To: <8437506927015511836@unknownmsgid> References: <8437506927015511836@unknownmsgid> Message-ID: <514BB640.5050406@lightbird.net> On 03/21/2013 08:39 PM, Matthew Johnson wrote: > Dear list, > > I have been trying to understand out how to use iterators and in > particular groupby statements. I am, however, quite lost. > > I wish to subset the below list, selecting the observations that have > an ID ('realtime_start') value that is greater than some date (i've > used the variable name maxDate), and in the case that there is more > than one such record, returning only the one that has the largest ID > ('realtime_start'). > > The code below does the job, however i have the impression that it > might be done in a more python way using iterators and groupby > statements. > > could someone please help me understand how to go from this code to > the pythonic idiom? > > thanks in advance, > > Matt Johnson > > _________________ > > ## Code example > > import pprint > > obs = [{'date': '2012-09-01', > 'realtime_end': '2013-02-18', > 'realtime_start': '2012-10-15', > 'value': '231.951'}, > {'date': '2012-09-01', > 'realtime_end': '2013-02-18', > 'realtime_start': '2012-11-15', > 'value': '231.881'}, > {'date': '2012-10-01', > 'realtime_end': '2013-02-18', > 'realtime_start': '2012-11-15', > 'value': '231.751'}, > {'date': '2012-10-01', > 'realtime_end': '9999-12-31', > 'realtime_start': '2012-12-19', > 'value': '231.623'}, > {'date': '2013-02-01', > 'realtime_end': '9999-12-31', > 'realtime_start': '2013-03-21', > 'value': '231.157'}, > {'date': '2012-11-01', > 'realtime_end': '2013-02-18', > 'realtime_start': '2012-12-14', > 'value': '231.025'}, > {'date': '2012-11-01', > 'realtime_end': '9999-12-31', > 'realtime_start': '2013-01-19', > 'value': '231.071'}, > {'date': '2012-12-01', > 'realtime_end': '2013-02-18', > 'realtime_start': '2013-01-16', > 'value': '230.979'}, > {'date': '2012-12-01', > 'realtime_end': '9999-12-31', > 'realtime_start': '2013-02-19', > 'value': '231.137'}, > {'date': '2012-12-01', > 'realtime_end': '9999-12-31', > 'realtime_start': '2013-03-19', > 'value': '231.197'}, > {'date': '2013-01-01', > 'realtime_end': '9999-12-31', > 'realtime_start': '2013-02-21', > 'value': '231.198'}, > {'date': '2013-01-01', > 'realtime_end': '9999-12-31', > 'realtime_start': '2013-03-21', > 'value': '231.222'}] > > maxDate = "2013-03-21" > > dobs = dict([(d, []) for d in set([e['date'] for e in obs])]) > > for o in obs: > dobs[o['date']].append(o) > > dobs_subMax = dict([(k, [d for d in v if d['realtime_start'] <= maxDate]) > for k, v in dobs.items()]) > > rts = lambda x: x['realtime_start'] > > mmax = [sorted(e, key=rts)[-1] for e in dobs_subMax.values() if e] > > mmax.sort(key = lambda x: x['date']) > > pprint.pprint(mmax) > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > You can do it with groupby like so: from itertools import groupby from operator import itemgetter maxDate = "2013-03-21" mmax = list() obs.sort(key=itemgetter('date')) for k, group in groupby(obs, key=itemgetter('date')): group = [dob for dob in group if dob['realtime_start'] <= maxDate] if group: group.sort(key=itemgetter('realtime_start')) mmax.append(group[-1]) pprint.pprint(mmax) Note that writing multiply-nested comprehensions like you did results in very unreadable code. Do you find this code more readable? -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Many a man fails as an original thinker simply because his memory it too good. Friedrich Nietzsche From steve at pearwood.info Fri Mar 22 03:05:38 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 22 Mar 2013 13:05:38 +1100 Subject: [Tutor] Help with iterators In-Reply-To: <8437506927015511836@unknownmsgid> References: <8437506927015511836@unknownmsgid> Message-ID: <514BBC72.8040802@pearwood.info> On 22/03/13 11:39, Matthew Johnson wrote: > Dear list, > > I have been trying to understand out how to use iterators and in > particular groupby statements. I am, however, quite lost. groupby is a very specialist function which is not very intuitive to use. Sometimes I think that groupby is an excellent solution in search of a problem. > I wish to subset the below list, selecting the observations that have > an ID ('realtime_start') value that is greater than some date (i've > used the variable name maxDate), and in the case that there is more > than one such record, returning only the one that has the largest ID > ('realtime_start'). The code that you show does not so what you describe here. The most obvious difference is that it doesn't return or display a single record, but shows multiple records. In your case, it selects six records, four of which have a realtime_start that occurs BEFORE the given maxDate. To solve the problem you describe here, of finding at most a single record, the solution is much simpler than what you have done. Prepare a list of observations, sorted by realtime_start. Take the latest such observation. If the realtime_start is greater than the maxDate, you have your answer. If not, there is no answer. The simplest solution is usually the best. The simpler your code, the fewer bugs it will contain. obs.sort(key=lambda rec: rec['realtime_start']) rec = obs[-1] if rec['realtime_start'] > maxDate: print rec else: print "no record found" which prints: {'date': '2013-01-01', 'realtime_start': '2013-03-21', 'realtime_end': '9999-12-31', 'value': '231.222'} -- Steven From steve at pearwood.info Fri Mar 22 03:20:09 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 22 Mar 2013 13:20:09 +1100 Subject: [Tutor] Help with iterators In-Reply-To: <514BB640.5050406@lightbird.net> References: <8437506927015511836@unknownmsgid> <514BB640.5050406@lightbird.net> Message-ID: <514BBFD9.3090801@pearwood.info> On 22/03/13 12:39, Mitya Sirenef wrote: > You can do it with groupby like so: > > > from itertools import groupby > from operator import itemgetter > > maxDate = "2013-03-21" > mmax = list() > > obs.sort(key=itemgetter('date')) > > for k, group in groupby(obs, key=itemgetter('date')): > group = [dob for dob in group if dob['realtime_start'] <= maxDate] > if group: > group.sort(key=itemgetter('realtime_start')) > mmax.append(group[-1]) > > pprint.pprint(mmax) This suffers from the same problem of finding six records instead of one, and that four of the six have start dates before the given date instead of after it. Here's another solution that finds all the records that start on or after the given data (the poorly named "maxDate") and displays them sorted by date. selected = [rec for rec in obs if rec['realtime_start'] >= maxDate] selected.sort(key=lambda rec: rec['date']) print selected -- Steven From msirenef at lightbird.net Fri Mar 22 03:31:53 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Thu, 21 Mar 2013 22:31:53 -0400 Subject: [Tutor] Help with iterators In-Reply-To: <514BBFD9.3090801@pearwood.info> References: <8437506927015511836@unknownmsgid> <514BB640.5050406@lightbird.net> <514BBFD9.3090801@pearwood.info> Message-ID: <514BC299.1070600@lightbird.net> On 03/21/2013 10:20 PM, Steven D'Aprano wrote: > On 22/03/13 12:39, Mitya Sirenef wrote: > >> You can do it with groupby like so: >> >> >> from itertools import groupby >> from operator import itemgetter >> >> maxDate = "2013-03-21" >> mmax = list() >> >> obs.sort(key=itemgetter('date')) >> >> for k, group in groupby(obs, key=itemgetter('date')): >> group = [dob for dob in group if dob['realtime_start'] <= maxDate] >> if group: >> group.sort(key=itemgetter('realtime_start')) >> mmax.append(group[-1]) >> >> pprint.pprint(mmax) > > > This suffers from the same problem of finding six records instead of one, > and that four of the six have start dates before the given date instead > of after it. OP said his code produces the needed result and I think his description probably doesn't match what he really intends to do (he also said he wants the same code rewritten using groupby). I reproduced the logic of his code... hopefully he can step in and clarify! > > Here's another solution that finds all the records that start on or after > the given data (the poorly named "maxDate") and displays them sorted by > date. > > > selected = [rec for rec in obs if rec['realtime_start'] >= maxDate] > selected.sort(key=lambda rec: rec['date']) > print selected > > > > -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ A little bad taste is like a nice dash of paprika. Dorothy Parker From arijit.ukil at tcs.com Fri Mar 22 08:24:01 2013 From: arijit.ukil at tcs.com (Arijit Ukil) Date: Fri, 22 Mar 2013 12:54:01 +0530 Subject: [Tutor] Please Help In-Reply-To: References: Message-ID: Hi, I have another small problem. Pls help. I have written the following code: f = open ("digi_2.txt", "r+") lines = f.readlines() for line in lines: number_list = [] for number in line.split(','): number_list.append(float(number)) s_data = [] for i in range(len(number_list)): if number_list[i] > 5: s_data = number_list[i] print 'Data val:', s_data The problem is: it is printing only the last value, not all the values. In this case '10', not '9,8,6,10'. Regards, Arijit Ukil Tata Consultancy Services Mailto: arijit.ukil at tcs.com Website: http://www.tcs.com ____________________________________________ Experience certainty. IT Services Business Solutions Outsourcing ____________________________________________ From: Amit Saha To: Arijit Ukil Cc: tutor at python.org Date: 03/21/2013 05:30 PM Subject: Re: [Tutor] Please Help Hi Arijit, On Thu, Mar 21, 2013 at 8:42 PM, Arijit Ukil wrote: > > I am new to python. I like to calculate average of the numbers by reading > the file 'digi_2.txt'. I have written the following code: > > def average(s): return sum(s) * 1.0 / len(s) > > f = open ("digi_2.txt", "r+") > > list_of_lists1 = f.readlines() > > > for index in range(len(list_of_lists1)): > > > tt = list_of_lists1[index] > > print 'Current value :', tt > > avg =average (tt) > > > This gives an error: > > def average(s): return sum(s) * 1.0 / len(s) > TypeError: unsupported operand type(s) for +: 'int' and 'str' > > I also attach the file i am reading. > > > > Please help to rectify. The main issue here is that when you are reading from a file, to Python, its all strings. And although, 'abc' + 'def' is valid, 'abc' + 5 isn't (for example). Hence, besides the fact that your average calculation is not right, you will have to 'convert' the string to an integer/float to do any arithmetic operation on them. (If you know C, this is similar to typecasting). So, coming back to your program, I will first demonstrate you a few things and then you can write the program yourself. If you were to break down this program into simple steps, they would be: 1. Read the lines from a file (Assume a generic case, where you have more than one line in the file, and you have to calculate the average for each such row) 2. Create a list of floating point numbers for each of those lines 3. And call your average function on each of these lists You could of course do 2 & 3 together, so you create the list and call the average function. So, here is step 1: with open('digi.txt','r') as f: lines = f.readlines() Please refer to http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects for an explanation of the advantage of using 'with'. Now, you have *all* the lines of the file in 'lines'. Now, you want to perform step 2 for each line in this file. Here you go: for line in lines: number_list = [] for number in line.split(','): number_list.append(float(number)) (To learn more about Python lists, see http://effbot.org/zone/python-list.htm). It is certainly possible to use the index of an element to access elements from a list, but this is more Pythonic way of doing it. To understand this better, in the variable 'line', you will have a list of numbers on a single line. For example: 1350696461, 448.0, 538660.0, 1350696466, 448.0. Note how they are separated by a ',' ? To get each element, we use the split( ) function, which returns a list of the individual numbers. (See: http://docs.python.org/2/library/stdtypes.html#str.split). And then, we use the .append() method to create the list. Now, you have a number_list which is a list of floating point numbers for each line. Now, step 2 & 3 combined: for line in lines: number_list = [] for number in line.split(','): number_list.append(float(number)) print average(number_list) Where average( ) is defined as: def average(num_list): return sum(num_list)/len(num_list) There may be a number of unknown things I may have talked about, but i hope the links will help you learn more and write your program now. Good Luck. -Amit. -- http://amitsaha.github.com/ =====-----=====-----===== Notice: The information contained in this e-mail message and/or attachments to it may contain confidential or privileged information. If you are not the intended recipient, any dissemination, use, review, distribution, printing or copying of the information contained in this e-mail message and/or attachments to it are strictly prohibited. If you have received this communication in error, please notify us by reply e-mail or telephone and immediately and permanently delete the message and any attachments. Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: digi_2.txt URL: From suhasbhairav at hotmail.com Fri Mar 22 08:48:39 2013 From: suhasbhairav at hotmail.com (suhas bhairav) Date: Fri, 22 Mar 2013 13:18:39 +0530 Subject: [Tutor] Please Help In-Reply-To: References: , , , , Message-ID: Hi Arijit, I have modified your program a bit and it is working fine for me. Values greater than 5 are being printed. Here is the code: f = open ("D:\\digi_2.txt", "r+") lines = f.readlines() number_list = [] for line in lines: print line for number in line.split(','): #number_list.append(float(number)) number_list.append(int(number)) s_data = [] for i in number_list: print i #if number_list[i] > 5: if(i>5): s_data.append(i) for x in s_data: print 'Data val:', float(x) RegardsSuhas To: tutor at python.org From: arijit.ukil at tcs.com Date: Fri, 22 Mar 2013 12:54:01 +0530 Subject: [Tutor] Please Help Hi, I have another small problem. Pls help. I have written the following code: f = open ("digi_2.txt", "r+") lines = f.readlines() for line in lines: number_list = [] for number in line.split(','): number_list.append(float(number)) s_data = [] for i in range(len(number_list)): if number_list[i] > 5: s_data = number_list[i] print 'Data val:', s_data The problem is: it is printing only the last value, not all the values. In this case '10', not '9,8,6,10'. Regards, Arijit Ukil Tata Consultancy Services Mailto: arijit.ukil at tcs.com Website: http://www.tcs.com ____________________________________________ Experience certainty. IT Services Business Solutions Outsourcing ____________________________________________ From: Amit Saha To: Arijit Ukil Cc: tutor at python.org Date: 03/21/2013 05:30 PM Subject: Re: [Tutor] Please Help Hi Arijit, On Thu, Mar 21, 2013 at 8:42 PM, Arijit Ukil wrote: > > I am new to python. I like to calculate average of the numbers by reading > the file 'digi_2.txt'. I have written the following code: > > def average(s): return sum(s) * 1.0 / len(s) > > f = open ("digi_2.txt", "r+") > > list_of_lists1 = f.readlines() > > > for index in range(len(list_of_lists1)): > > > tt = list_of_lists1[index] > > print 'Current value :', tt > > avg =average (tt) > > > This gives an error: > > def average(s): return sum(s) * 1.0 / len(s) > TypeError: unsupported operand type(s) for +: 'int' and 'str' > > I also attach the file i am reading. > > > > Please help to rectify. The main issue here is that when you are reading from a file, to Python, its all strings. And although, 'abc' + 'def' is valid, 'abc' + 5 isn't (for example). Hence, besides the fact that your average calculation is not right, you will have to 'convert' the string to an integer/float to do any arithmetic operation on them. (If you know C, this is similar to typecasting). So, coming back to your program, I will first demonstrate you a few things and then you can write the program yourself. If you were to break down this program into simple steps, they would be: 1. Read the lines from a file (Assume a generic case, where you have more than one line in the file, and you have to calculate the average for each such row) 2. Create a list of floating point numbers for each of those lines 3. And call your average function on each of these lists You could of course do 2 & 3 together, so you create the list and call the average function. So, here is step 1: with open('digi.txt','r') as f: lines = f.readlines() Please refer to http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects for an explanation of the advantage of using 'with'. Now, you have *all* the lines of the file in 'lines'. Now, you want to perform step 2 for each line in this file. Here you go: for line in lines: number_list = [] for number in line.split(','): number_list.append(float(number)) (To learn more about Python lists, see http://effbot.org/zone/python-list.htm). It is certainly possible to use the index of an element to access elements from a list, but this is more Pythonic way of doing it. To understand this better, in the variable 'line', you will have a list of numbers on a single line. For example: 1350696461, 448.0, 538660.0, 1350696466, 448.0. Note how they are separated by a ',' ? To get each element, we use the split( ) function, which returns a list of the individual numbers. (See: http://docs.python.org/2/library/stdtypes.html#str.split). And then, we use the .append() method to create the list. Now, you have a number_list which is a list of floating point numbers for each line. Now, step 2 & 3 combined: for line in lines: number_list = [] for number in line.split(','): number_list.append(float(number)) print average(number_list) Where average( ) is defined as: def average(num_list): return sum(num_list)/len(num_list) There may be a number of unknown things I may have talked about, but i hope the links will help you learn more and write your program now. Good Luck. -Amit. -- http://amitsaha.github.com/ =====-----=====-----===== Notice: The information contained in this e-mail message and/or attachments to it may contain confidential or privileged information. If you are not the intended recipient, any dissemination, use, review, distribution, printing or copying of the information contained in this e-mail message and/or attachments to it are strictly prohibited. If you have received this communication in error, please notify us by reply e-mail or telephone and immediately and permanently delete the message and any attachments. Thank you _______________________________________________ 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 Fri Mar 22 09:56:43 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 22 Mar 2013 08:56:43 +0000 Subject: [Tutor] Please Help In-Reply-To: References: Message-ID: On 22/03/13 07:24, Arijit Ukil wrote: > f = open ("digi_2.txt", "r+") > lines = f.readlines() > for line in lines: > number_list = [] > for number in line.split(','): > number_list.append(float(number)) > > s_data = [] > for i in range(len(number_list)): You hardly ever need to do this, its much simpler to just iterate over the list items directly: for number in number_list: > if number_list[i] > 5: > s_data = number_list[i] Note that you are overwriting your list with a single value. You need to do what you did above and use append(). > *The problem is: it is printing only the last value, not all the values. > In this case '10', **not**'9,8,6,10'.* Because you overwrote the list each time. You need to remember to append data to lists not replace the list. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From miguel.guasch at hushmail.com Fri Mar 22 10:02:38 2013 From: miguel.guasch at hushmail.com (miguel.guasch at hushmail.com) Date: Fri, 22 Mar 2013 10:02:38 +0100 Subject: [Tutor] Starting a simple python project Message-ID: <20130322090238.B48AF6F443@smtp.hushmail.com> Greetings all! My name is Miguel Guasch, I'm a software tester who's trying to slowly get into automation, and eventually (in a couple of years) into development. For that, I need to learn. At the moment I'm studying computer engineering in the evenings, and we do a lot of work in C and assembly. Java will be coming at some time, but not for the moment. So I decided to learn python as a side project, so I could get my feet wet with OOP and start actually being productive. I understand the basics of OOP thanks to a class I took about object modelling and design (UML on Enterprise Architect) In order to better learn python, I'm trying to "automate" (or make it easier to do) repetitive tasks here in the company. Like, for example: We have to write a daily "status" e-mail of our tasks, divided into: planned for tomorrow, open tasks, finished tasks, general findings. I thought I could take it upon me to write a small program to, instead of writing these e-mails at the end of the day, we could just have the program open, and, as soon as we start working on a task, we enter it, and before we close it, we can write "general findings" to it. It would work like this in the beginning: Open the program, import a new template, write the open tasks you have (and any you receive during the day), and then start working on a certain task. While working on the task, you can write a "general findings" entry to it, and when you're done, you "close it" (meaning, you open the next one). The tasks have specific ID numbers based on our ClearQuest entry numbers, so it would be easy to match the open and finished tasks, and substact the finished from the done ones. At the end of the day, you can click on "end" and it would generate a simple text file with a very simple formatting, like: Planned for tomorrow: 1. 2.. And the same with the others. We could then just copy the text files contents and paste them into a regular outlook e-mail This is a simple start, but in the future I'd like to be able to store these tasks in a folder and name the text files with the days date, so I can "import" them back in case I need to look at it. I'd also like to make a small dictionary with the names and e-mail addresses of the people who should receive the e-mail, and somehow either copy the text into an outlook e-mail, or directly send it over SMTP (whichever is simpler) I'm having a hard time actually starting, but so far I have a basic idea and it shouldn't be too hard. I'm planning to use wxPython on Windows 7 because it looks pretty simple so far and it also looks elegant enough :-) If you guys/gals could comment on this, or give me some kind of advice, I'd be more than thankful. I'll be sure to let you know how it goes, and share the source. Thanks, everyone! All the best! Miguel A. Guasch miguel.guasch at hushmail.com From arijit.ukil at tcs.com Fri Mar 22 13:37:14 2013 From: arijit.ukil at tcs.com (Arijit Ukil) Date: Fri, 22 Mar 2013 18:07:14 +0530 Subject: [Tutor] Please Help In-Reply-To: References: Message-ID: I have the following data points. data = [1,2,0,9,0,1,4] I like to store in an array and print the odd-indexed points, i.e. 2, 9,1 (considering index starts at 0) I have written the following code which is not running: import math number_list = [1,2,0,9,0,1,4] number_list_1 = [] for k in range(math.floor(float(len(number_list)/2))): if (k< math.floor(float(len(number_list)/2))): number_list_1[k] = number_list[k*2 + 1] print 'data: ', number_list_1 Please help Regards, Arijit Ukil Tata Consultancy Services Mailto: arijit.ukil at tcs.com Website: http://www.tcs.com ____________________________________________ Experience certainty. IT Services Business Solutions Outsourcing ____________________________________________ =====-----=====-----===== Notice: The information contained in this e-mail message and/or attachments to it may contain confidential or privileged information. If you are not the intended recipient, any dissemination, use, review, distribution, printing or copying of the information contained in this e-mail message and/or attachments to it are strictly prohibited. If you have received this communication in error, please notify us by reply e-mail or telephone and immediately and permanently delete the message and any attachments. Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From andipersti at gmail.com Fri Mar 22 14:14:43 2013 From: andipersti at gmail.com (Andreas Perstinger) Date: Fri, 22 Mar 2013 14:14:43 +0100 Subject: [Tutor] Please Help In-Reply-To: References: Message-ID: <514C5943.5030704@gmail.com> Please use a meaningful subject. On 22.03.2013 13:37, Arijit Ukil wrote: > I have the following data points. > data = [1,2,0,9,0,1,4] > I like to store in an array and print the odd-indexed points, i.e. 2, 9,1 > (considering index starts at 0) You can simply slice your list: >>> data = [1, 2, 0, 9, 0, 1, 4] >>> number_list = data[1::2] >>> number_list [2, 9, 1] See also http://docs.python.org/3/library/stdtypes.html#common-sequence-operations Bye, Andreas From pasokan at talentsprint.com Fri Mar 22 14:34:09 2013 From: pasokan at talentsprint.com (Asokan Pichai) Date: Fri, 22 Mar 2013 19:04:09 +0530 Subject: [Tutor] Please Help In-Reply-To: References: Message-ID: On Fri, Mar 22, 2013 at 6:07 PM, Arijit Ukil wrote: > I have the following data points. > data = [1,2,0,9,0,1,4] > I like to store in an array and print the odd-indexed points, i.e. 2, 9,1 > (considering index starts at 0) > > *I have written the following code which is** not **running:* > > import math > > number_list = [1,2,0,9,0,1,4] > > number_list_1 = [] > for k in range(math.floor(float(len(number_list)/2))): > if (k< math.floor(float(len(number_list)/2))): > number_list_1[k] = number_list[k*2 + 1] > > print *'data: '*, number_list_1 > > Please help > > Regards, > I would suggest that your roblems have more to do with insufficient understanding of basic constructs, and that you should work on them, "Learn Python the hard way" a book by Zed Shaw is a good one. Why do I say that? Among other things, k< math.floor(float(len(number_list)/2)) is very poor in any language. Asokan Pichai The root of all superstition is that men observe when a thing hits, but not when it misses. -- Francis Bacon -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at linux-ip.net Fri Mar 22 14:33:50 2013 From: martin at linux-ip.net (Martin A. Brown) Date: Fri, 22 Mar 2013 09:33:50 -0400 Subject: [Tutor] Please Help In-Reply-To: References: Message-ID: Greetings, : I have the following data points. : data = [1,2,0,9,0,1,4] : I like to store in an array and print the odd-indexed points, i.e. 2, 9,1 : (considering index starts at 0) : : I have written the following code which is not running: : : import math : : number_list = [1,2,0,9,0,1,4] : : number_list_1 = [] : for k in range(math.floor(float(len(number_list)/2))): : if (k< math.floor(float(len(number_list)/2))): : number_list_1[k] = number_list[k*2 + 1] : : print 'data: ', number_list_1 My first thought when I see the above is that you appear to be taking a circuitous route to the market! You must really want to get your exercise on your journey to fetch the list of [2, 9, 1]. My second observation is that the looping over a list using the technique you showed here (and in your prior mail) is something that looks more like C or Java. Looping on an list (array, or any sort of sequence) is a bit easier here in the lands of Python. You can simply: for item in list_data: # -- do something with item Since you are in the lands of Python (and welcome, by the way), the Python docs are pretty good (and not overwhelming), and include some excellent examples, so try reading about sequences and how to manipulate them at this online doc: http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange Anyway, I think you may benefit from seeing this solution a bit more Pythonically, so I have offered two different solutions. -Martin data = number_list = [1,2,0,9,0,1,4] # -- you call it 'number_list_1'; I will call it 'outlist' # outlist = [] for idx,val in enumerate(data): print idx, val if 0 == (idx % 2): # -- skip even entries; do not append continue outlist.append(val) print 'loop over enumerate() to get your data: ', outlist # -- OR, given how simple your operation on the list is, consider # learning about slicing; see the standard docs on sequences: # # http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange # print 'slice out from your original data: ', data[1::2] -- Martin A. Brown http://linux-ip.net/ From bgailer at gmail.com Fri Mar 22 18:17:26 2013 From: bgailer at gmail.com (bob gailer) Date: Fri, 22 Mar 2013 13:17:26 -0400 Subject: [Tutor] Starting a simple python project In-Reply-To: <20130322090238.B48AF6F443@smtp.hushmail.com> References: <20130322090238.B48AF6F443@smtp.hushmail.com> Message-ID: <514C9226.3070708@gmail.com> On 3/22/2013 5:02 AM, miguel.guasch at hushmail.com wrote: > Greetings all! Hi. > I decided to learn python as a side project, so > I could get my feet wet with OOP and start actually being > productive. I understand the basics of OOP thanks to a class I took > about object modelling and design (UML on Enterprise Architect) > > In order to better learn python, I'm trying to "automate" (or make > it easier to do) repetitive tasks here in the company. IMHO this is not a simple project. I suggest you start with something a lot simpler so you can focus on learning Python rather than all the complexities involved in the daily "status" e-mail project (which includes learning wxPython). When you do tackle daily "status" e-mail - start with one step. A good starting point is to clarify the project (expand the description, be very specific, draw pictures of the user interface, ...) Have you gone through any Python tutorials? Might be a good idea. Personally I'd tackle a task like thhis using Access rather than Python. > Like, for example: > > We have to write a daily "status" e-mail of our tasks, divided > into: planned for tomorrow, open tasks, finished tasks, general > findings. > > I thought I could take it upon me to write a small program to, > instead of writing these e-mails at the end of the day, we could > just have the program open, and, as soon as we start working on a > task, we enter it, and before we close it, we can write "general > findings" to it. > > It would work like this in the beginning: Open the program, import > a new template, write the open tasks you have (and any you receive > during the day), and then start working on a certain task. While > working on the task, you can write a "general findings" entry to > it, and when you're done, you "close it" (meaning, you open the > next one). The tasks have specific ID numbers based on our > ClearQuest entry numbers, so it would be easy to match the open and > finished tasks, and substact the finished from the done ones. > > At the end of the day, you can click on "end" and it would generate > a simple text file with a very simple formatting, like: > > Planned for tomorrow: > 1. > 2.. > > And the same with the others. > > We could then just copy the text files contents and paste them into > a regular outlook e-mail > > This is a simple start, but in the future I'd like to be able to > store these tasks in a folder and name the text files with the days > date, so I can "import" them back in case I need to look at it. > I'd also like to make a small dictionary with the names and e-mail > addresses of the people who should receive the e-mail, and somehow > either copy the text into an outlook e-mail, or directly send it > over SMTP (whichever is simpler) > > > I'm having a hard time actually starting, but so far I have a basic > idea and it shouldn't be too hard. > > I'm planning to use wxPython on Windows 7 because it looks pretty > simple so far and it also looks elegant enough :-) > > > If you guys/gals could comment on this, or give me some kind of > advice, I'd be more than thankful. I'll be sure to let you know how > it goes, and share the source. > > > Thanks, everyone! > > All the best! > > Miguel A. Guasch > miguel.guasch at hushmail.com > > _______________________________________________ > 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 msirenef at lightbird.net Sat Mar 23 01:09:28 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Fri, 22 Mar 2013 20:09:28 -0400 Subject: [Tutor] Starting a simple python project In-Reply-To: <20130322090238.B48AF6F443@smtp.hushmail.com> References: <20130322090238.B48AF6F443@smtp.hushmail.com> Message-ID: <514CF2B8.6060401@lightbird.net> On 03/22/2013 05:02 AM, miguel.guasch at hushmail.com wrote: > Greetings all! > > > My name is Miguel Guasch, I'm a software tester who's trying to > slowly get into automation, and eventually (in a couple of years) > into development. For that, I need to learn. At the moment I'm > studying computer engineering in the evenings, and we do a lot of > work in C and assembly. Java will be coming at some time, but not > for the moment. So I decided to learn python as a side project, so > I could get my feet wet with OOP and start actually being > productive. I understand the basics of OOP thanks to a class I took > about object modelling and design (UML on Enterprise Architect) > > In order to better learn python, I'm trying to "automate" (or make > it easier to do) repetitive tasks here in the company. > > Like, for example: > > We have to write a daily "status" e-mail of our tasks, divided > into: planned for tomorrow, open tasks, finished tasks, general > findings. > > I thought I could take it upon me to write a small program to, > instead of writing these e-mails at the end of the day, we could > just have the program open, and, as soon as we start working on a > task, we enter it, and before we close it, we can write "general > findings" to it. > > It would work like this in the beginning: Open the program, import > a new template, write the open tasks you have (and any you receive > during the day), and then start working on a certain task. While > working on the task, you can write a "general findings" entry to > it, and when you're done, you "close it" (meaning, you open the > next one). The tasks have specific ID numbers based on our > ClearQuest entry numbers, so it would be easy to match the open and > finished tasks, and substact the finished from the done ones. > > At the end of the day, you can click on "end" and it would generate > a simple text file with a very simple formatting, like: > > Planned for tomorrow: > 1. > 2.. > > And the same with the others. > > We could then just copy the text files contents and paste them into > a regular outlook e-mail > > This is a simple start, but in the future I'd like to be able to > store these tasks in a folder and name the text files with the days > date, so I can "import" them back in case I need to look at it. > I'd also like to make a small dictionary with the names and e-mail > addresses of the people who should receive the e-mail, and somehow > either copy the text into an outlook e-mail, or directly send it > over SMTP (whichever is simpler) > > > I'm having a hard time actually starting, but so far I have a basic > idea and it shouldn't be too hard. > > I'm planning to use wxPython on Windows 7 because it looks pretty > simple so far and it also looks elegant enough :-) > > > If you guys/gals could comment on this, or give me some kind of > advice, I'd be more than thankful. I'll be sure to let you know how > it goes, and share the source. > > > Thanks, everyone! > > All the best! > > Miguel A. Guasch > miguel.guasch at hushmail.com > > It might be a good idea to first implement this as a command-line script and then consider moving to a gui; note that Tkinter is quite a bit easier than wxPython. (and in recent years it was updated to look nicer than it used to). -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Frisbeetarianism is the belief that when you die, your soul goes up on the roof and gets stuck. George Carlin From phil_lor at bigpond.com Sat Mar 23 02:48:12 2013 From: phil_lor at bigpond.com (Phil) Date: Sat, 23 Mar 2013 11:48:12 +1000 Subject: [Tutor] Beep sound Message-ID: <514D09DC.60006@bigpond.com> Just out of curiosity how can a beep sound be generated? My interest in this came about because echo -e '\a' no longer works. Also print '\a' doesn't work, presumably for the same reason. The following is also mute: import Tkinter Tkinter.Tk().bell() Print '\a', under Idle, causes a bell icon to be displayed so it seems that the lack of a beep is due to a system setting. A Google search has shown several methods to play .wav files, some easier than others. Perhaps Pulse Audio has made '\a' redundant? -- Regards, Phil From steve at pearwood.info Sat Mar 23 03:17:43 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 23 Mar 2013 13:17:43 +1100 Subject: [Tutor] Beep sound In-Reply-To: <514D09DC.60006@bigpond.com> References: <514D09DC.60006@bigpond.com> Message-ID: <514D10C7.9090405@pearwood.info> On 23/03/13 12:48, Phil wrote: > Just out of curiosity how can a beep sound be generated? > > My interest in this came about because echo -e '\a' no longer works. Also print '\a' doesn't work, presumably for the same reason. The following is also mute: > > import Tkinter > Tkinter.Tk().bell() > > Print '\a', under Idle, causes a bell icon to be displayed so it seems that the lack of a beep is due to a system setting. Would you like us to guess what system you are running? Linux, Mac OS, Windows, FreeBSD, OpenBSD, Android, something else? My guess is... Windows XP. Am I close? Is your sound volume on and not muted? Can you play other sounds? Does your terminal have the "Terminal Bell" enabled? -- Steven From losermeloser at yahoo.com Sat Mar 23 04:29:47 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Fri, 22 Mar 2013 20:29:47 -0700 (PDT) Subject: [Tutor] send issue Message-ID: <1364009387.69583.YahooMailNeo@web121104.mail.ne1.yahoo.com> using a socket im trying to send a message between connections. it was a string and my python complained: ?"TypeError: must be bytes or buffer, not str" .. so i put a b infront of the string. now this works fine but the problem is after recieving this message, i need to send it back with an int included, like: message = 'Thankyou!, processed connection number %d' % connections??????? connections being an int. again this is a string, but puttng a b infront of that strong wont work, it returns: TypeError: unsupported operand type(s) for %: 'bytes' and 'int' ? i tried everything but i cant seem to get past this little obstacle. im using python 3 on windows vista -------------- next part -------------- An HTML attachment was scrubbed... URL: From msirenef at lightbird.net Sat Mar 23 05:02:50 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Sat, 23 Mar 2013 00:02:50 -0400 Subject: [Tutor] send issue In-Reply-To: <1364009387.69583.YahooMailNeo@web121104.mail.ne1.yahoo.com> References: <1364009387.69583.YahooMailNeo@web121104.mail.ne1.yahoo.com> Message-ID: <514D296A.7030206@lightbird.net> On 03/22/2013 11:29 PM, Lolo Lolo wrote: > using a socket im trying to send a message between connections. it was a string and my python complained: > "TypeError: must be bytes or buffer, not str" .. so i put a b infront of the string. now this works fine but the problem is after recieving this message, i need to send it back with an int included, like: > message = 'Thankyou!, processed connection number %d' % connections connections being an int. > again this is a string, but puttng a b infront of that strong wont work, it returns: > TypeError: unsupported operand type(s) for %: 'bytes' and 'int' > > i tried everything but i cant seem to get past this little obstacle. im using python 3 on windows vista > > > _______________________________________________ > You can use bytes() function: >>> bytes('%d' % 3, 'utf-8') b'3' -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Whenever you find yourself on the side of the majority, it is time to pause and reflect. Mark Twain From robert.sjoblom at gmail.com Sat Mar 23 05:08:06 2013 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Sat, 23 Mar 2013 05:08:06 +0100 Subject: [Tutor] Overriding equality tests in Python Message-ID: Hi list. I'll preface this by saying that I am very grateful for all of you, and thank you in advance to anyone that answers. I'm currently working on a roulette simulator, because it seemed like fun. I found out I needed a way to compare two different outcomes, and it was suggested to me that I should override the __eq__ and __ne__ methods. Said and done, I did: class Outcome(): def __init__(self, name): #Ignoring odds for now self.name = name def __eq__(self, other): '''returns True if Outcome.name matches other.name''': if self.name == other.name: return True def __ne__(self, other): '''returns True if Outcome.name does not match other.name''' if self.name != other.name: return True Now, this works, as far as this is concerned: >>> a = Outcome('Bob') >>> b = Outcome('Ray') >>> c = Outcome('Bob') >>> a == b >>> a == c True >>> a != b True >>> However, if I were to create a class without the __eq__ and __ne__ definitions, what is to prevent me from doing: a.name == b.name ? Or am I missing something in my implementation of the overrides? Is there a reason why I shouldn't do .name comparisons? -- best regards, Robert S. From losermeloser at yahoo.com Sat Mar 23 05:22:15 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Fri, 22 Mar 2013 21:22:15 -0700 (PDT) Subject: [Tutor] send issue In-Reply-To: <514D296A.7030206@lightbird.net> References: <1364009387.69583.YahooMailNeo@web121104.mail.ne1.yahoo.com> <514D296A.7030206@lightbird.net> Message-ID: <1364012535.42588.YahooMailNeo@web121101.mail.ne1.yahoo.com> >You can use bytes() function: >>>> bytes('%d' % 3,? 'utf-8') >b'3' >-m ? thanks this has solved everything. can i ask if this is an issue only in python 3 where sockets cant send strings? the docs state the argument is a string, but i believe that was for 2.7. I knew nothing about b'' or bytes() before today. thanks again -------------- next part -------------- An HTML attachment was scrubbed... URL: From msirenef at lightbird.net Sat Mar 23 05:29:04 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Sat, 23 Mar 2013 00:29:04 -0400 Subject: [Tutor] Overriding equality tests in Python In-Reply-To: References: Message-ID: <514D2F90.7080403@lightbird.net> On 03/23/2013 12:08 AM, Robert Sjoblom wrote: > Hi list. I'll preface this by saying that I am very grateful for all > of you, and thank you in advance to anyone that answers. > > I'm currently working on a roulette simulator, because it seemed like > fun. I found out I needed a way to compare two different outcomes, and > it was suggested to me that I should override the __eq__ and __ne__ > methods. Said and done, I did: > class Outcome(): > def __init__(self, name): #Ignoring odds for now > self.name = name > > def __eq__(self, other): > '''returns True if Outcome.name matches other.name''': > if self.name == other.name: return True > def __ne__(self, other): > '''returns True if Outcome.name does not match other.name''' > if self.name != other.name: return True > > Now, this works, as far as this is concerned: >>>> a = Outcome('Bob') >>>> b = Outcome('Ray') >>>> c = Outcome('Bob') >>>> a == b >>>> a == c > True >>>> a != b > True >>>> > However, if I were to create a class without the __eq__ and __ne__ > definitions, what is to prevent me from doing: a.name == b.name ? Or > am I missing something in my implementation of the overrides? Is there > a reason why I shouldn't do .name comparisons? > Firstly, in __eq__, you can do: return self.name == other.name Second, you are right that you can also compare attributes directly. But the meaning is different, if I'm reading your program, a == b tells me "object a is equal to b for the purpose of this program", a.name == b.name tells me, name attrs are equal. a == b is also a shorter and more readable expression. __eq__ is also used in constructs like: if a in mylist: ... __eq__ is probably used for other things, too; the basic idea is that it tells Python that objects are equal, and Python can use this information in various circumstances. -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Each religion, by the help of more or less myth, which it takes more or less seriously, proposes some method of fortifying the human soul and enabling it to make its peace with its destiny. George Santayana From steve at pearwood.info Sat Mar 23 09:14:09 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 23 Mar 2013 19:14:09 +1100 Subject: [Tutor] send issue In-Reply-To: <1364012535.42588.YahooMailNeo@web121101.mail.ne1.yahoo.com> References: <1364009387.69583.YahooMailNeo@web121104.mail.ne1.yahoo.com> <514D296A.7030206@lightbird.net> <1364012535.42588.YahooMailNeo@web121101.mail.ne1.yahoo.com> Message-ID: <514D6451.40900@pearwood.info> On 23/03/13 15:22, Lolo Lolo wrote: >> You can use bytes() function: > >>>>> bytes('%d' % 3, 'utf-8') >> b'3' > >> -m > > thanks this has solved everything. can i ask if this is an issue only in python 3 where sockets cant send strings? the docs state the argument is a string, but i believe that was for 2.7. I knew nothing about b'' or bytes() before today. thanks again The thing to remember is that there are two types of strings: byte strings text strings (also known as Unicode) In Python 2, strings created with "" are called "strings", and even though they are actually byte strings, Python tries really hard to pretend that they are text strings. In Python 2, strings created with u"" are called "unicode strings". They are exactly the same as the strings you create in Python 3 using "" without the U. In Python 3, strings created with b"" are called "bytes", for "byte strings", and Python no longer tries to pretend that they are text strings. (Python 2.7 also understands b"" syntax for creating byte strings.) Summary: * I want a series of bytes, e.g. for sending to a socket - use "abc" or b"abc" in Python 2 - use b"abc" in Python 3 * I want a series of text characters: - use u"abc" in Python 2 - use "abc" in Python 3 * I don't care what I get: - use "abc" in Python 2 or 3, and so long as you don't try to do anything too complicated, it will just work. Does this help? -- Steven From steve at pearwood.info Sat Mar 23 09:34:48 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 23 Mar 2013 19:34:48 +1100 Subject: [Tutor] Overriding equality tests in Python In-Reply-To: References: Message-ID: <514D6928.7020901@pearwood.info> On 23/03/13 15:08, Robert Sjoblom wrote: > Hi list. I'll preface this by saying that I am very grateful for all > of you, and thank you in advance to anyone that answers. > > I'm currently working on a roulette simulator, because it seemed like > fun. I found out I needed a way to compare two different outcomes, and > it was suggested to me that I should override the __eq__ and __ne__ > methods. Said and done, I did: > class Outcome(): > def __init__(self, name): #Ignoring odds for now > self.name = name > > def __eq__(self, other): > '''returns True if Outcome.name matches other.name''': > if self.name == other.name: return True > def __ne__(self, other): > '''returns True if Outcome.name does not match other.name''' > if self.name != other.name: return True I'm not sure what relevance a name has for roulette simulator, but okay. Those two methods are probably better written something like this: def __eq__(self, other): return (self.name == other.name) def __ne__(self, other): return (self.name != other.name) Actually, here's an even better way of doing it: def __eq__(self, other): if isinstance(other, Outcome): return (self.name == other.name) # Give the other object a chance to check for equality. return NotImplemented def __ne__(self, other): return not self == other > Now, this works, as far as this is concerned: >>>> a = Outcome('Bob') >>>> b = Outcome('Ray') >>>> c = Outcome('Bob') >>>> a == b >>>> a == c > True >>>> a != b > True When testing, you should also test values that give the opposite result. For example, compare a == b and a != c. > However, if I were to create a class without the __eq__ and __ne__ > definitions, what is to prevent me from doing: a.name == b.name ? Nothing. But consider a more complicated example. Which would you rather write? a.name.lower() == b.name.lower() and a.age == b.age and a.sex == b.sex a == b The idea of defining __eq__ is that you can hide all the complexity of checking equality in a single method. For example, the __eq__ for dicts might look something like this: def __eq__(self, other): if self is other: return True if not isinstance(self, other): return NotImplemented if len(self) != len(other): return False for key in self: if key not in other: return False if self[key] != self[other]: return False return True Imagine having to write something like that every single time you wanted to compare to dicts for equality. > Or > am I missing something in my implementation of the overrides? Is there > a reason why I shouldn't do .name comparisons? As I said, I don't really understand why a roulette outcome has a name in the first place, but given that it does, I don't any problem with comparing the names directly. Still, I would probably write it as an __eq__ method, since it's easier to write a == b than a.name == b.name. -- Steven From johnsteedman360 at gmail.com Sat Mar 23 10:10:50 2013 From: johnsteedman360 at gmail.com (John Steedman) Date: Sat, 23 Mar 2013 09:10:50 +0000 Subject: [Tutor] Overriding equality tests in Python In-Reply-To: References: Message-ID: It is also good to know that overriding the "comparison magic methods" in your class can be very useful if you wish to apply sorting/searching procedures available in python. If you also implement __gt__, __lt__, __ge__, __le__ in your class, then you can append each of your objects to a list and successfully use the sorted () function on that list. It will enable you to have your list sorted by some other variables within your class, such as the number scored. John S -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Mar 23 10:25:51 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Mar 2013 09:25:51 +0000 Subject: [Tutor] Overriding equality tests in Python In-Reply-To: References: Message-ID: On 23/03/13 04:08, Robert Sjoblom wrote: > However, if I were to create a class without the __eq__ and __ne__ > definitions, what is to prevent me from doing: a.name == b.name ? Or > am I missing something in my implementation of the overrides? Is there > a reason why I shouldn't do .name comparisons? Yes, polymorphism. If you have a function that takes a collection of different types of object and you want to compare them you don't want that function to need to know how to compare every possible type of object (including the ones you haven't written yet). The classic example is a sort function L1 = [1,3,5,4,2,6,8] L2 - [ Outcome(...),Outcome(...)...Outcome()] my lists = [L1,L2] for lst in mylists: lst.sort() That last line can only work sensibly if the lists contain objects that know how to compare themselves. There are many other places where you could be processing mixed objects and want to apply an equality test as part of the algorithm. Hiding the details of the representation of the object inside a method is what OOP is all about. That is what allows us to write code that uses objects rather than the data hidden inside those objects. Welcome to the world of abstract data types :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From davea at davea.name Sat Mar 23 13:03:11 2013 From: davea at davea.name (Dave Angel) Date: Sat, 23 Mar 2013 08:03:11 -0400 Subject: [Tutor] Overriding equality tests in Python In-Reply-To: References: Message-ID: <514D99FF.1020401@davea.name> On 03/23/2013 12:08 AM, Robert Sjoblom wrote: You already got lots of good answers. But I want to explicitly point out a bug in your code (2 places) that was only indirectly mentioned. > class Outcome(): > def __init__(self, name): #Ignoring odds for now > self.name = name > > def __eq__(self, other): > '''returns True if Outcome.name matches other.name''': > if self.name == other.name: return True Here your method returns either True or None. You never supply a return value of False, you just let the default None get returned. For most purposes that will work, but it's a problem waiting to happen. In this particular case, it's easiest to just return the expression: self.name == other.name which already has a value of True or False. But if the function were more complex, you'd want to make sure that all paths through it will return the value you desire, and not the default None. def my_method(self, other): '''returns True if Outcome.name matches other.name and False otherwise''': if self.name == other.name: return True return False -- DaveA From losermeloser at yahoo.com Sat Mar 23 13:12:31 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Sat, 23 Mar 2013 05:12:31 -0700 (PDT) Subject: [Tutor] send issue In-Reply-To: <514D6451.40900@pearwood.info> References: <1364009387.69583.YahooMailNeo@web121104.mail.ne1.yahoo.com> <514D296A.7030206@lightbird.net> <1364012535.42588.YahooMailNeo@web121101.mail.ne1.yahoo.com> <514D6451.40900@pearwood.info> Message-ID: <1364040751.30802.YahooMailNeo@web121104.mail.ne1.yahoo.com> > Does this help? ? THANKS!! Yes it definately helped. everything is so much clearer now. i always used to wonder about the u"" syntax in python 2 -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.sjoblom at gmail.com Sat Mar 23 15:35:53 2013 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Sat, 23 Mar 2013 15:35:53 +0100 Subject: [Tutor] Overriding equality tests in Python In-Reply-To: <514D6928.7020901@pearwood.info> References: <514D6928.7020901@pearwood.info> Message-ID: > As I said, I don't really understand why a roulette outcome has a name in > the first place, but given that it does, I don't any problem with comparing > the names directly. Still, I would probably write it as an __eq__ method, > since it's easier to write a == b than a.name == b.name. I figured that it would be easier if outcomes had names. Consider that each Bin (where the ball lands) can contain between 2 to 14 different winning outcomes. Each Bin() collects various Outcome()s, each Outcome() handles the amount won. Consider the '1' Bin, it contains the following winning Outcome()s: ?1?, ?Red?, ?Odd?, ?Low?, ?Column 1?, ?Dozen 1-12?, ?Split 1-2?, ?Split 1-4?, ?Street 1-2-3?, ?Corner 1-2-4-5?, ?Five Bet?, ?Line 1-2-3-4-5-6?, ?00-0-1-2-3?, ?Dozen 1?. All of these bets will payoff if the wheel spins a ?1?. I'm almost done with the Outcome() class (just writing the unittests for it), after that I'll tackle the Bin class, at which point I will definitely return for more questions. As I said before, thanks to everyone who answered. -- best regards, Robert S. From davea at davea.name Sat Mar 23 16:07:53 2013 From: davea at davea.name (Dave Angel) Date: Sat, 23 Mar 2013 11:07:53 -0400 Subject: [Tutor] Overriding equality tests in Python In-Reply-To: References: <514D6928.7020901@pearwood.info> Message-ID: <514DC549.8080203@davea.name> On 03/23/2013 10:35 AM, Robert Sjoblom wrote: >> As I said, I don't really understand why a roulette outcome has a name in >> the first place, but given that it does, I don't any problem with comparing >> the names directly. Still, I would probably write it as an __eq__ method, >> since it's easier to write a == b than a.name == b.name. > I figured that it would be easier if outcomes had names. Consider that > each Bin (where the ball lands) can contain between 2 to 14 different > winning outcomes. Each Bin() collects various Outcome()s, each > Outcome() handles the amount won. Consider the '1' Bin, it contains > the following winning Outcome()s: > ?1?, ?Red?, ?Odd?, ?Low?, ?Column 1?, ?Dozen 1-12?, ?Split 1-2?, > ?Split 1-4?, ?Street 1-2-3?, ?Corner 1-2-4-5?, ?Five Bet?, ?Line > 1-2-3-4-5-6?, ?00-0-1-2-3?, ?Dozen 1?. All of these bets will payoff > if the wheel spins a ?1?. > > I'm almost done with the Outcome() class (just writing the unittests > for it), after that I'll tackle the Bin class, at which point I will > definitely return for more questions. As I said before, thanks to > everyone who answered. > So you're using the name attribute to match the Outcome instance in the Bin slot against the Outcome instance in the Betting slot? Have you considered just making exactly one instance of each Outcome, and then you can use something like: for mybet in bets: if mybet.outcome in bin[1]: ...do calculation bin is a simple list describing the wheel, and mybet describes an individual bet. mybet.outcome is the particular Outcome, like "Odd". -- DaveA From bodsda at googlemail.com Sat Mar 23 18:42:18 2013 From: bodsda at googlemail.com (Bod Soutar) Date: Sat, 23 Mar 2013 17:42:18 +0000 Subject: [Tutor] Beep sound In-Reply-To: <514D10C7.9090405@pearwood.info> References: <514D09DC.60006@bigpond.com> <514D10C7.9090405@pearwood.info> Message-ID: On Mar 23, 2013 2:24 AM, "Steven D'Aprano" wrote: > > On 23/03/13 12:48, Phil wrote: >> >> Just out of curiosity how can a beep sound be generated? >> >> My interest in this came about because echo -e '\a' no longer works. Also print '\a' doesn't work, presumably for the same reason. The following is also mute: >> >> import Tkinter >> Tkinter.Tk().bell() >> >> Print '\a', under Idle, causes a bell icon to be displayed so it seems that the lack of a beep is due to a system setting. > > > > Would you like us to guess what system you are running? Linux, Mac OS, Windows, FreeBSD, OpenBSD, Android, something else? My guess is... Windows XP. Am I close? > I'm gonna guess Ubuntu, in which case the system beep is probably disabled system wide. Google "ubuntu enable disable system beep" Bodsda -------------- next part -------------- An HTML attachment was scrubbed... URL: From edythe.thompson at lycos.com Sat Mar 23 23:35:19 2013 From: edythe.thompson at lycos.com (Edythe Thompson) Date: Sat, 23 Mar 2013 17:35:19 -0500 Subject: [Tutor] help with installing and/or running PyNomo Message-ID: <2D42D2C8-28EC-4A9E-A0FC-D4F5D0AB3D42@lycos.com> Using Python 2.6.5 Mac OS X version 10.6.8 I want to run the PyNomo package that uses python. I have followed the instructions shown. Install newest python (2.6.5 tested) [1] Download and install latest Numpy for python 2.6. Download and install latest Scipy Install PIL (or skip, probably you won't need it) Install MacTex Install PyX sudo python setup.py install Install PyNomo Run tests on examples directory found in zip-distribution python GENERATE_ALL.py The Numpy and PyX files do not have an installer and can't be dropped into the applications folder, so I have them on the desktop. Python will open in a shell, but shows the following when I run it. Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) [GCC 4.2.1 (Apple Inc. build 5664)] on darwin Type "copyright", "credits" or "license()" for more information. >>> ================================ RESTART ================================ >>> Traceback (most recent call last): File "/Users/edythethompson/Desktop/Type8-Sample.py", line 3, in from pynomo.nomographer import * ImportError: No module named pynomo.nomographer >>> I'm stuck here. What do I need to do to make this work, if it will? Regards, Edythe -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Mar 24 00:59:02 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 23 Mar 2013 23:59:02 +0000 Subject: [Tutor] help with installing and/or running PyNomo In-Reply-To: <2D42D2C8-28EC-4A9E-A0FC-D4F5D0AB3D42@lycos.com> References: <2D42D2C8-28EC-4A9E-A0FC-D4F5D0AB3D42@lycos.com> Message-ID: On 23/03/13 22:35, Edythe Thompson wrote: > Using Python 2.6.5 > Mac OS X version 10.6.8 > > I want to run the PyNomo package that uses python. This list is for learning core Python so you are probably better off asking on a PyNomo forum or mailing list. Or at the very least the MacPython list. However, > Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) This is running Python 2.7 not the 2.6 that you installed. This os probably because your MacOS has python 2.7 installed by default. You will maybe need to explicitly run the 2.6 version for PyNomo. > Traceback (most recent call last): > File "/Users/edythethompson/Desktop/Type8-Sample.py", line 3, in > from pynomo.nomographer import * > ImportError: No module named pynomo.nomographer > >>> I have no idea what PyNomo is or how it works so thats a guess but there is also a danger that some of your other packages have installed themselves in the wrong Python so some may be inPython 2.6 and others in 2.7! That's a pure guess... But what the error says is that python 2.7 doesn't know what/where PyNomo is. My best advice is to see if there is a Python 2./7 version available and if so install that instead. Failing that check that all your installs have been in the 2.6 area and then run Python2.6 (create a shortcut to the executable) Finally your paste suggests you are actually running Python within IDLE. That may not be the best thing to do when using 3rd party packages like PyNomo. Again check with a PyNomo forum (or the developer if there is no forum) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From phil_lor at bigpond.com Sun Mar 24 00:31:33 2013 From: phil_lor at bigpond.com (Phil) Date: Sun, 24 Mar 2013 09:31:33 +1000 Subject: [Tutor] Beep sound In-Reply-To: References: <514D09DC.60006@bigpond.com> <514D10C7.9090405@pearwood.info> Message-ID: <514E3B55.3020501@bigpond.com> On 24/03/13 03:42, Bod Soutar wrote: > > On Mar 23, 2013 2:24 AM, "Steven D'Aprano" > wrote: > > > > On 23/03/13 12:48, Phil wrote: > >> > >> Just out of curiosity how can a beep sound be generated? > >> > >> My interest in this came about because echo -e '\a' no longer works. > Also print '\a' doesn't work, presumably for the same reason. The > following is also mute: > >> > >> import Tkinter > >> Tkinter.Tk().bell() > >> > >> Print '\a', under Idle, causes a bell icon to be displayed so it > seems that the lack of a beep is due to a system setting. > > > > > > > > Would you like us to guess what system you are running? Linux, Mac > OS, Windows, FreeBSD, OpenBSD, Android, something else? My guess is... > Windows XP. Am I close? > > > I'm gonna guess Ubuntu, in which case the system beep is probably > disabled system wide. Google "ubuntu enable disable system beep" > Thank you for your reply Bodsda, Actually, I didn't think there was any need to make any guesses since "echo -e" is exclusively a Linux command. Anyway, I had already spent some time searching for an answerer and the answer given most often was to "modprobe pcspkr". This didn't lead to a working beep. As I said previously, I'm was only curious and it's of little importance. There are many methods, some more complex than others, to play sound files. I found that the pygame library is the easiest to use. Thank you again for taking the time to answer. -- Regards, Phil From steve at pearwood.info Sun Mar 24 03:18:20 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 24 Mar 2013 13:18:20 +1100 Subject: [Tutor] Beep sound In-Reply-To: <514E3B55.3020501@bigpond.com> References: <514D09DC.60006@bigpond.com> <514D10C7.9090405@pearwood.info> <514E3B55.3020501@bigpond.com> Message-ID: <514E626C.2030307@pearwood.info> On 24/03/13 10:31, Phil wrote: > Actually, I didn't think there was any need to make any guesses since "echo -e" is exclusively a Linux command. Nonsense. Not only does echo exist as a command on any Unix, including Apple Mac OS, FreeBSD, OpenBSD, Solaris and others, it also exists on Windows and DOS: http://www.computerhope.com/echohlp.htm More important than the operating system, what terminal application are you using, and does it have Terminal Bell enabled? -- Steven From pankajmittl at gmail.com Sun Mar 24 05:05:13 2013 From: pankajmittl at gmail.com (Pankaj Agarwal) Date: Sat, 23 Mar 2013 21:05:13 -0700 Subject: [Tutor] Python based SMB 2.1/3 testing tool Message-ID: Hi, I'm looking for a tool like PySMB which can provide support for SMB 2.1. Any references will be appreciated. Thanks, Pankaj -------------- next part -------------- An HTML attachment was scrubbed... URL: From phil_lor at bigpond.com Sun Mar 24 05:38:45 2013 From: phil_lor at bigpond.com (Phil) Date: Sun, 24 Mar 2013 14:38:45 +1000 Subject: [Tutor] Beep sound In-Reply-To: <514E626C.2030307@pearwood.info> References: <514D09DC.60006@bigpond.com> <514D10C7.9090405@pearwood.info> <514E3B55.3020501@bigpond.com> <514E626C.2030307@pearwood.info> Message-ID: <514E8355.3040707@bigpond.com> On 24/03/13 12:18, Steven D'Aprano wrote: > On 24/03/13 10:31, Phil wrote: > >> Actually, I didn't think there was any need to make any guesses since >> "echo -e" is exclusively a Linux command. > > Nonsense. Not only does echo exist as a command on any Unix, including > Apple Mac OS, FreeBSD, OpenBSD, Solaris and others, it also exists on > Windows and DOS: > > http://www.computerhope.com/echohlp.htm > I don't want to appear augmentative but there is no echo -e command for Windows. There is, however, echo without the 'e' switch. -- Regards, Phil From michelle_low at zoho.com Sun Mar 24 08:45:49 2013 From: michelle_low at zoho.com (michelle_low) Date: Sun, 24 Mar 2013 00:45:49 -0700 Subject: [Tutor] Phyton script for fasta file (seek help) In-Reply-To: <13d9b2944c8.-4757810490957638786.6251647252550083523@zoho.com> References: <13d9b2944c8.-4757810490957638786.6251647252550083523@zoho.com> Message-ID: <13d9b5c498d.1873243657086367891.785841827467134850@zoho.com> Hi everyone, Can someone please help me with the following phyton script? I received the error message DeprecationWarning: the sets module is deprecated from sets import Set. After googling, I have tried the methods others suggest: change sets to set or delete the from sets import Set but none of them works. Can someone suggest me how to modify the following codes so that the input file is read from standard input? I'd like to execute them with unix command script.py < sequence.fna Thanks a bunch. #!/usr/local/bin/python import math from sets import Set line = file("sequence.fna", "r") for x in line: if x [0] == ">" : #determine the length of sequences s=line.next() s=s.rstrip() length = len(s) # determine the GC content G = s.count('G') C = s.count('C') GC= 100 * (float(G + C) / length) stList = list(s) alphabet = list(Set(stList)) freqList = [] for symbol in alphabet: ctr = 0 for sym in stList: if sym == symbol: ctr += 1 freqList.append(float(ctr)/len(stList)) # Shannon entropy ent = 0.0 for freq in freqList: ent = ent + freq * math.log(freq, 2) ent = -ent print x print "Length:" , length print "G+C:" ,round(GC),"%" print 'Shannon entropy:' print ent print 'Minimum number of bits required to encode each symbol:' print int(math.ceil(ent)) -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sun Mar 24 09:14:11 2013 From: __peter__ at web.de (Peter Otten) Date: Sun, 24 Mar 2013 09:14:11 +0100 Subject: [Tutor] Phyton script for fasta file (seek help) References: <13d9b2944c8.-4757810490957638786.6251647252550083523@zoho.com> <13d9b5c498d.1873243657086367891.785841827467134850@zoho.com> Message-ID: michelle_low wrote: > Can someone please help me with the following phyton script? I received Python; write it on the blackboard one hundred times ;) > the error message DeprecationWarning: the sets module is deprecated > from sets import Set. > After googling, I have tried the methods others suggest: change sets to > set or delete the from sets import Set but none of them works. Remove the line from sets import Set completely and replace Set with set everywhere in your code. > Can someone suggest me how to modify the following codes so that the input > file is read from standard input? I'd like to execute them with unix > command Replace the line > line = file("sequence.fna", "r") with import sys line = sys.stdin If you want to go fancy you can accept either a file name or read from stdin with import sys if sys.argv > 1: # filename was passed as an argument to the script line = open(sys.argv[1]) else: # no filename was passed, default to stdin line = sys.stdin From eryksun at gmail.com Sun Mar 24 09:24:55 2013 From: eryksun at gmail.com (eryksun) Date: Sun, 24 Mar 2013 04:24:55 -0400 Subject: [Tutor] Beep sound In-Reply-To: <514E8355.3040707@bigpond.com> References: <514D09DC.60006@bigpond.com> <514D10C7.9090405@pearwood.info> <514E3B55.3020501@bigpond.com> <514E626C.2030307@pearwood.info> <514E8355.3040707@bigpond.com> Message-ID: On Sun, Mar 24, 2013 at 12:38 AM, Phil wrote: > On 24/03/13 12:18, Steven D'Aprano wrote: >> Nonsense. Not only does echo exist as a command on any Unix, including >> Apple Mac OS, FreeBSD, OpenBSD, Solaris and others, it also exists on >> Windows and DOS: > I don't want to appear augmentative but there is no echo -e command for > Windows. There is, however, echo without the 'e' switch. PulseAudio also suggests that you're using Linux or BSD, though I think it does have ports for OS X and Windows. The ossaudiodev module exists on Linux/BSD, so try something relatively simple like outputting a square wave to /dev/dsp. Here's an example device configuration: format = ossaudiodev.AFMT_U8 # unsigned 8-bit channels = 1 rate = 8000 # samples/second strict = True dsp = ossaudiodev.open('/dev/dsp', 'w') dsp.setparameters(format, channels, rate, strict) Say you want a 1000 Hz, 50% duty-cycle square wave. Given the rate is 8000 sample/s, that's 8 samples per cycle. In 8-bit mode, a cycle has four bytes at the given amplitude followed by four null bytes. For a 0.5 s beep, you need 0.5 * 1000 = 500 cycles. In general: amp = chr(amplitude) # bytes([amplitude]) in 3.x cycles = int(duration * frequency) nhalf = int(0.5 * rate / frequency) data = (amp * nhalf + b'\x00' * nhalf) * cycles Then just write the data. Make sure to close the device when you no longer need it. dsp.write(data) dsp.close() You can use threading to play the beep in the background without blocking the main thread. To me this is simpler than juggling partial writes in nonblock mode. However, you can't access the device concurrently. Instead you could make beep() a method. Then queue the requests, to be handled sequentially by a worker thread. From alan.gauld at btinternet.com Sun Mar 24 10:10:44 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Mar 2013 09:10:44 +0000 Subject: [Tutor] Phyton script for fasta file (seek help) In-Reply-To: <13d9b5c498d.1873243657086367891.785841827467134850@zoho.com> References: <13d9b2944c8.-4757810490957638786.6251647252550083523@zoho.com> <13d9b5c498d.1873243657086367891.785841827467134850@zoho.com> Message-ID: On 24/03/13 07:45, michelle_low wrote: > Can someone please help me with the following phyton script? I > received the error message DeprecationWarning: the sets module is > deprecated > from sets import Set. > I'd like to execute them with unix command Peter answered both of these. However, I think there may be a bug in your code... > > freqList = [] > for symbol in alphabet: > ctr = 0 > for sym in stList: > if sym == symbol: > ctr += 1 > freqList.append(float(ctr)/len(stList)) Should the last line not be indented to be part of the first for loop? Otherwise you only store the count for the last symbol. BTW this could be made simpler: freqList = [] for symbol in alphabet: val = float(stList.count(symbol)/len(stlist) freqList.append(val) HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Mar 24 10:13:07 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Mar 2013 09:13:07 +0000 Subject: [Tutor] Python based SMB 2.1/3 testing tool In-Reply-To: References: Message-ID: On 24/03/13 04:05, Pankaj Agarwal wrote: > I'm looking for a tool like PySMB which can provide support for SMB 2.1. > Any references will be appreciated. This list is for learning the Python language and its core libraries. I suspect you might get a better response for this type of specialist question on the main Python mailing list/newsgroup comp.lang.python -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From pankajmittl at gmail.com Sun Mar 24 12:08:04 2013 From: pankajmittl at gmail.com (Pankaj Agarwal) Date: Sun, 24 Mar 2013 04:08:04 -0700 Subject: [Tutor] Python based SMB 2.1/3 testing tool In-Reply-To: References: Message-ID: Thanks Alan! On Sun, Mar 24, 2013 at 2:13 AM, Alan Gauld wrote: > On 24/03/13 04:05, Pankaj Agarwal wrote: > > I'm looking for a tool like PySMB which can provide support for SMB 2.1. >> Any references will be appreciated. >> > > This list is for learning the Python language and its core > libraries. I suspect you might get a better response for > this type of specialist question on the main Python > mailing list/newsgroup > > comp.lang.python > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ______________________________**_________________ > 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 leamhall at gmail.com Sun Mar 24 12:22:27 2013 From: leamhall at gmail.com (Leam Hall) Date: Sun, 24 Mar 2013 07:22:27 -0400 Subject: [Tutor] Starting a simple python project In-Reply-To: <20130322090238.B48AF6F443@smtp.hushmail.com> References: <20130322090238.B48AF6F443@smtp.hushmail.com> Message-ID: <514EE1F3.9040005@gmail.com> On 03/22/2013 05:02 AM, miguel.guasch at hushmail.com wrote: > Greetings all! > > > My name is Miguel Guasch, I'm a software tester who's trying to > slowly get into automation, and eventually (in a couple of years) > into development. Miguel, welcome! Depending on your skills, you might want to look up the Python classes on Coursera.org. They are free, challenging, and some offer a certificate of achievement. That might be useful in your work portfolio when you move to developer. Last year's videos for one beginner class are still on-line: https://class.coursera.org/programming1-2012-001/class/index The follow up class for that starts tomorrow: https://www.coursera.org/course/programming2 There's an introductory class starting in a few weeks: https://www.coursera.org/course/interactivepython And a Programming Design class starts in May: https://www.coursera.org/course/programdesign Note that I'm not affiliated with Coursera, except to take their classes. Of course, I'm a believer in open education, too. Leam From phil_lor at bigpond.com Sun Mar 24 12:45:37 2013 From: phil_lor at bigpond.com (Phil) Date: Sun, 24 Mar 2013 21:45:37 +1000 Subject: [Tutor] Beep sound In-Reply-To: References: <514D09DC.60006@bigpond.com> <514D10C7.9090405@pearwood.info> <514E3B55.3020501@bigpond.com> <514E626C.2030307@pearwood.info> <514E8355.3040707@bigpond.com> Message-ID: <514EE761.7020005@bigpond.com> On 24/03/13 18:24, eryksun wrote: > PulseAudio also suggests that you're using Linux or BSD, though I > think it does have ports for OS X and Windows. > > The ossaudiodev module exists on Linux/BSD, so try something > relatively simple like outputting a square wave to /dev/dsp. Here's an > example device configuration: > > format = ossaudiodev.AFMT_U8 # unsigned 8-bit > channels = 1 > rate = 8000 # samples/second > strict = True > > dsp = ossaudiodev.open('/dev/dsp', 'w') > dsp.setparameters(format, channels, rate, strict) > > Say you want a 1000 Hz, 50% duty-cycle square wave. Given the rate is > 8000 sample/s, that's 8 samples per cycle. In 8-bit mode, a cycle has > four bytes at the given amplitude followed by four null bytes. For a > 0.5 s beep, you need 0.5 * 1000 = 500 cycles. > > In general: > > amp = chr(amplitude) # bytes([amplitude]) in 3.x > cycles = int(duration * frequency) > nhalf = int(0.5 * rate / frequency) > data = (amp * nhalf + b'\x00' * nhalf) * cycles > > Then just write the data. Make sure to close the device when you no > longer need it. > > dsp.write(data) > dsp.close() > > You can use threading to play the beep in the background without > blocking the main thread. To me this is simpler than juggling partial > writes in nonblock mode. However, you can't access the device > concurrently. Instead you could make beep() a method. Then queue the > requests, to be handled sequentially by a worker thread. Thanks Erksun for your detailed reply. I've saved your reply for a rainy day. I had discovered some information about writing to the dsp device since my original post. However, my experiments have been temporarily curtailed by a wife who wants me to spent more time building our house and less time playing with the computer. It's amazing what's available to play with these days. -- Regards, Phil From bodsda at googlemail.com Sun Mar 24 15:27:22 2013 From: bodsda at googlemail.com (Bod Soutar) Date: Sun, 24 Mar 2013 14:27:22 +0000 Subject: [Tutor] Beep sound In-Reply-To: <514E3B55.3020501@bigpond.com> References: <514D09DC.60006@bigpond.com> <514D10C7.9090405@pearwood.info> <514E3B55.3020501@bigpond.com> Message-ID: > Thank you for your reply Bodsda, > > Actually, I didn't think there was any need to make any guesses since "echo > -e" is exclusively a Linux command. Anyway, I had already spent some time > searching for an answerer and the answer given most often was to "modprobe > pcspkr". This didn't lead to a working beep. > > As I said previously, I'm was only curious and it's of little importance. > There are many methods, some more complex than others, to play sound files. > I found that the pygame library is the easiest to use. > > Thank you again for taking the time to answer. > > -- > Regards, > Phil > Your on the right track, the other thing I've seen is pcspkr being blacklisted. Look in /etc/modprobe.d/blacklist.conf for a line like 'blacklist pcspkr' if it's there, remove it then modprobe or reboot and it should be working again. HTH, Bodsda From thudfoo at gmail.com Sun Mar 24 19:30:35 2013 From: thudfoo at gmail.com (xDog Walker) Date: Sun, 24 Mar 2013 11:30:35 -0700 Subject: [Tutor] Beep sound In-Reply-To: <514D09DC.60006@bigpond.com> References: <514D09DC.60006@bigpond.com> Message-ID: <201303241130.35367.thudfoo@gmail.com> On Friday 2013 March 22 18:48, Phil wrote: > Just out of curiosity how can a beep sound be generated? > > My interest in this came about because echo -e '\a' no longer works. > Also print '\a' doesn't work, presumably for the same reason. The > following is also mute: > > import Tkinter > Tkinter.Tk().bell() > > Print '\a', under Idle, causes a bell icon to be displayed so it seems > that the lack of a beep is due to a system setting. > > A Google search has shown several methods to play .wav files, some > easier than others. Perhaps Pulse Audio has made '\a' redundant? Maybe something here: http://code.activestate.com/search/recipes/#q=beep -- Yonder nor sorghum stenches shut ladle gulls stopper torque wet strainers. From __peter__ at web.de Sun Mar 24 20:24:48 2013 From: __peter__ at web.de (Peter Otten) Date: Sun, 24 Mar 2013 20:24:48 +0100 Subject: [Tutor] Phyton script for fasta file (seek help) References: <13d9b2944c8.-4757810490957638786.6251647252550083523@zoho.com> <13d9b5c498d.1873243657086367891.785841827467134850@zoho.com> Message-ID: michelle_low wrote: > Hi Peter, > Thanks for your help. You're welcome. In the future, please send your mail to the list, not to an individual poster. That way more people get a chance to read it and you are more likely to get help. > I have followed your advice: > > > -removed the line > > from sets import Set > > completely and replace Set with set > > > -Replace the line > > > line = file("sequence.fna", "r") > > with > > import sys > line = sys.stdin > However, when I tried to run the script using command ./script.py < > sequence.fna . nothing came up. The code just does't run. I used to be able > to execute the code and it printed out the list. Now I'm clueless and stuck again. If it worked to your satisfaction before I suggest that you doublecheck you didn't accidentally make changes other than those I suggested. > Can you please look at my script below? Thanks a million I'd rather not ;) Seriously, without a clear notion of what the script is supposed to do it is hard to fix its behaviour... > #!/usr/local/bin/python > > > import math > import sys > > > line = sys.stdin > > > for x in line: > if x [0] == ">" : I suppose that's a ">" in your actual code. Otherwise the condition is always False -- which would explain why you see nothing. > #determine the length of sequences > s=line.next() > s=s.rstrip() > length = len(s) > > > # determine the GC content > G = s.count('G') > C = s.count('C') > GC= 100 * (float(G + C) / length) > > > > > stList = list(s) > alphabet = list(set(stList)) > > > freqList = [] > for symbol in alphabet: > ctr = 0 > for sym in stList: > if sym == symbol: > ctr += 1 > > freqList.append(float(ctr)/len(stList)) The above line gave me an IndentationError. It should probably be > freqList.append(float(ctr)/len(stList)) Had you answered Alan (publicly) there'd be no need to guess... > # Shannon entropy > ent = 0.0 > for freq in freqList: > ent = ent + freq * math.log(freq, 2) > ent = -ent > > > print x > print "Length:" , length > print "G+C:" ,round(GC),"%" > print 'Shannon entropy:' > print ent > print 'Minimum number of bits required to encode each symbol:' > print int(math.ceil(ent)) PS: if you reuse code from someone else: it's a good idea to give credits. From luckytsukune at gmail.com Sun Mar 24 20:41:43 2013 From: luckytsukune at gmail.com (John Bochicchio) Date: Sun, 24 Mar 2013 15:41:43 -0400 Subject: [Tutor] A Text Adventure Problem Message-ID: I've been trying to write a simple test text adventure, but have been running into serious problems. Here is the error I get when I run it. It will give me the opening text and lets me make my first choice. Then I get this. error "Traceback: (Most recent call last) file "game1.py", line 104, in RUNNER (ROOMS, shack_front) file "game1.py", line 100 in runner room = map[next] keyerror= none And here is my code. from sys import exit from random import randint def death(): quips = ["You've become a zombie and eat you pals. Douche." "You've died and left your comrades to fend for themselves. Douche" "Your whole group dies because of you. Douche." "You've got terrible planning skills, and ruined the teams chances of survival. Douche."] print quips[randint(0, len(quips)-1)] exit(1) def shack_front(): print "The year is 2062, and the zombies have risen. You're not a doctor, and you have no training. You're just a guy trying to survive." print "......" * 8 print "You stand in front of a broken down shack, you here gurgles and screams from inside. There is a window to the side of the house that you can see through, or a door you can burst into." print "......" * 8 print "Window or door?" action = raw_input(">") if action == "window": print "You silently walk over to the dirty window. You look inside to see a man held captive by 2 marauders. The marauders are armed with bats, and don't seem to know what they're doing. You have 1 9mm glock with 12 bullets." elif action == "door": print "You burst through the door with your shoulder. You see only one marauder. You shoot him in the chest and notice a man tied up in a chair. You walk over to him but feel a sharp pain in the back of your head. You never saw the second marauder coming." return 'death' else: print "Not a valid command" return 'shack_front' def shack_window(): print "Do you burst through the door or try to fire through the window at the marauders?" action = raw_input(">") if action == "window": print "You fire off three shots through the window. Two in the chest of the first marauder, one in the neck of the other. They fall to the ground, dead. You walk inside to see if the man is okay." elif action == "door": print "You burst through the door and fire two shots into the first marauder. You remember seeing two, so you turn around and put one bullet through the head of the one behind you. You walk over to the man to see if he's okay." else: print "Not a valid command" return 'shack_window' def shack_interior(): print "You ask the man if he is okay." print "He says that he will be fine, and that his name is Carmicheal." print "He says he is an ex marine, but was ambushed by five of them. He believes that three went out on a scavenging party." print "Carmicheal believes that if you wait for them to come back and ambush them, you will be able to get food, ammo, and perhaps even a gun." print "Do you tell him yes, or no?" action = raw_input(">") if action == "yes": print "You tell Carmicheal yes. You both hide in the back of the shack. Carmicheal takes a cleaver and you pull out your glock. 30 minutes pass." print "......" * 10 elif action == "no": print "Carmicheal looks at you puzzled. You ask if he wants to come with you, but he only gets mad. He screams at you for not following the plan, but you walk out." print "You hear a rush of sound as the cleaver hits the back of your skull. You are dead." return 'death' else: print "Not a valid command" return 'shack_interior' def shack_back(): print "You hear the sound of boots in the next room. Carmicheal and you stand up, ready to attack. Do you go in first, or him?" action = raw_input(">") if action == "him": print "Carmicheal goes in first. His cleaver tearing through the neck of the first marauder. You see one trying to pull the gun from his waist. You fire two shots into the marauder, killing him. The third marauder grabs you from behind. You elbow him in the abdomen, leaving Carmicheal just enough room to throw his cleaver into the marauder's head." print "You have both survived. Do you scavenge the dead bodies?" elif action == "me": print "You go in first. You see the three marauders lined up like bowling pins. You let off six shots. Killing first the marauder with the gun, then the two with knives and bats. You easily killed these men without even breaking a sweat. Their bodies lay before you. Do you want to scavenge them?" else: print "Not a valid command." return 'shack_back' ROOMS = { 'death': death, 'shack_front': shack_front, 'shack_window': shack_window, 'shack_interior': shack_interior, 'shack_back' : shack_back } def runner(map, start): next = start while True: room = map[next] print "\n--------" next = room() runner (ROOMS, 'shack_front') -- A computer without a Microsoft operating system is like a dog without bricks tied to its head. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Sun Mar 24 21:58:02 2013 From: bgailer at gmail.com (bob gailer) Date: Sun, 24 Mar 2013 16:58:02 -0400 Subject: [Tutor] A Text Adventure Problem In-Reply-To: References: Message-ID: <514F68DA.8040103@gmail.com> On 3/24/2013 3:41 PM, John Bochicchio wrote: > I've been trying to write a simple test text adventure, but have been > running into serious problems. Here is the error I get when I run it. > It will give me the opening text and lets me make my first choice. What did you enter? I will bet is was 'window'. > Then I get this. > > error "Traceback: (Most recent call last) > file "game1.py", line 104, in > RUNNER (ROOMS, shack_front) > file "game1.py", line 100 in runner > room = map[next] > keyerror= none > [snip] Questions: 1 - what are you using to run your code? 2 - Version of Python? 3 - Operating system? 4 - Did you think about what the error might mean? Observations: 1 - The traceback does not match your code, so either you retyped it or you are using some unusual way of running the program. Compare RUNNER (ROOMS, shack_front) with runner (ROOMS, 'shack_front') 2 - the error normally would look like KeyError: None rather than keyerror= none 3 - The various room functions have at least one way out of them with no return statement. The value returned in that case is None. 4 - There are many many blank lines in the program making it much harder to read. In future eliminate most or all of them. 5 - Most of us do not have the patience to count down 100 lines. In future flag the line with something like: room = map[next] <======== line 100 6 - quips = ["You've become a zombie and eat you pals. Douche." "You've died and left your comrades to fend for themselves. Douche" "Your whole group dies because of you. Douche." "You've got terrible planning skills, and ruined the teams chances of survival. Douche."] quips is a list with one element, consisting of one string or 244 characters. print quips[randint(0, len(quips)-1)] will always print the entire string. Perhaps you meant to put a comma at the end of each line? HTH and good luck. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From luckytsukune at gmail.com Sun Mar 24 22:09:38 2013 From: luckytsukune at gmail.com (John Bochicchio) Date: Sun, 24 Mar 2013 17:09:38 -0400 Subject: [Tutor] A Text Adventure Problem In-Reply-To: <514F68DA.8040103@gmail.com> References: <514F68DA.8040103@gmail.com> Message-ID: 1. I'm using the terminal to run the code. Using the command - (cd python && python2 game1.py) 2. Using python 2.6 I believe. 3. I'm running Arch Linux at the moment. 4. I'm new to python, but I assume the error must have something to do with not having a way for the program to move to the next area of the code. On Sun, Mar 24, 2013 at 4:58 PM, bob gailer wrote: > On 3/24/2013 3:41 PM, John Bochicchio wrote: > > I've been trying to write a simple test text adventure, but have been > running into serious problems. Here is the error I get when I run it. It > will give me the opening text and lets me make my first choice. > > What did you enter? I will bet is was 'window'. > > Then I get this. > > error "Traceback: (Most recent call last) > file "game1.py", line 104, in > RUNNER (ROOMS, shack_front) > file "game1.py", line 100 in runner > room = map[next] > keyerror= none > > [snip] > > Questions: > 1 - what are you using to run your code? > 2 - Version of Python? > 3 - Operating system? > 4 - Did you think about what the error might mean? > > Observations: > > 1 - The traceback does not match your code, so either you retyped it or > you are using some unusual way of running the program. > > Compare > RUNNER (ROOMS, shack_front) > with > runner (ROOMS, 'shack_front') > > 2 - the error normally would look like KeyError: None rather than keyerror= > none > > 3 - The various room functions have at least one way out of them with no > return statement. The value returned in that case is None. > > 4 - There are many many blank lines in the program making it much harder > to read. In future eliminate most or all of them. > > 5 - Most of us do not have the patience to count down 100 lines. In future > flag the line with something like: > room = map[next] <======== line 100 > > 6 - quips = ["You've become a zombie and eat you pals. Douche." > > "You've died and left your comrades to fend for themselves. > Douche" > "Your whole group dies because of you. Douche." > "You've got terrible planning skills, and ruined the teams > chances of survival. Douche."] > quips is a list with one element, consisting of one string or 244 > characters. > print quips[randint(0, len(quips)-1)] > will always print the entire string. > Perhaps you meant to put a comma at the end of each line? > > HTH and good luck. > > -- > Bob Gailer919-636-4239 > Chapel Hill NC > > -- A computer without a Microsoft operating system is like a dog without bricks tied to its head. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Mar 24 22:43:05 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 24 Mar 2013 21:43:05 +0000 Subject: [Tutor] A Text Adventure Problem In-Reply-To: References: <514F68DA.8040103@gmail.com> Message-ID: On 24/03/13 21:09, John Bochicchio wrote: > 4. I'm new to python, but I assume the error must have something to do > with not having a way for the program to move to the next area of the code. Bob already gave you the clue. Look atyou code for window. What does it return? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Sun Mar 24 23:03:05 2013 From: bgailer at gmail.com (bob gailer) Date: Sun, 24 Mar 2013 18:03:05 -0400 Subject: [Tutor] A Text Adventure Problem In-Reply-To: References: Message-ID: <514F7819.1070307@gmail.com> On 3/24/2013 3:41 PM, John Bochicchio wrote: > I've been trying to write a simple test text adventure [snip] Good first try! As you learn OOP and use of classes you will discover ways to improve and simplify coding. Here's an example. It is far from perfect, but definitely worth a study. It will make text adventures easier to create. Note that this separates logic from data. Most room definitions have only data and the Room class has the common logic. from sys import exit from random import randint class Room: # superclass of rooms actions = dict() def __init__(self): self.prompt = ', '.join(self.actions.keys()) def enter(self): print self.enterMsg if self.prompt: while True: action = raw_input(self.prompt + ">").lower() next = self.actions.get(action,None) if next is None: print "Not a valid command" else: print next[0] return next[1] else: exit(1) class Shack_front(Room): enterMsg = "The year is 2062, and the zombies have risen. You're not a doctor, and you have no training. You're just a guy trying to survive.\n" enterMsg += "......" * 8 + "\n" enterMsg += "You stand in front of a broken down shack, you here gurgles and screams from inside. There is a window to the side of the house " enterMsg += "that you can see through, or a door you can burst into.\n" enterMsg += "......" * 8 + "\n" actions = dict( window = ("You silently walk over to the dirty window. You look inside to see a man held captive by 2 marauders. " "The marauders are armed with bats, and don't seem to know what they're doing. You have 1 9mm glock with 12 bullets.", 'window'), door = ("You burst through the door with your shoulder. You see only one marauder. You shoot him in the chest and notice a man tied up " "in a chair. You walk over to him but feel a sharp pain in the back of your head. You never saw the second marauder coming.", 'death')) class Shack_window(Room): enterMsg = "Do you burst through the door or try to fire through the window at the marauders?" actions = dict( window = ("You fire off three shots through the window. Two in the chest of the first marauder, one in the neck of the other. " "They fall to the ground, dead. You walk inside to see if the man is okay.", 'window'), door = ("You burst through the door and fire two shots into the first marauder. You remember seeing two, so you turn around and " "put one bullet through the head of the one behind you. You walk over to the man to see if he's okay.", 'death')) class Death(Room): quips = ["You've become a zombie and eat you pals. Douche.", "You've died and left your comrades to fend for themselves. Douche", "Your whole group dies because of you. Douche.", "You've got terrible planning skills, and ruined the teams chances of survival. Douche."] enterMsg = quips[randint(0, len(quips)-1)] actions = dict() rooms = dict(shack_front = Shack_front(), death = Death(), window = Shack_window()) next = 'shack_front' while True: next = rooms[next].enter() -- Bob Gailer 919-636-4239 Chapel Hill NC From bgailer at gmail.com Sun Mar 24 23:11:19 2013 From: bgailer at gmail.com (bob gailer) Date: Sun, 24 Mar 2013 18:11:19 -0400 Subject: [Tutor] A Text Adventure Problem In-Reply-To: References: <514F68DA.8040103@gmail.com> Message-ID: <514F7A07.1080200@gmail.com> On 3/24/2013 5:09 PM, John Bochicchio wrote: > 1. I'm using the terminal to run the code. Using the command - (cd > python && python2 game1.py) > 2. Using python 2.6 I believe. > 3. I'm running Arch Linux at the moment. > 4. I'm new to python, but I assume the error must have something to do > with not having a way for the program to move to the next area of the > code. OK - what responses do you have to the rest of my questions and observations. Please respond thoroughly. When you the the error copy and paste it directly from the terminal window. Also in the future place your responses immediately after the item you are responding to rather than "top-posting". Thank you for sending to the list as well as me. What did you enter? I will bet is was 'window'.\ > > Questions: > 1 - Did you think about what the error might mean? > > Observations: > > 1 - The traceback does not match your code, so either you retyped > it or you are using some unusual way of running the program. > > Compare > RUNNER (ROOMS, shack_front) > with > runner (ROOMS, 'shack_front') > > 2 - the error normally would look like KeyError: None rather than > keyerror= none > > 3 - The various room functions have at least one way out of them > with no return statement. The value returned in that case is None. > > 4 - There are many many blank lines in the program making it much > harder to read. In future eliminate most or all of them. > > 5 - Most of us do not have the patience to count down 100 lines. > In future flag the line with something like: > room = map[next] <======== line 100 > > 6 - quips = ["You've become a zombie and eat you pals. Douche." > > "You've died and left your comrades to fend for > themselves. Douche" > "Your whole group dies because of you. Douche." > "You've got terrible planning skills, and ruined the > teams chances of survival. Douche."] > quips is a list with one element, consisting of one string or 244 > characters. > print quips[randint(0, len(quips)-1)] > will always print the entire string. > Perhaps you meant to put a comma at the end of each line? > -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From doanviettrung at gmail.com Sun Mar 24 23:36:02 2013 From: doanviettrung at gmail.com (DoanVietTrungAtGmail) Date: Mon, 25 Mar 2013 09:36:02 +1100 Subject: [Tutor] Fwd: Which databases allow lists as record fields? In-Reply-To: References: <514117DB.4080900@davea.name> Message-ID: I read your help (thanks, Peter and Alan) and thought that relational database technology didn't naturally map to my problem domain. Here, at each simulation timestep each entity has a run-time variable number of pointers to other entities. Representing each entity as a table seems unwieldy to me. So, I searched further and now write about what I've learnt, in case someone with a similar problem finds this thread in future. One possible set of solutions is the family of "NoSQL databases". Redis is one such DB, of "key-value" type, and in Pypi there is a package called redis 2.7.2 . Another type is "graph databases", and in Pypi there's a package called redis-graph 1.0built on top of Redis. I've also just installed Scipy because Scipy handles sparse matrices. My simulation has N entities, I'll try representing it as an NxN sparse matrix, each row stores pointers in some sparse format to the rows it talks to. And then there's also NxN bitarray , where on each row a bit is 1 if this row points to this column, to save space there's "compressed bitarray". I also read about "Judy sparse array", touted as fast and memory efficient, but last night I read the author of the package PyJudy writing in 2009 that he hasn't maintained it for "a few years", that put me off. Which one to use, I don't know yet. I am about to start experimenting with Scipy sparse matrix. Trung ============== On Thu, Mar 14, 2013 at 8:13 PM, Alan Gauld wrote: > On 14/03/13 01:39, DoanVietTrungAtGmail wrote: > >> You don't. You create a second table to hold the list. >> Then in the second table you include be reference back to the first. >> >> assuming I do it that way, how to deal with variable-length list? Most >> lists have 10^3, but some can grow to perhaps 10^7 items. A fixed record >> structure to fit the longest possible record would make the database >> table sparse and, presumably, waste space. >> > > I'm not sure what you mean here but the tables are not fixed size. Usually > you are only limited by the size of your hard drive. > > To give an example if you have an object MyType with two of these list > type attributes called foo and bar. We have two instances of MyType, A and > B. A has 10 foos and 50 bars while B has 500 foos and 1000 bars. > > Create a table MyType and populate it with A and B > > Create a Table MyType_foo and populate it with 10 rows referencing A and > 500 rows referencing B > > Create a table Mytype_bar and populate it with 50 rows referencing A and > 1000 rows referencing bar > > Now to see all the foos for A use > > select value from foo where parent = A > > or for B use > > select value from foo whee parent = B > > and the same for bar... > > You can keep adding rows to foo or bar for as long as ypou like. > Youb can add new MyType rows and then add more rows to MyType_foo and bar > which reference thiose new MyTypes. > > There is no limit to how many items you add until your disk fills up! > > > An alternative I thought of was to use SQL Server fields for XML, or >> varchar variable-length character strings containing 10^9 characters, >> then to read the list I'd parse the XML or split the string into literal >> integers then convert to int. I wanted to avoid this computation cost if >> possible. >> > > You can do this but you might as well just store everything in XML in a > flat file. You lose the power of the database query language to > search/filter the results and give yourself a huge > development/test/maintenance task. > > The people who build databases are likely much better at this stuff that > you or me. Use what they give you. > > > > -- > Alan G > 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 zac_vanessa1fan at yahoo.ca Mon Mar 25 00:38:48 2013 From: zac_vanessa1fan at yahoo.ca (Mariel Jane Sanchez) Date: Sun, 24 Mar 2013 16:38:48 -0700 (PDT) Subject: [Tutor] Chapter 3 Projects Message-ID: <1364168328.77990.YahooMailNeo@web141005.mail.bf1.yahoo.com> Hi, I'm sort of new to Python. I'm taking Computer Science 10 and I'm now on Chapter 3. I don't really get how to do the first three projects. Okay, so for the first project, I don't know how to input the ranges like 0-999, 1000-9999, 10000+ and even the negatives. Like when I run it on the shell, it doesn't have any errors whatsoever but it does another thing?especially?when I put 1000000, my typed phrase "Good Score" shows up when "Very Impressive" is the appropriate phrase to go with that score. And when I put in a negative score it says the same thing instead of saying it's an invalid score. How do I put those ranges so that the phrases match with it?? I don't have the book nor the PDF at home, it's in school but I'm sure the second project is about flipping a coin 100 times and I have to show how many heads and tails where randomly flipped. My problem is that, I do get a random number for each sides of the coin but the number is either below or above 100. What am I doing wrong? Lastly, the third project is doing the same thing as one of the demo codes. I have to make a guessing game that only gives the player 5 tries. I just don't understand how to end the loop when the user used up their 5 chances. When I run it and tried to guess the number, it's still the same as the demo code where I can guess as long as I want. What do I put to only have 5 chances? Also, how do I match the 2 phrases? For example, the player guessed the number within 5 attempts, the phrase that is congratulating the player should pop out and vise versa when the player exceeded his chances. I worked on Chapter 3 review questions for the whole class, spent 2 class or less on the demos and the projects took me like 3 days and I'm still working on it. I do try to figure it out myself through trial and error but these projects got me. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Mon Mar 25 00:57:48 2013 From: davea at davea.name (Dave Angel) Date: Sun, 24 Mar 2013 19:57:48 -0400 Subject: [Tutor] Chapter 3 Projects In-Reply-To: <1364168328.77990.YahooMailNeo@web141005.mail.bf1.yahoo.com> References: <1364168328.77990.YahooMailNeo@web141005.mail.bf1.yahoo.com> Message-ID: <514F92FC.4080400@davea.name> On 03/24/2013 07:38 PM, Mariel Jane Sanchez wrote: > Hi, I'm sort of new to Python. I'm taking Computer Science 10 and I'm now on Chapter 3. I don't really get how to do the first three projects. > > Okay, so for the first project, I don't know how to input the ranges like 0-999, 1000-9999, 10000+ and even the negatives. Like when I run it on the shell, it doesn't have any errors whatsoever but it does another thing especially when I put 1000000, my typed phrase "Good Score" shows up when "Very Impressive" is the appropriate phrase to go with that score. And when I put in a negative score it says the same thing instead of saying it's an invalid score. How do I put those ranges so that the phrases match with it? > You can generate a range of numbers into a list with the range() function. So if you want a list of all the ints between 0 and 999 inclusive, you'd use mylist = range(0, 1000) The rest of your paragrph was so unclear and incomplete that I didn't try to read the other paragraphs. When you're able to post a real question, please do so. Start by posting your email as text, not html. Start with a problem statement (one, not three), a valid description of your environment, and some code that you tried. Since you claim to get different results when run from the shell, and from some other technique, I'll suggest you restrict yourself to only running from Linux terminal. And include the full transcript from the Linux prompt forward. Then describe how you ran it, what result you expected, and what you saw, including full traceback for any suggestion. Be sure you use copy/paste, not retyping the code and messages. -- DaveA From msegerrn at gmail.com Mon Mar 25 01:13:09 2013 From: msegerrn at gmail.com (Mandi Seger) Date: Sun, 24 Mar 2013 20:13:09 -0400 Subject: [Tutor] (no subject) Message-ID: Hello, everyone, I am looking for suggestions on a beginner's book for learning Python. I have a nursing background with basic science and math education. I have no programming experience in any computer language. I am currently enrolled in a Master's program for Geographic Information Science and will be learning Python with an eye toward applying it in GIS software programs such as ESRI's ArcMap. I prefer to start with a book for ease of reference, and then move forward with online resources. Thank you for any input. Mandi Seger -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Mar 25 01:36:37 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 25 Mar 2013 00:36:37 +0000 Subject: [Tutor] Chapter 3 Projects In-Reply-To: <1364168328.77990.YahooMailNeo@web141005.mail.bf1.yahoo.com> References: <1364168328.77990.YahooMailNeo@web141005.mail.bf1.yahoo.com> Message-ID: On 24/03/13 23:38, Mariel Jane Sanchez wrote: > thing especially when I put 1000000, my typed phrase "Good Score" shows > up when "Very Impressive" is the appropriate phrase to go with that > score. And when I put in a negative score it says the same thing instead > of saying it's an invalid score. How do I put those ranges so that the > phrases match with it? Bear in mind that we have no idea what projects you are talking about. You might have the PDF at school but we don't even have that so you need to explain in detail what you are talking about. When you say "input the ranges" what do you mean? Are you trying to read the range from a user? Or do you want to produce a range in your code? And do you need all of the numbers in the range? Or are you only testing against the max/min of the range? I can't tell from your description. > the second project is about flipping a coin 100 times and I have to show > how many heads and tails where randomly flipped. My problem is that, I > do get a random number for each sides of the coin but the number is > either below or above 100. What am I doing wrong? Do you know how to repeat an action a known number of times? If so the number of tails is the total minus the number of heads. Can you collect or count the number of heads? > Lastly, the third project is doing the same thing as one of the demo > codes. Without sight of the demo codes that means nothing to us. > have to make a guessing game that only gives the player 5 > tries. I just don't understand how to end the loop when the user used up > their 5 chances. Do you know about while loops? number_of_tries = 0 while number_of_tries < 5: do your loop stuff here number_of_tries = number_of_tries +1 > When I run it and tried to guess the number, it's still > the same as the demo code where I can guess as long as I want. What do I > put to only have 5 chances? Also, > how do I match the 2 phrases? For > example, the player guessed the number within 5 attempts, the phrase > that is congratulating the player should pop out and vise versa when the > player exceeded his chances. Do you know about if statements? Also you can combine tests in your while loop using boolean (or logical) operators like and, or and not. Does that help? hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Mar 25 01:42:29 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 25 Mar 2013 00:42:29 +0000 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On 25/03/13 00:13, Mandi Seger wrote: > have a nursing background with basic science and math education. I have > no programming experience in any computer language. I would try a library loan since such a book will be of limited value after you've finished it. There are a few that are suitable, including mine and Jeff Elkner's and a couple of others. It's hard to recommend one without knowing how you learn... Mine and Jeff's both have online versions (although my book is now well behind the online version, I'm not sure about Jeff's) > I am currently enrolled in a Master's program for Geographic Information > Science and will be learning Python with an eye toward applying it in > GIS software programs such as ESRI's ArcMap. There are libraries available to help with that and some of the folks on this list are actively involved. But that should wait till you at least have the basics down. > I prefer to start with a book for ease of reference, and then move > forward with online resources. As well as the book you can also print out my V2 tutorial from the PDF file - or load it on an eReader if that works for you. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From robert.sjoblom at gmail.com Mon Mar 25 01:45:25 2013 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Mon, 25 Mar 2013 01:45:25 +0100 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: On 25 March 2013 01:13, Mandi Seger wrote: > Hello, everyone, > > I am looking for suggestions on a beginner's book for learning Python. I > have a nursing background with basic science and math education. I have no > programming experience in any computer language. Head First Python or Head First Programming should fit the bill nicely -- both books deal with Python, but in slightly different approaches. Head First Python is much more focused on web applications and mobile devices, where Head First Programming is more focused on building Graphical interfaces (although simplified greatly). I would recommend Head First Python over Programming, because Programming leaves out classes (for one), and your stated background makes it sound like you'll have more use, overall, from Head First Python. There are other books out there, obviously, but Head First Python is the best one I've come across. -- best regards, Robert S. From alan.gauld at btinternet.com Mon Mar 25 01:58:58 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 25 Mar 2013 00:58:58 +0000 Subject: [Tutor] Fwd: Which databases allow lists as record fields? In-Reply-To: References: <514117DB.4080900@davea.name> Message-ID: On 24/03/13 22:36, DoanVietTrungAtGmail wrote: > I read your help (thanks, Peter and Alan) and thought that relational > database technology didn't naturally map to my problem domain. Here, at > each simulation timestep each entity has a run-time variable number of > pointers to other entities. Representing each entity as a table seems > unwieldy to me. It really depends on your problem. If you have a great many number of entity types then relational may not be the best solution. If you have a lot of entities of a few types then relational is a good match - thats what relational databases do best. So the question is how many data types you need to deal with and the dependency graphs between the types. If there are many types all cross referencing each other then a non RDBMS may be a better fit. (although you can get round it in an RDBMS by modelling the type relationships as tables and then simply storing references to the type relations, but that's a bit of a forced solution i agree) > One possible set of solutions is the family of "NoSQL databases There are a huge number of these ranging from single "big table" models to network and graph databases. There are also a myriad of recent "big data" stores too, with their own query languages, for example I've played with Hadoop. Which one suits your problem depends on what you need to store and what you want to retrieve after you've stored it! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From phil_lor at bigpond.com Mon Mar 25 01:08:25 2013 From: phil_lor at bigpond.com (Phil) Date: Mon, 25 Mar 2013 10:08:25 +1000 Subject: [Tutor] Beep sound In-Reply-To: <201303241130.35367.thudfoo@gmail.com> References: <514D09DC.60006@bigpond.com> <201303241130.35367.thudfoo@gmail.com> Message-ID: <514F9579.3040806@bigpond.com> On 25/03/13 04:30, xDog Walker wrote: > Maybe something here: > > http://code.activestate.com/search/recipes/#q=beep Thanks xDog, yet another sound library (pyaudio) to play with. -- Regards, Phil From wrw at mac.com Mon Mar 25 02:38:17 2013 From: wrw at mac.com (William Ray Wing) Date: Sun, 24 Mar 2013 21:38:17 -0400 Subject: [Tutor] (no subject) In-Reply-To: References: Message-ID: <165472D1-B88F-43BE-AB8D-27DE6640E3F8@mac.com> On Mar 24, 2013, at 8:13 PM, Mandi Seger wrote: > Hello, everyone, > > I am looking for suggestions on a beginner's book for learning Python. I have a nursing background with basic science and math education. I have no programming experience in any computer language. > > I am currently enrolled in a Master's program for Geographic Information Science and will be learning Python with an eye toward applying it in GIS software programs such as ESRI's ArcMap. > > I prefer to start with a book for ease of reference, and then move forward with online resources. > > Thank you for any input. > > Mandi Seger > _______________________________________________ Mandi, I've looked at both Alan and Robert's replies. They are both good and relevant - but I'm a bit concerned with your statement that: "I have no programming experience in any computer language." In and of itself, this is NOT a problem, and with a nursing background and a math and science education, you are obviously more than smart enough. What I'm focused on is the initial a-ha! moment when you suddenly see just what programming is all about - or more properly, how you examine a problem you want to solve and express that problem as a series of steps that the computer can carry out. Most of the folks on this list experienced that a-ha moment so long ago, they've forgotten what it was like. Different people get to that moment in different ways, and through different learning experiences. But that moment IS critical. Without it, you are writing programs by rote, and that will be frustrating and you won't get very far - let alone enjoy it, which you should. With it, and after learning your first computer language (and Python is an excellent choice), then learning other languages is trivial. This is a VERY long winded and indirect recommendation to spend a couple of days in your university's book store. It should have a sizable section on various computer languages and a selection of beginner books. Look at the first chapter in several (and look at the first section of Alan's on-line tutorial, in which he talks about this subject). What you are looking for is a book that speaks to YOU, and gets you over that very first conceptual hump. I might also suggest that as a first problem, pick something that is almost a pure exercise in simple mathematical logic - searching for prime numbers for example, or for perfect numbers. Once you can break a problem like that down into simple declarative steps, you are on your way. Welcome to the wonderful world of Python -Bill From phil_lor at bigpond.com Mon Mar 25 01:06:04 2013 From: phil_lor at bigpond.com (Phil) Date: Mon, 25 Mar 2013 10:06:04 +1000 Subject: [Tutor] Beep sound In-Reply-To: References: <514D09DC.60006@bigpond.com> <514D10C7.9090405@pearwood.info> <514E3B55.3020501@bigpond.com> Message-ID: <514F94EC.5080004@bigpond.com> On 25/03/13 00:27, Bod Soutar wrote: > > Your on the right track, the other thing I've seen is pcspkr being > blacklisted. Look in /etc/modprobe.d/blacklist.conf for a line like > 'blacklist pcspkr' if it's there, remove it then modprobe or reboot > and it should be working again. Thanks Bodsda, I had a brief look through the black list files a couple of days ago and didn't find any mention of pcspkr. I've decided to drop this and simply use a sound module because they provide greater scope for experimentation. -- Regards, Phil From suhasbhairav at hotmail.com Mon Mar 25 06:22:30 2013 From: suhasbhairav at hotmail.com (suhas bhairav) Date: Mon, 25 Mar 2013 10:52:30 +0530 Subject: [Tutor] (no subject) In-Reply-To: References: , <165472D1-B88F-43BE-AB8D-27DE6640E3F8@mac.com>, Message-ID: Python website provides you a whole set of resources catering to novices. http://docs.python.org/2/tutorial/ Nick Parlante, a Stanford lecturer has created a wonderful tutorial on Python and you can find it in the below link: https://developers.google.com/edu/python/ Google has free videos which teaches basic Python for people with no programming experience. Again, this is taught by Nick Parlante. http://www.youtube.com/watch?v=tKTZoB2Vjuk RegardsSuhas From: suhasbhairav at hotmail.com To: wrw at mac.com; msegerrn at gmail.com CC: tutor at python.org Subject: RE: [Tutor] (no subject) Date: Mon, 25 Mar 2013 10:43:21 +0530 I'm attaching a pdf which teaches you the basics of Python. This is the pdf that helped me learning python. Apart from this, python website provides you a whole set of resources catering to novices. http://docs.python.org/2/tutorial/ Nick Parlante, a Stanford lecturer has created a wonderful tutorial on Python and you can find it in the below link: https://developers.google.com/edu/python/ Google has free videos which teaches basic Python for people with no programming experience. Again, this is taught by Nick Parlante. http://www.youtube.com/watch?v=tKTZoB2Vjuk RegardsSuhas > From: wrw at mac.com > Date: Sun, 24 Mar 2013 21:38:17 -0400 > To: msegerrn at gmail.com > CC: tutor at python.org; wrw at mac.com > Subject: Re: [Tutor] (no subject) > > On Mar 24, 2013, at 8:13 PM, Mandi Seger wrote: > > > Hello, everyone, > > > > I am looking for suggestions on a beginner's book for learning Python. I have a nursing background with basic science and math education. I have no programming experience in any computer language. > > > > I am currently enrolled in a Master's program for Geographic Information Science and will be learning Python with an eye toward applying it in GIS software programs such as ESRI's ArcMap. > > > > I prefer to start with a book for ease of reference, and then move forward with online resources. > > > > Thank you for any input. > > > > Mandi Seger > > _______________________________________________ > > Mandi, > I've looked at both Alan and Robert's replies. They are both good and relevant - but I'm a bit concerned with your statement that: "I have no programming experience in any computer language." In and of itself, this is NOT a problem, and with a nursing background and a math and science education, you are obviously more than smart enough. What I'm focused on is the initial a-ha! moment when you suddenly see just what programming is all about - or more properly, how you examine a problem you want to solve and express that problem as a series of steps that the computer can carry out. Most of the folks on this list experienced that a-ha moment so long ago, they've forgotten what it was like. Different people get to that moment in different ways, and through different learning experiences. But that moment IS critical. Without it, you are writing programs by rote, and that will be frustrating and you won't get very far - let alone enjoy it, which you should. With it, and after l > earning your first computer language (and Python is an excellent choice), then learning other languages is trivial. This is a VERY long winded and indirect recommendation to spend a couple of days in your university's book store. It should have a sizable section on various computer languages and a selection of beginner books. Look at the first chapter in several (and look at the first section of Alan's on-line tutorial, in which he talks about this subject). What you are looking for is a book that speaks to YOU, and gets you over that very first conceptual hump. > I might also suggest that as a first problem, pick something that is almost a pure exercise in simple mathematical logic - searching for prime numbers for example, or for perfect numbers. Once you can break a problem like that down into simple declarative steps, you are on your way. > > Welcome to the wonderful world of Python > > -Bill > _______________________________________________ > 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 robert.sjoblom at gmail.com Tue Mar 26 05:36:03 2013 From: robert.sjoblom at gmail.com (Robert Sjoblom) Date: Tue, 26 Mar 2013 05:36:03 +0100 Subject: [Tutor] Dictionaries and multiple keys/values Message-ID: Hi again, Tutor List. I am trying to figure out a problem I've run into. Let me first say that this is an assignment, so please don't give me any answers, but just nudge me in the general direction. So the task is this: from a text file, populate three different dictionaries with various information. The text file is structured like so: Georgie Porgie 87% $$$ Canadian, Pub Food So name, rating, price range, and food offered. After food offered follows a blank line before the next restaurant is listed. The three dictionaries are: name_to_rating = {} price_to_names = {'$': [], '$$': [], '$$$': [], '$$$$': []} cuisine_to_names = {} Now I've poked at this for a while now, and one idea I had, which I worked on for quite a while, was that since the restaurants all start at index 0, 5, 10 and so on, I could structure a while loop like this: with open('textfile.txt') as mdf: file_length = len(mdf.readlines())-1 mdf.seek(0) data = mdf.readlines() i = 0 while file_length > 0: name_to_rating[data[i]] = int(data[i+1][:2]) price_to_names[data[i+2].strip()].append(data[i].strip()) # here's the cuisine_to_names part i += 5 file_length -= 5 And while this works, for the two first dictionaries, it seems really cumbersome -- especially that second expression -- and very, very brittle. However, even if I was happy with that, I can't figure out what to do in the situation where: data[i+3] = 'Canadian, Pub Food' #should be two items, is currently a string. My problem is that I'm... stupid. I can split the entry into a list with two items, but even so I don't know how to add the key: value pair to the dictionary so that the value is a list, which I then later can append things to. I'm sorry, this sounds terribly confused, I know. I had another idea to feed each line to a function, because no restaurant name has a comma in it, and food offered always has a comma in it if the restaurant offers more than one kind. But again, this seems really brittle. I guess we can't use objects (for some reason), but that doesn't really matter because if I can't extract the data into dictionaries I wouldn't have much use of an object either way. So yeah, my two questions are these: is there a better way to move through the text file other than a really convoluted expression? And how do I add more than one value to a key in a dictionary, if the values are added at different times and there's no list created in the dictionary to begin with? (I briefly though about initializing empty lists for each food type in the dictionary and go with my horrible expressions, but that seems like a cheap way out of a problem I'd rather tackle in a good way to begin with) Much thanks in advance. -- best regards, Robert S. From joskerc at gmail.com Tue Mar 26 06:54:14 2013 From: joskerc at gmail.com (Jos Kerc) Date: Tue, 26 Mar 2013 06:54:14 +0100 Subject: [Tutor] Dictionaries and multiple keys/values In-Reply-To: References: Message-ID: Hi, On Tue, Mar 26, 2013 at 5:36 AM, Robert Sjoblom wrote: > Hi again, Tutor List. > > I am trying to figure out a problem I've run into. Let me first say > that this is an assignment, so please don't give me any answers, but > just nudge me in the general direction. So the task is this: from a > text file, populate three different dictionaries with various > information. The text file is structured like so: > Georgie Porgie > 87% > $$$ > Canadian, Pub Food > > So name, rating, price range, and food offered. After food offered > follows a blank line before the next restaurant is listed. > > The three dictionaries are: > name_to_rating = {} > price_to_names = {'$': [], '$$': [], '$$$': [], '$$$$': []} > cuisine_to_names = {} > > Now I've poked at this for a while now, and one idea I had, which I > worked on for quite a while, was that since the restaurants all start > at index 0, 5, 10 and so on, I could structure a while loop like this: > with open('textfile.txt') as mdf: > file_length = len(mdf.readlines())-1 > mdf.seek(0) > data = mdf.readlines() > No need to calculate the file length. Read yoiur data & ask python for the length of data. You don't need nor want to read the file twice. > i = 0 > while file_length > 0: > name_to_rating[data[i]] = int(data[i+1][:2]) > price_to_names[data[i+2].strip()].append(data[i].strip()) > # here's the cuisine_to_names part > i += 5 > file_length -= 5 > Another approach could be to process the file while reading it. Since the format is fixed, you knoow exactly what information the line contains. > > And while this works, for the two first dictionaries, it seems really > cumbersome -- especially that second expression -- and very, very > brittle. However, even if I was happy with that, I can't figure out > what to do in the situation where: > data[i+3] = 'Canadian, Pub Food' #should be two items, is currently a > string. > My problem is that I'm... stupid. I can split the entry into a list > with two items, but even so I don't know how to add the key: value > pair to the dictionary so that the value is a list, which I then later > can append things to. > You might want to read up on the dict.get() method. > > I'm sorry, this sounds terribly confused, I know. I had another idea > to feed each line to a function, because no restaurant name has a > comma in it, and food offered always has a comma in it if the > restaurant offers more than one kind. But again, this seems really > brittle. > > Much thanks in advance. > -- > best regards, > Robert S. > _______________________________________________ > 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 davea at davea.name Tue Mar 26 10:44:13 2013 From: davea at davea.name (Dave Angel) Date: Tue, 26 Mar 2013 05:44:13 -0400 Subject: [Tutor] Dictionaries and multiple keys/values In-Reply-To: References: Message-ID: <51516DED.1050104@davea.name> On 03/26/2013 12:36 AM, Robert Sjoblom wrote: > Hi again, Tutor List. > > I am trying to figure out a problem I've run into. Let me first say > that this is an assignment, so please don't give me any answers, but > just nudge me in the general direction. So the task is this: from a > text file, populate three different dictionaries with various > information. The text file is structured like so: > Georgie Porgie > 87% > $$$ > Canadian, Pub Food > > So name, rating, price range, and food offered. After food offered > follows a blank line before the next restaurant is listed. > There are a number of things about the input file that you haven't specified, and it's useful to create a running description of the assumptions you're making about it. That way, if one of those assumptions turns out to not always be true, you at least have a clue as to what might be wrong. And in real-life problems, you might want to add code to test every one of those assumptions, and exit with a clean message when the data doesn't meet them. Examples of such assumptions: 1) the "name" line is unique; no two records have the same name 2) the rating is always exactly two digits followed by a percent sign, even if it's less than 10%. 3) white space may occur before and after the dollarsigns on the price-range field, but never on the rating or name lines 4) there will be exactly 5 lines for every record, including the last one in the file. > The three dictionaries are: > name_to_rating = {} > price_to_names = {'$': [], '$$': [], '$$$': [], '$$$$': []} > cuisine_to_names = {} > > Now I've poked at this for a while now, and one idea I had, which I > worked on for quite a while, was that since the restaurants all start > at index 0, 5, 10 and so on, I could structure a while loop like this: > with open('textfile.txt') as mdf: > file_length = len(mdf.readlines())-1 > mdf.seek(0) > data = mdf.readlines() > > i = 0 > while file_length > 0: > name_to_rating[data[i]] = int(data[i+1][:2]) > price_to_names[data[i+2].strip()].append(data[i].strip()) > # here's the cuisine_to_names part > i += 5 > file_length -= 5 > > And while this works, for the two first dictionaries, it seems really > cumbersome -- especially that second expression -- and very, very > brittle. However, even if I was happy with that, I can't figure out > what to do in the situation where: > data[i+3] = 'Canadian, Pub Food' #should be two items, is currently a string. > My problem is that I'm... stupid. I can split the entry into a list > with two items, but even so I don't know how to add the key: value > pair to the dictionary so that the value is a list, which I then later > can append things to. > Nothing stupid about that. Your only shortcoming is assuming it should be a single line doing the assignment. Once you use cuisines.split(something) to make a list of cuisines, you then need to loop over them. And if the cuisine doesn't already exist, you need to create the item, while if it does, you need to append to the item. > I'm sorry, this sounds terribly confused, I know. I had another idea > to feed each line to a function, because no restaurant name has a > comma in it, and food offered always has a comma in it if the > restaurant offers more than one kind. But again, this seems really > brittle. > > I guess we can't use objects (for some reason), but that doesn't > really matter because if I can't extract the data into dictionaries I > wouldn't have much use of an object either way. So yeah, my two > questions are these: > is there a better way to move through the text file other than a > really convoluted expression? And how do I add more than one value to > a key in a dictionary, if the values are added at different times and > there's no list created in the dictionary to begin with? > > (I briefly though about initializing empty lists for each food type in > the dictionary and go with my horrible expressions, but that seems > like a cheap way out of a problem I'd rather tackle in a good way to > begin with) > > Much thanks in advance. > First thing I'd do to make those lines clearer is to assign temp names to each of those fields. For example, if you say name = then the other places that use name can be much more readable. Likewise, if a particular name needs to be stripped or split before being assigned, it's in one common place. So the loop would start with four assignments, capturing usable versions of those four lines. Then you'd have 3 assignments, updating the three dictionaries from those four names. And one of those assignments would update multiple dictionary items, it would actually be a loop. You mention objects, which is one way to make things easier. But you didn't mention functions. I think it'd be an improvement if each dictionary had a function created to do its updating. Then the loop that you're writing here would be four assignments, followed by 3 function calls. Finally, you ask if there's a better way than readlines(). I don't think there's any harm in doing it this way, though it could take a lot of memory if the file is really large. But why not do a readline() for each individual variable? Then all the bookkeeping of i+3 etc goes away. -- DaveA From alan.gauld at btinternet.com Tue Mar 26 11:41:16 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Mar 2013 10:41:16 +0000 Subject: [Tutor] Dictionaries and multiple keys/values In-Reply-To: References: Message-ID: On 26/03/13 04:36, Robert Sjoblom wrote: > Georgie Porgie > 87% > $$$ > Canadian, Pub Food > So a 5 line pattern with 4 data fields. The last one containing multiple comma separated values, potentially. > The three dictionaries are: > name_to_rating = {} > price_to_names = {'$': [], '$$': [], '$$$': [], '$$$$': []} > cuisine_to_names = {} And the keys are all basic single data values So far so good. > Now I've poked at this for a while now, and one idea I had, which I > worked on for quite a while, was that since the restaurants all start > at index 0, 5, 10 and so on, I could structure a while loop like this: Sounds way too complicated. I'd just read the file in groups of 5 lines and process them as I went. I'd also write a helper function to process each record. In pseudo code def storeRestaurant(mdr): name = mdr.readline() rating = mdr.readline() price = mdr.readline() cuisines= mdr.readline().split(',') # now assign values to dictionaries. with open....as mdr while True: try: storeRestaurant(mdr) except end of file: pass > I'm sorry, this sounds terribly confused, I know. I had another idea > to feed each line to a function, because no restaurant name has a > comma in it, and food offered always has a comma in it if the > restaurant offers more than one kind. But again, this seems really > brittle. I'm not sure why you think its brittle? You need to code in error checking somewhere, it might as well be hidden in a function. > I guess we can't use objects (for some reason), Technically you can but maybe assignment wise you can't... > really convoluted expression? And how do I add more than one value to > a key in a dictionary, if the values are added at different times and > there's no list created in the dictionary to begin with? You can create a list to begin with if you suspect you may need multiple values.... ie each time you add a new key create a list. The get() method should help here. > (I briefly though about initializing empty lists for each food type in > the dictionary and go with my horrible expressions, You can do the empty lists without the horrible expressions! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mousumi251 at gmail.com Tue Mar 26 13:16:15 2013 From: mousumi251 at gmail.com (Mousumi Basu) Date: Tue, 26 Mar 2013 17:46:15 +0530 Subject: [Tutor] PyDtls Message-ID: I have installed PyDtls from the link:-" https://pypi.python.org/pypi/Dtls/0.1.0". While creating the server and client objects in "sslconnection.py", it is referring to "x509.py" for certificates. Following error is occurring :- File "C:\dtls\Dtls-0.1.0.sdist_with_openssl.win32\Dtls-0.1.0\dtls\"x509.py",line 34 , in from openssl import * File"C:\dtls\Dtls-0.1.0.sdist_with_openssl.win32\Dtls-0.1.0\dtls\"openssl.py", line 74 in libcrypto=CDLL(release_cryptodll_path) File"C:\Python27\lib\ctypes\"_init_.py", line 365,in _init_ self_.handle=_dlopen(self._name,mode) WindowsError: [Error 126] The specified module could not be found. Please help me out to sort that error. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Tue Mar 26 13:28:56 2013 From: davea at davea.name (Dave Angel) Date: Tue, 26 Mar 2013 08:28:56 -0400 Subject: [Tutor] PyDtls In-Reply-To: References: Message-ID: <51519488.4020502@davea.name> On 03/26/2013 08:16 AM, Mousumi Basu wrote: > I have installed PyDtls from the link:-" > https://pypi.python.org/pypi/Dtls/0.1.0". > While creating the server and client objects in > "sslconnection.py", it is referring to "x509.py" for certificates. > Following error is occurring :- > > File > "C:\dtls\Dtls-0.1.0.sdist_with_openssl.win32\Dtls-0.1.0\dtls\"x509.py",line > 34 , in > from openssl import * > File"C:\dtls\Dtls-0.1.0.sdist_with_openssl.win32\Dtls-0.1.0\dtls\"openssl.py", > line 74 in > > libcrypto=CDLL(release_cryptodll_path) > > File"C:\Python27\lib\ctypes\"_init_.py", line 365,in _init_ > self_.handle=_dlopen(self._name,mode) > > WindowsError: [Error 126] The specified module could not be found. > > > Please help me out to sort that error. > > Sounds to me like the DLL that implements the crypto is missing, in the wrong place, or has unmet dependencies. You can find out the name (and presumably the path) of the dll by looking at release_cryptodll_path. If it's indeed there, then I'd use the dependency walker (from the appropriate Windows ddk) to find whether there are any unmet dependencies. That assumes you haven't done anything obscure with the path, as the dependency walker needs to run with the same environment variables. -- DaveA From phil_lor at bigpond.com Tue Mar 26 12:30:28 2013 From: phil_lor at bigpond.com (Phil) Date: Tue, 26 Mar 2013 21:30:28 +1000 Subject: [Tutor] Udp socket questio Message-ID: <515186D4.9060303@bigpond.com> Thank you for reading this. I'm a bit out of my depth here. I'm attempting to set up a simple udp client. The example that follows results in an error message and I'm wondering if I should be importing a different module. A Google search doesn't support that idea. '' udp socket client Silver Moon ''' import socket #for sockets import sys #for exit # create dgram udp socket try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) except socket.error: print 'Failed to create socket' sys.exit() host = 'localhost'; port = 8888; while(1) : msg = raw_input('Enter message to send : ') try : #Set the whole string s.sendto(msg, (host, port)) # receive data from client (data, addr) d = s.recvfrom(1024) reply = d[0] addr = d[1] print 'Server reply : ' + reply except socket.error, msg: print 'Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() Traceback (most recent call last): File "socket2.py", line 6, in import socket #for sockets File "/home/phil/Python/socket.py", line 7, in s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) AttributeError: 'module' object has no attribute 'AF_INET' -- Regards, Phil From davea at davea.name Tue Mar 26 14:15:04 2013 From: davea at davea.name (Dave Angel) Date: Tue, 26 Mar 2013 09:15:04 -0400 Subject: [Tutor] Udp socket questio In-Reply-To: <515186D4.9060303@bigpond.com> References: <515186D4.9060303@bigpond.com> Message-ID: <51519F58.8000401@davea.name> On 03/26/2013 07:30 AM, Phil wrote: > Thank you for reading this. > > I'm a bit out of my depth here. I'm attempting to set up a simple udp > client. > > The example that follows results in an error message and I'm wondering > if I should be importing a different module. A Google search doesn't > support that idea. > > '' > udp socket client > Silver Moon > ''' > > import socket #for sockets > import sys #for exit > > # create dgram udp socket > try: > s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > except socket.error: > print 'Failed to create socket' > sys.exit() > > host = 'localhost'; > port = 8888; > > while(1) : > msg = raw_input('Enter message to send : ') > > try : > #Set the whole string > s.sendto(msg, (host, port)) > > # receive data from client (data, addr) > d = s.recvfrom(1024) > reply = d[0] > addr = d[1] > > print 'Server reply : ' + reply > > except socket.error, msg: > print 'Error Code : ' + str(msg[0]) + ' Message ' + msg[1] > sys.exit() > > > Traceback (most recent call last): > File "socket2.py", line 6, in > import socket #for sockets > File "/home/phil/Python/socket.py", line 7, in > s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > AttributeError: 'module' object has no attribute 'AF_INET' > Looks to me like you have your own file socket.py in /home/phil/Python and that it has the line that's causing the exception. That file hides the one in the system library, so please rename it to something else. -- DaveA From alan.gauld at btinternet.com Tue Mar 26 14:23:21 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Mar 2013 13:23:21 +0000 Subject: [Tutor] PyDtls In-Reply-To: References: Message-ID: On 26/03/13 12:16, Mousumi Basu wrote: > I have installed PyDtls from the > link:-"https://pypi.python.org/pypi/Dtls/0.1.0". This list is for learning the python language and standard library. Anything beyond that you are taking pot luck whether anyone here knows about it. You would be better off asking on a specific Dtls forum or possibly on the general Python mailing list/newsgroup. comp.lang.python -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From eryksun at gmail.com Tue Mar 26 14:57:26 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 26 Mar 2013 09:57:26 -0400 Subject: [Tutor] PyDtls In-Reply-To: References: Message-ID: On Tue, Mar 26, 2013 at 8:16 AM, Mousumi Basu wrote: > File"C:\dtls\Dtls-0.1.0.sdist_with_openssl.win32\Dtls-0.1.0\dtls\"openssl.py", > line 74 in You didn't install the package. Run "python setup.py install". This will install it to Lib\site-packages\Dtls and copy the pre-built DLLs into the package directory. From scarolan at gmail.com Tue Mar 26 15:55:49 2013 From: scarolan at gmail.com (Sean Carolan) Date: Tue, 26 Mar 2013 09:55:49 -0500 Subject: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error Message-ID: I'm attempting to use setup.py to build an RPM, but ran into this error: [scarolan at cobbler:~/rpmbuild/BUILD/Python-2.7.3]$ python27 setup.py bdist_rpm File "setup.py", line 361 with open(tmpfile) as fp: ^ SyntaxError: invalid syntax error: Bad exit status from /var/tmp/rpm-tmp.8897 (%build) It appears the syntax error is striggered when "python setup.py build" is run from that temporary bash script (/var/tmp/rpm-tmp.8897): + cd /home/scarolan/rpmbuild/BUILD/Python-2.7.3/build/bdist.linux-x86_64/rpm/BUILD + cd Python-2.7.3 + env 'CFLAGS=-O2 -g -m64 -mtune=generic' python setup.py build File "setup.py", line 361 with open(tmpfile) as fp: ^ SyntaxError: invalid syntax Any ideas how to fix this? The documentation on this topic is quite scarce. -------------- next part -------------- An HTML attachment was scrubbed... URL: From amitsaha.in at gmail.com Tue Mar 26 16:07:02 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Wed, 27 Mar 2013 01:07:02 +1000 Subject: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error In-Reply-To: References: Message-ID: On Wed, Mar 27, 2013 at 12:55 AM, Sean Carolan wrote: > I'm attempting to use setup.py to build an RPM, but ran into this error: > > [scarolan at cobbler:~/rpmbuild/BUILD/Python-2.7.3]$ python27 setup.py > bdist_rpm > > File "setup.py", line 361 > with open(tmpfile) as fp: > ^ > SyntaxError: invalid syntax > error: Bad exit status from /var/tmp/rpm-tmp.8897 (%build) > > It appears the syntax error is striggered when "python setup.py build" is > run from that temporary bash script (/var/tmp/rpm-tmp.8897): Could it be that it is taking the system python executable which is probably 2.4? -Amit. -- http://amitsaha.github.com/ From scarolan at gmail.com Tue Mar 26 16:18:24 2013 From: scarolan at gmail.com (Sean Carolan) Date: Tue, 26 Mar 2013 10:18:24 -0500 Subject: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error In-Reply-To: References: Message-ID: > Could it be that it is taking the system python executable which is > probably 2.4? > > -Amit. I've tried it with python24, python25 and python27 and all of them give the same error. -------------- next part -------------- An HTML attachment was scrubbed... URL: From scarolan at gmail.com Tue Mar 26 17:54:03 2013 From: scarolan at gmail.com (Sean Carolan) Date: Tue, 26 Mar 2013 11:54:03 -0500 Subject: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error In-Reply-To: References: Message-ID: Ok, so I'm now attempting a "clean room" installation using Python 2.7.3 to build the RPM. Here's my installation command: ./configure --with-zlib=/usr/include; make; sudo make install But the bdist_rpm setup command fails: [scarolan at titania:~/Python-2.7.3]$ python2.7 setup.py bdist_rpm error: pyconfig.h: No such file or directory error: Bad exit status from /var/tmp/rpm-tmp.67699 (%build) RPM build errors: Bad exit status from /var/tmp/rpm-tmp.67699 (%build) error: command 'rpmbuild' failed with exit status 1 Where is it looking for pyconfig.h? On Tue, Mar 26, 2013 at 10:18 AM, Sean Carolan wrote: > > Could it be that it is taking the system python executable which is >> probably 2.4? >> >> -Amit. > > > I've tried it with python24, python25 and python27 and all of them give > the same error. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From hugo.yoshi at gmail.com Tue Mar 26 17:54:15 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Tue, 26 Mar 2013 16:54:15 +0000 Subject: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error In-Reply-To: References: Message-ID: On Tue, Mar 26, 2013 at 3:18 PM, Sean Carolan wrote: > > Could it be that it is taking the system python executable which is >> probably 2.4? >> >> -Amit. > > > I've tried it with python24, python25 and python27 and all of them give > the same error. > > What it looks like to me is that while you run (using python 2.7): > python27 setup.py bdist_rpm doing that generates a temporary bash script, which in turn runs: > python setup.py build which is linked to the system default python, which I'm guessing is 2.4. No matter which version you execute the first one with, the bash script generated will always try to use the system-default python. This is essentially a bug in the setup script; it should generate a script that uses the same python version it was executed with, ideally. The easiest workaround I can think of is a temporary alias, i.e.: $ alias python="python27" && python setup.by bdist_rpm && unalias python Or some variation of such. The more permanent fix is to change the bash script that setup.py generates so it's less naive about having the right system python installed, *or* upgrading the system python version. HTH, Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From scarolan at gmail.com Tue Mar 26 18:05:24 2013 From: scarolan at gmail.com (Sean Carolan) Date: Tue, 26 Mar 2013 12:05:24 -0500 Subject: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error In-Reply-To: References: Message-ID: > What it looks like to me is that while you run (using python 2.7): > > > python27 setup.py bdist_rpm > > doing that generates a temporary bash script, which in turn runs: > > > python setup.py build > Yea, I checked this, and /usr/local/bin/python is just a symlink pointing at /usr/local/bin/python2.7. Unfortunately Red Hat is slow to update their package versions; even the most recent RHEL6 comes with Python 2.6. I think if I can figure out where it wants that pyconfig.h file, it should work. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Tue Mar 26 18:07:08 2013 From: wprins at gmail.com (Walter Prins) Date: Tue, 26 Mar 2013 17:07:08 +0000 Subject: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error In-Reply-To: References: Message-ID: Hi, On 26 March 2013 16:54, Hugo Arts wrote: > On Tue, Mar 26, 2013 at 3:18 PM, Sean Carolan wrote: > >> >> Could it be that it is taking the system python executable which is >>> probably 2.4? >>> >>> -Amit. >> >> >> I've tried it with python24, python25 and python27 and all of them give >> the same error. >> > > The easiest workaround I can think of is a temporary alias, i.e.: > > $ alias python="python27" && python setup.by bdist_rpm && unalias python > > Or some variation of such. The more permanent fix is to change the bash > script that setup.py generates so it's less naive about having the right > system python installed, *or* upgrading the system python version. > Sean you might also look into virtualenv. I suspect a suitably setup virtualenv will also avoid your problem, but is obviously more work than what Hugo's suggested. See for example this question on stackoverflow: http://stackoverflow.com/questions/1534210/use-different-python-version-with-virtualenv Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Tue Mar 26 18:22:27 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 26 Mar 2013 13:22:27 -0400 Subject: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error In-Reply-To: References: Message-ID: On Tue, Mar 26, 2013 at 11:18 AM, Sean Carolan wrote: > I've tried it with python24, python25 and python27 and all of them give the > same error. After looking at the source, I think the option python=python2.7 may solve the problem. http://hg.python.org/cpython/file/d321885ff8f3/Lib/distutils/command/bdist_rpm.py#l23 From eryksun at gmail.com Tue Mar 26 18:35:08 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 26 Mar 2013 13:35:08 -0400 Subject: [Tutor] PyDtls In-Reply-To: References: Message-ID: On Tue, Mar 26, 2013 at 12:59 PM, Mousumi Basu wrote: > > I have run the following command previously in the command prompt:- > > C:\dtls\Dtls-0.1.0.sdist_with_openssl.win32\Dtls-0.1.0\dtls> > python setup.py install > > Was that incorrect?Please help me out as i am eager to learn about pydtls. That's fine, but the error messages you posted showed 'File "C:\dtls\ ....', which is not correct. I see from the ctypes error that Python is installed in C:\Python27. Then the package (and the DLLs) should be located here: C:\Python27\Lib\site-packages\dtls You don't run it from there as a script, however. Python will find it along sys.path when you "import dtls". From eryksun at gmail.com Tue Mar 26 19:01:49 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 26 Mar 2013 14:01:49 -0400 Subject: [Tutor] PyDtls In-Reply-To: References: Message-ID: On Tue, Mar 26, 2013 at 1:35 PM, eryksun wrote: >> C:\dtls\Dtls-0.1.0.sdist_with_openssl.win32\Dtls-0.1.0\dtls> >> python setup.py install >> >> Was that incorrect?Please help me out as i am eager to learn about pydtls. > > That's fine, On 2nd thought, that's not fine. setup.py is located in the parent directory. Make sure you're in the right directory: > C: > cd C:\dtls\Dtls-0.1.0.sdist_with_openssl.win32\Dtls-0.1.0 Run the setup script: > python setup.py install Run python and import dtls to test it: >>> import dtls >>> import ssl >>> hasattr(ssl, 'DTLS_OPENSSL_VERSION') False Now patch ssl: >>> dtls.do_patch() >>> ssl.DTLS_OPENSSL_VERSION 'OpenSSL 1.0.1c 10 May 2012' From david at graniteweb.com Tue Mar 26 19:05:29 2013 From: david at graniteweb.com (David Rock) Date: Tue, 26 Mar 2013 13:05:29 -0500 Subject: [Tutor] Dictionaries and multiple keys/values In-Reply-To: References: Message-ID: <20130326180529.GB24325@wdfs.bad> * Robert Sjoblom [2013-03-26 05:36]: > > brittle. However, even if I was happy with that, I can't figure out > what to do in the situation where: > data[i+3] = 'Canadian, Pub Food' #should be two items, is currently a string. > My problem is that I'm... stupid. I can split the entry into a list > with two items, but even so I don't know how to add the key: value > pair to the dictionary so that the value is a list, which I then later > can append things to. If your data is a list, then it will be a list in the dict. You could just make it so that particular key always contains a list of characteristics, even if it's a list of only one. >>> data = 'Canadian, Pub Food'.split(',') >>> data ['Canadian', ' Pub Food'] >>> data = 'French'.split(',') >>> data ['French'] Then just put the list as the value. d['characteristics'] = data >>> data = 'Canadian, Pub Food'.split(',') >>> d['characteristics'] = data >>> d['characteristics'] ['Canadian', ' Pub Food'] -- David Rock david at graniteweb.com From scarolan at gmail.com Tue Mar 26 20:04:19 2013 From: scarolan at gmail.com (Sean Carolan) Date: Tue, 26 Mar 2013 14:04:19 -0500 Subject: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error In-Reply-To: References: Message-ID: > > http://hg.python.org/cpython/file/d321885ff8f3/Lib/distutils/command/bdist_rpm.py#l23 > No dice. [scarolan at titania:~/Python-2.7.3]$ alias | grep python alias python='/usr/local/bin/python2.7' [scarolan at titania:~/Python-2.7.3]$ /usr/local/bin/python2.7 setup.py bdist_rpm error: pyconfig.h: No such file or directory error: Bad exit status from /var/tmp/rpm-tmp.14555 (%build) RPM build errors: Bad exit status from /var/tmp/rpm-tmp.14555 (%build) error: command 'rpmbuild' failed with exit status 1 Has anyone on this list successfully built a python 2.7 RPM using this command? python2.7 setup.py bdist_rpm If so, what was your secret? -------------- next part -------------- An HTML attachment was scrubbed... URL: From scarolan at gmail.com Tue Mar 26 20:21:35 2013 From: scarolan at gmail.com (Sean Carolan) Date: Tue, 26 Mar 2013 14:21:35 -0500 Subject: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error In-Reply-To: References: Message-ID: > If so, what was your secret? > > I tried running this again with strace, and it looks like it's finding the pyconfig.h file: open("/usr/local/include/python2.7/pyconfig.h", O_RDONLY) = 4 read(4, "/* pyconfig.h. Generated from p"..., 4096) = 4096 stat("pyconfig.h", {st_mode=S_IFREG|0664, st_size=36037, ...}) = 0 stat("pyconfig.h.in", {st_mode=S_IFREG|0644, st_size=34336, ...}) = 0 stat("PC/pyconfig.h", {st_mode=S_IFREG|0644, st_size=20770, ...}) = 0 stat("PC/os2vacpp/pyconfig.h", {st_mode=S_IFREG|0644, st_size=10113, ...}) = 0 stat("PC/os2emx/pyconfig.h", {st_mode=S_IFREG|0644, st_size=8096, ...}) = 0 stat("Include/pyconfig.h", {st_mode=S_IFREG|0664, st_size=36037, ...}) = 0 stat("build/bdist.linux-x86_64/rpm/BUILD/Python-2.7.3/pyconfig.h", {st_mode=S_IFREG|0664, st_size=36037, ...}) = 0 stat("build/bdist.linux-x86_64/rpm/BUILD/Python-2.7.3/Include/pyconfig.h", {st_mode=S_IFREG|0664, st_size=36037, ...}) = 0 stat("RISCOS/pyconfig.h", {st_mode=S_IFREG|0644, st_size=18510, ...}) = 0 open("/usr/local/include/python2.7/pyconfig.h", O_RDONLY) = 3 read(3, "/* pyconfig.h. Generated from p"..., 4096) = 4096 error: pyconfig.h: No such file or directory /usr/local/include/python2.7/pyconfig.h exists: [scarolan at titania:~/Python-2.7.3]$ ls /usr/local/include/python2.7/pyconfig.h -l -rw-r--r-- 1 root root 36037 Mar 26 11:45 /usr/local/include/python2.7/pyconfig.h I'm not sure exactly what the installer is expecting here... -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Mar 26 22:15:18 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 26 Mar 2013 21:15:18 +0000 Subject: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error In-Reply-To: References: Message-ID: On 26/03/13 19:04, Sean Carolan wrote: > Has anyone on this list successfully built a python 2.7 RPM using this > command? > python2.7 setup.py bdist_rpm Given that most folks on this list are only learning Python its pretty unlikely that they are building bespoke RPMs... You might find more experience of RPM building on the general Python mailing list/newsgroup. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From scarolan at gmail.com Tue Mar 26 22:32:44 2013 From: scarolan at gmail.com (Sean Carolan) Date: Tue, 26 Mar 2013 16:32:44 -0500 Subject: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error In-Reply-To: References: Message-ID: > Given that most folks on this list are only learning Python its pretty > unlikely that they are building bespoke RPMs... > > You might find more experience of RPM building on the general Python > mailing list/newsgroup. Sorry 'bout that. I'll follow up with the bug report and possibly the general list as well. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Tue Mar 26 23:10:29 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 26 Mar 2013 22:10:29 +0000 Subject: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF4741827ED72@SCACMX008.exchad.jpmchase.net> Sean Carolan wrote: > [Alan Gauld wrote:] > > Given that most folks on this list are only learning Python its pretty unlikely that they are building > > bespoke RPMs... > > > > You might find more experience of RPM building on the general Python mailing list/newsgroup. > > Sorry 'bout that. ?I'll follow up with the bug report and possibly the general list as well. Please post your solution back (if you find one), for archive completeness. And my curiosity. :) ~Ramit This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From amitsaha.in at gmail.com Tue Mar 26 23:37:11 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Wed, 27 Mar 2013 08:37:11 +1000 Subject: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error In-Reply-To: References: Message-ID: On Wed, Mar 27, 2013 at 7:32 AM, Sean Carolan wrote: > >> Given that most folks on this list are only learning Python its pretty >> unlikely that they are building bespoke RPMs... >> >> You might find more experience of RPM building on the general Python >> mailing list/newsgroup. > > > Sorry 'bout that. I'll follow up with the bug report and possibly the > general list as well. I am going to try doing this sometime today. I shall let you know if I find a solution or my observations. Best, Amit. -- http://amitsaha.github.com/ From amitsaha.in at gmail.com Wed Mar 27 00:05:00 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Wed, 27 Mar 2013 09:05:00 +1000 Subject: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error In-Reply-To: References: Message-ID: On Wed, Mar 27, 2013 at 7:32 AM, Sean Carolan wrote: > >> Given that most folks on this list are only learning Python its pretty >> unlikely that they are building bespoke RPMs... >> >> You might find more experience of RPM building on the general Python >> mailing list/newsgroup. > > > Sorry 'bout that. I'll follow up with the bug report and possibly the > general list as well. FWIW, I tried the same thing with Python 3 sources on Fedora 18, and got the same error as you. But, where did you get the idea that you could build Python RPMs using $python setup.py bdist_rpm ? I thought that was only limited to building RPMs for python packages (including extensions), but not the Python interpreter itself. Please correct me if i am wrong. Okay, here is something for you to try in the meantime. Download the Python 2.7 SRPM (source RPM) from http://koji.fedoraproject.org/koji/packageinfo?packageID=130. May be the F17 version. Extract it to get the source files, patches and the SPEC file. If you are familiar with building RPM packages by hand, please try building it like any other package. That is, by copying the .spec file to SPECS and the .patch, .xz and other files in SOURCES and then doing rpmbuild -ba python.spec from the SPECS directory. Oh yes, please install the dependencies for building the package first by doing, yum-builddep before doing the build. It seems like it built the RPMs alright on my laptop. See if that helps. Best, Amit. -- http://amitsaha.github.com/ From phil_lor at bigpond.com Wed Mar 27 00:32:51 2013 From: phil_lor at bigpond.com (Phil) Date: Wed, 27 Mar 2013 09:32:51 +1000 Subject: [Tutor] Udp socket questio In-Reply-To: <51519F58.8000401@davea.name> References: <515186D4.9060303@bigpond.com> <51519F58.8000401@davea.name> Message-ID: <51523023.1050800@bigpond.com> On 26/03/13 23:15, Dave Angel wrote: >> >> Traceback (most recent call last): >> File "socket2.py", line 6, in >> import socket #for sockets >> File "/home/phil/Python/socket.py", line 7, in >> s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) >> AttributeError: 'module' object has no attribute 'AF_INET' >> > > Looks to me like you have your own file socket.py in /home/phil/Python Thanks Dave, I woke up during the early hours of the morning and realised what was going on. The name of my python file was not the same as the module but it was prefixed "socket" and than seems to be enough to cause a problem. The udp client still doesn't do what I want but at least the example runs without an error. -- Regards, Phil From sayanchatterjee at gmail.com Wed Mar 27 07:14:14 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Wed, 27 Mar 2013 11:44:14 +0530 Subject: [Tutor] HELP: Creating animation from multiple plots Message-ID: Dear All, I am a newbie to Python but have a fair know how of other languages i.e C etc. I want to run an astrophysical simulation in Python. All I have to do it to generate a set of 'plots' depending on a varying parameter and then stitch them up. 1) Is it possible to automatically generate different data files( say in the orders of 1000) with different names depending on a parameter? 2) Is it possible to plot the data sets right from Python itself and save the plots in different jpeg files to stitched upon later on. Awaiting your reply. Thank you in advance. Sincerely, Sayan -- -------------------------------------------------------------------------- *Sayan Chatterjee* Dept. of Physics and Meteorology IIT Kharagpur Lal Bahadur Shastry Hall of Residence Room AB 205 Mob: +91 9874513565 blog: www.blissprofound.blogspot.com Volunteer , Padakshep www.padakshep.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From amitsaha.in at gmail.com Wed Mar 27 07:23:13 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Wed, 27 Mar 2013 16:23:13 +1000 Subject: [Tutor] HELP: Creating animation from multiple plots In-Reply-To: References: Message-ID: Hi Sayan, On Wed, Mar 27, 2013 at 4:14 PM, Sayan Chatterjee wrote: > Dear All, > > I am a newbie to Python but have a fair know how of other languages i.e C > etc. > > I want to run an astrophysical simulation in Python. All I have to do it to > generate a set of 'plots' depending on a varying parameter and then stitch > them up. > > 1) Is it possible to automatically generate different data files( say in the > orders of 1000) with different names depending on a parameter? It certainly is. Are you talking about the file names being file_1001.txt, file_1002.txt and so on? If yes, let's say your parameter values are stored in param. Then something like this would do the trick: param_values = [1000,1001, 1005, 2001] for param in param_values: fname = 'file_' + str(param) # write to file fname # # Sorry if its different from what you are looking for. But yes, its certainly possible. > > 2) Is it possible to plot the data sets right from Python itself and save > the plots in different jpeg files to stitched upon later on. It is possible to generate plots and save each as JPEGs. [1]. What do you mean by stitching together? [1] http://stackoverflow.com/questions/8827016/matplotlib-savefig-in-jpeg-format Best, Amit -- http://amitsaha.github.com/ From amitsaha.in at gmail.com Wed Mar 27 07:27:38 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Wed, 27 Mar 2013 16:27:38 +1000 Subject: [Tutor] HELP: Creating animation from multiple plots In-Reply-To: References: Message-ID: On Wed, Mar 27, 2013 at 4:23 PM, Amit Saha wrote: > Hi Sayan, > > On Wed, Mar 27, 2013 at 4:14 PM, Sayan Chatterjee > wrote: >> Dear All, >> >> I am a newbie to Python but have a fair know how of other languages i.e C >> etc. >> >> I want to run an astrophysical simulation in Python. All I have to do it to >> generate a set of 'plots' depending on a varying parameter and then stitch >> them up. >> >> 1) Is it possible to automatically generate different data files( say in the >> orders of 1000) with different names depending on a parameter? > > It certainly is. Are you talking about the file names being > file_1001.txt, file_1002.txt and so on? If yes, let's say your > parameter values are stored in param. Then something like this would > do the trick: > > param_values = [1000,1001, 1005, 2001] > > for param in param_values: > fname = 'file_' + str(param) > > > # write to file fname > # > # > > > Sorry if its different from what you are looking for. But yes, its > certainly possible. > > >> >> 2) Is it possible to plot the data sets right from Python itself and save >> the plots in different jpeg files to stitched upon later on. > > It is possible to generate plots and save each as JPEGs. [1]. > > What do you mean by stitching together? You probably meant creating an animation from them. Yes, it is certainly possible. I will try to find a link which makes it really easy to create an animation out of a bunch of images. Which operating system are you on? -Amit. -- http://amitsaha.github.com/ From sayanchatterjee at gmail.com Wed Mar 27 07:36:39 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Wed, 27 Mar 2013 12:06:39 +0530 Subject: [Tutor] HELP: Creating animation from multiple plots In-Reply-To: References: Message-ID: Thanks a lot for your prompt reply. 1. Yes. This is exactly what I wanted. Creating a bunch of data sets and then writing script to plot them using gnuplot, but if something can produce directly 'plots' it will certainly be helpful. 2. Yes. By stitching them up I meant an animation.Sorry for the ambiguity. Exactly how we can do it Octave. Pls see this link: http://www.krizka.net/2009/11/06/creating-animations-with-octave/ I think Python is THE language, which may come to an immediate rescue. My OS is Linux Mint (Gnome 3) Sayan On 27 March 2013 11:57, Amit Saha wrote: > On Wed, Mar 27, 2013 at 4:23 PM, Amit Saha wrote: > > Hi Sayan, > > > > On Wed, Mar 27, 2013 at 4:14 PM, Sayan Chatterjee > > wrote: > >> Dear All, > >> > >> I am a newbie to Python but have a fair know how of other languages i.e > C > >> etc. > >> > >> I want to run an astrophysical simulation in Python. All I have to do > it to > >> generate a set of 'plots' depending on a varying parameter and then > stitch > >> them up. > >> > >> 1) Is it possible to automatically generate different data files( say > in the > >> orders of 1000) with different names depending on a parameter? > > > > It certainly is. Are you talking about the file names being > > file_1001.txt, file_1002.txt and so on? If yes, let's say your > > parameter values are stored in param. Then something like this would > > do the trick: > > > > param_values = [1000,1001, 1005, 2001] > > > > for param in param_values: > > fname = 'file_' + str(param) > > > > > > # write to file fname > > # > > # > > > > > > Sorry if its different from what you are looking for. But yes, its > > certainly possible. > > > > > >> > >> 2) Is it possible to plot the data sets right from Python itself and > save > >> the plots in different jpeg files to stitched upon later on. > > > > It is possible to generate plots and save each as JPEGs. [1]. > > > > What do you mean by stitching together? > > You probably meant creating an animation from them. Yes, it is > certainly possible. I will try to find a link which makes it really > easy to create an animation out of a bunch of images. Which operating > system are you on? > > -Amit. > > > > -- > http://amitsaha.github.com/ > -- -------------------------------------------------------------------------- *Sayan Chatterjee* Dept. of Physics and Meteorology IIT Kharagpur Lal Bahadur Shastry Hall of Residence Room AB 205 Mob: +91 9874513565 blog: www.blissprofound.blogspot.com Volunteer , Padakshep www.padakshep.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From amitsaha.in at gmail.com Wed Mar 27 07:42:49 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Wed, 27 Mar 2013 16:42:49 +1000 Subject: [Tutor] HELP: Creating animation from multiple plots In-Reply-To: References: Message-ID: On Wed, Mar 27, 2013 at 4:36 PM, Sayan Chatterjee wrote: > Thanks a lot for your prompt reply. > > 1. Yes. This is exactly what I wanted. Creating a bunch of data sets and > then writing script to plot them using gnuplot, but if something can produce > directly 'plots' it will certainly be helpful. Yes, indeed it is possible. You may want to explore matplotlib a bit. You can start with this tutorial [1]. [1] http://www.loria.fr/~rougier/teaching/matplotlib/ > > 2. Yes. By stitching them up I meant an animation.Sorry for the ambiguity. > Exactly how we can do it Octave. > > Pls see this link: > http://www.krizka.net/2009/11/06/creating-animations-with-octave/ Right, yes, if you see it uses mencoder/ffmpeg to create the animation. So, if you save your individual plots and then use one of these tools, you should be able to get the animation done. Matplotlib itself seems to have some Animated plotting capabilities, but I haven't had any experience with them. Best, Amit. -- http://amitsaha.github.com/ From sayanchatterjee at gmail.com Wed Mar 27 07:49:23 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Wed, 27 Mar 2013 12:19:23 +0530 Subject: [Tutor] HELP: Creating animation from multiple plots In-Reply-To: References: Message-ID: Yes, ffmpeg will do if multiple plots can be generated using mathplotlib . I'll look up the links you provided and get back to you, if I can't figure it out. :) On 27 March 2013 12:12, Amit Saha wrote: > On Wed, Mar 27, 2013 at 4:36 PM, Sayan Chatterjee > wrote: > > Thanks a lot for your prompt reply. > > > > 1. Yes. This is exactly what I wanted. Creating a bunch of data sets and > > then writing script to plot them using gnuplot, but if something can > produce > > directly 'plots' it will certainly be helpful. > > Yes, indeed it is possible. You may want to explore matplotlib a bit. > You can start with this tutorial [1]. > > [1] http://www.loria.fr/~rougier/teaching/matplotlib/ > > > > > 2. Yes. By stitching them up I meant an animation.Sorry for the > ambiguity. > > Exactly how we can do it Octave. > > > > Pls see this link: > > http://www.krizka.net/2009/11/06/creating-animations-with-octave/ > > Right, yes, if you see it uses mencoder/ffmpeg to create the > animation. So, if you save your individual plots and then use one of > these tools, you should be able to get the animation done. > > Matplotlib itself seems to have some Animated plotting capabilities, > but I haven't had any experience with them. > > > Best, > Amit. > > > -- > http://amitsaha.github.com/ > -- -------------------------------------------------------------------------- *Sayan Chatterjee* Dept. of Physics and Meteorology IIT Kharagpur Lal Bahadur Shastry Hall of Residence Room AB 205 Mob: +91 9874513565 blog: www.blissprofound.blogspot.com Volunteer , Padakshep www.padakshep.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From scarolan at gmail.com Wed Mar 27 14:05:27 2013 From: scarolan at gmail.com (Sean Carolan) Date: Wed, 27 Mar 2013 08:05:27 -0500 Subject: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error In-Reply-To: References: Message-ID: > But, where did you get the idea that you could build Python RPMs using > $python setup.py bdist_rpm ? I thought that was only limited to > building RPMs for python packages (including extensions), but not the > Python interpreter itself. Please correct me if i am wrong. > Ok, so it's only for module distributions? I assumed it could package Python itself as well, because it creates a *.spec file that reads like this: %define name Python %define version 2.7.3 %define unmangled_version 2.7.3 %define release 1 Summary: A high-level object-oriented programming language > Okay, here is something for you to try in the meantime. Download the > Python 2.7 SRPM (source RPM) from > http://koji.fedoraproject.org/koji/packageinfo?packageID=130. May be > the F17 version. > Extract it to get the source files, patches and the SPEC file. > Thank you, I will try this today. In the meantime I have started a thread on the "distutils" mailing list, so as not to spam "Tutor" with my build woes. regards, Sean -------------- next part -------------- An HTML attachment was scrubbed... URL: From sayanchatterjee at gmail.com Wed Mar 27 16:50:08 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Wed, 27 Mar 2013 21:20:08 +0530 Subject: [Tutor] IndexError: index out of bounds Message-ID: Dear all, When trying to print or assign array elements, getting the following error: Traceback (most recent call last): File "ZA.py", line 32, in p_za[i] = p_initial[i] + t*K*cos(K*p_initial[i]); IndexError: index out of bounds I am using Numpy, is it due to that? I am attaching the code herewith. -- -------------------------------------------------------------------------- *Sayan Chatterjee* Dept. of Physics and Meteorology IIT Kharagpur Lal Bahadur Shastry Hall of Residence Room AB 205 Mob: +91 9874513565 blog: www.blissprofound.blogspot.com Volunteer , Padakshep www.padakshep.org -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: ZA.py Type: application/octet-stream Size: 1180 bytes Desc: not available URL: From sayanchatterjee at gmail.com Wed Mar 27 16:59:29 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Wed, 27 Mar 2013 21:29:29 +0530 Subject: [Tutor] HELP: Creating animation from multiple plots In-Reply-To: References: Message-ID: Hi Amit, fo = fopen('fname','r+') fo.write("%d %d",j,counter) Is giving the following error: File "ZA.py", line 30, in fo = open('fname','r+') IOError: [Errno 2] No such file or directory: 'fname' Where is the mistake? Cheers, Sayan On 27 March 2013 12:20, Amit Saha wrote: > On Wed, Mar 27, 2013 at 4:49 PM, Sayan Chatterjee > wrote: > > Yes, ffmpeg will do if multiple plots can be generated using mathplotlib > . > > I'll look up the links you provided and get back to you, if I can't > figure > > it out. :) > > Sure, good luck! :) > > > > > > > > > > > On 27 March 2013 12:12, Amit Saha wrote: > >> > >> On Wed, Mar 27, 2013 at 4:36 PM, Sayan Chatterjee > >> wrote: > >> > Thanks a lot for your prompt reply. > >> > > >> > 1. Yes. This is exactly what I wanted. Creating a bunch of data sets > and > >> > then writing script to plot them using gnuplot, but if something can > >> > produce > >> > directly 'plots' it will certainly be helpful. > >> > >> Yes, indeed it is possible. You may want to explore matplotlib a bit. > >> You can start with this tutorial [1]. > >> > >> [1] http://www.loria.fr/~rougier/teaching/matplotlib/ > >> > >> > > >> > 2. Yes. By stitching them up I meant an animation.Sorry for the > >> > ambiguity. > >> > Exactly how we can do it Octave. > >> > > >> > Pls see this link: > >> > http://www.krizka.net/2009/11/06/creating-animations-with-octave/ > >> > >> Right, yes, if you see it uses mencoder/ffmpeg to create the > >> animation. So, if you save your individual plots and then use one of > >> these tools, you should be able to get the animation done. > >> > >> Matplotlib itself seems to have some Animated plotting capabilities, > >> but I haven't had any experience with them. > >> > >> > >> Best, > >> Amit. > >> > >> > >> -- > >> http://amitsaha.github.com/ > > > > > > > > > > -- > > > > > > > -------------------------------------------------------------------------- > > Sayan Chatterjee > > Dept. of Physics and Meteorology > > IIT Kharagpur > > Lal Bahadur Shastry Hall of Residence > > Room AB 205 > > Mob: +91 9874513565 > > blog: www.blissprofound.blogspot.com > > > > Volunteer , Padakshep > > www.padakshep.org > > > > -- > http://amitsaha.github.com/ > -- -------------------------------------------------------------------------- *Sayan Chatterjee* Dept. of Physics and Meteorology IIT Kharagpur Lal Bahadur Shastry Hall of Residence Room AB 205 Mob: +91 9874513565 blog: www.blissprofound.blogspot.com Volunteer , Padakshep www.padakshep.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Wed Mar 27 17:06:56 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 27 Mar 2013 12:06:56 -0400 Subject: [Tutor] HELP: Creating animation from multiple plots In-Reply-To: References: Message-ID: On Wed, Mar 27, 2013 at 11:59 AM, Sayan Chatterjee < sayanchatterjee at gmail.com> wrote: > Hi Amit, > > fo = fopen('fname','r+') > fo.write("%d %d",j,counter) > > > Is giving the following error: > > File "ZA.py", line 30, in > fo = open('fname','r+') > IOError: [Errno 2] No such file or directory: 'fname' > > Where is the mistake? > Where is the file called 'fname'? It must exist and be in the current directory > > Cheers, > Sayan > > > > > > > On 27 March 2013 12:20, Amit Saha wrote: > >> On Wed, Mar 27, 2013 at 4:49 PM, Sayan Chatterjee >> wrote: >> > Yes, ffmpeg will do if multiple plots can be generated using >> mathplotlib . >> > I'll look up the links you provided and get back to you, if I can't >> figure >> > it out. :) >> >> Sure, good luck! :) >> >> >> > >> > >> > >> > >> > On 27 March 2013 12:12, Amit Saha wrote: >> >> >> >> On Wed, Mar 27, 2013 at 4:36 PM, Sayan Chatterjee >> >> wrote: >> >> > Thanks a lot for your prompt reply. >> >> > >> >> > 1. Yes. This is exactly what I wanted. Creating a bunch of data sets >> and >> >> > then writing script to plot them using gnuplot, but if something can >> >> > produce >> >> > directly 'plots' it will certainly be helpful. >> >> >> >> Yes, indeed it is possible. You may want to explore matplotlib a bit. >> >> You can start with this tutorial [1]. >> >> >> >> [1] http://www.loria.fr/~rougier/teaching/matplotlib/ >> >> >> >> > >> >> > 2. Yes. By stitching them up I meant an animation.Sorry for the >> >> > ambiguity. >> >> > Exactly how we can do it Octave. >> >> > >> >> > Pls see this link: >> >> > http://www.krizka.net/2009/11/06/creating-animations-with-octave/ >> >> >> >> Right, yes, if you see it uses mencoder/ffmpeg to create the >> >> animation. So, if you save your individual plots and then use one of >> >> these tools, you should be able to get the animation done. >> >> >> >> Matplotlib itself seems to have some Animated plotting capabilities, >> >> but I haven't had any experience with them. >> >> >> >> >> >> Best, >> >> Amit. >> >> >> >> >> >> -- >> >> http://amitsaha.github.com/ >> > >> > >> > >> > >> > -- >> > >> > >> > >> -------------------------------------------------------------------------- >> > Sayan Chatterjee >> > Dept. of Physics and Meteorology >> > IIT Kharagpur >> > Lal Bahadur Shastry Hall of Residence >> > Room AB 205 >> > Mob: +91 9874513565 >> > blog: www.blissprofound.blogspot.com >> > >> > Volunteer , Padakshep >> > www.padakshep.org >> >> >> >> -- >> http://amitsaha.github.com/ >> > > > > -- > > > -------------------------------------------------------------------------- > *Sayan Chatterjee* > Dept. of Physics and Meteorology > IIT Kharagpur > Lal Bahadur Shastry Hall of Residence > Room AB 205 > Mob: +91 9874513565 > blog: www.blissprofound.blogspot.com > > Volunteer , Padakshep > www.padakshep.org > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Wed Mar 27 17:08:18 2013 From: wprins at gmail.com (Walter Prins) Date: Wed, 27 Mar 2013 16:08:18 +0000 Subject: [Tutor] HELP: Creating animation from multiple plots In-Reply-To: References: Message-ID: Hello, On 27 March 2013 15:59, Sayan Chatterjee wrote: > Hi Amit, > > fo = fopen('fname','r+') > fo.write("%d %d",j,counter) > > > Is giving the following error: > > File "ZA.py", line 30, in > fo = open('fname','r+') > IOError: [Errno 2] No such file or directory: 'fname' > > Where is the mistake? > You are trying to open a file named literally "fname" due to putting it in quotes, you probably want to drop the quotes. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Wed Mar 27 17:04:04 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 27 Mar 2013 12:04:04 -0400 Subject: [Tutor] IndexError: index out of bounds In-Reply-To: References: Message-ID: On Wed, Mar 27, 2013 at 11:50 AM, Sayan Chatterjee < sayanchatterjee at gmail.com> wrote: > Dear all, > > When trying to print or assign array elements, getting the following error: > > Traceback (most recent call last): > File "ZA.py", line 32, in > p_za[i] = p_initial[i] + t*K*cos(K*p_initial[i]); > You declare p_za = [] above. So there is no p_za[i]. You should use append since you are adding elements to the end of the list. > IndexError: index out of bounds > > I am using Numpy, is it due to that? I am attaching the code herewith. > > > > -- > > > -------------------------------------------------------------------------- > *Sayan Chatterjee* > Dept. of Physics and Meteorology > IIT Kharagpur > Lal Bahadur Shastry Hall of Residence > Room AB 205 > Mob: +91 9874513565 > blog: www.blissprofound.blogspot.com > > Volunteer , Padakshep > www.padakshep.org > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Wed Mar 27 17:14:03 2013 From: wprins at gmail.com (Walter Prins) Date: Wed, 27 Mar 2013 16:14:03 +0000 Subject: [Tutor] IndexError: index out of bounds In-Reply-To: References: Message-ID: Hi, On 27 March 2013 15:50, Sayan Chatterjee wrote: > Dear all, > > When trying to print or assign array elements, getting the following error: > > Traceback (most recent call last): > File "ZA.py", line 32, in > p_za[i] = p_initial[i] + t*K*cos(K*p_initial[i]); > IndexError: index out of bounds > > I am using Numpy, is it due to that? I am attaching the code herewith. > Not Numpy no. The p_za list appears to be empty at the point where the above assgnment to p_za[i] is done, hence you get the "IndexError" message. You should initialise p_za to be as long as needed first. Maybe by simply using p_za = [None] * N instead of assigning [], or alternately perhaps by appending instead at the point where you first reference p_ze[i]. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From sayanchatterjee at gmail.com Wed Mar 27 17:17:27 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Wed, 27 Mar 2013 21:47:27 +0530 Subject: [Tutor] HELP: Creating animation from multiple plots In-Reply-To: References: Message-ID: for t in range(0,200): fname = 'file_' + str(t) So it will assign fname values file_0, file_1 so on. Dropping the quotes is giving me IOError: [Errno 2] No such file or directory: 'file_0' Indeed the file is not present. In C we write,if we have to record data in a file FILE *fp fp = fopen("file.dat","w") Here I want to write different data sets in files having different name i.e I want to create the files with the data sets. I am quite new to Python, so you can assume zero knowledge while answering. Thanks for your support. :) On 27 March 2013 21:38, Walter Prins wrote: > Hello, > > On 27 March 2013 15:59, Sayan Chatterjee wrote: > >> Hi Amit, >> >> fo = fopen('fname','r+') >> fo.write("%d %d",j,counter) >> >> >> Is giving the following error: >> >> File "ZA.py", line 30, in >> fo = open('fname','r+') >> IOError: [Errno 2] No such file or directory: 'fname' >> >> Where is the mistake? >> > > You are trying to open a file named literally "fname" due to putting it in > quotes, you probably want to drop the quotes. > > Walter > -- -------------------------------------------------------------------------- *Sayan Chatterjee* Dept. of Physics and Meteorology IIT Kharagpur Lal Bahadur Shastry Hall of Residence Room AB 205 Mob: +91 9874513565 blog: www.blissprofound.blogspot.com Volunteer , Padakshep www.padakshep.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From sayanchatterjee at gmail.com Wed Mar 27 17:24:42 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Wed, 27 Mar 2013 21:54:42 +0530 Subject: [Tutor] HELP: Creating animation from multiple plots In-Reply-To: References: Message-ID: Putting "w" instead of "r+" probably solves the problem. The error is not showing now. On 27 March 2013 21:47, Sayan Chatterjee wrote: > for t in range(0,200): > fname = 'file_' + str(t) > > So it will assign fname values file_0, file_1 so on. Dropping the quotes > is giving me > > IOError: [Errno 2] No such file or directory: 'file_0' > > > Indeed the file is not present. In C we write,if we have to record data in > a file > > FILE *fp > > fp = fopen("file.dat","w") > > > Here I want to write different data sets in files having different name > i.e I want to create the files with the data sets. I am quite new to > Python, so you can assume zero knowledge while answering. Thanks for your > support. :) > > > On 27 March 2013 21:38, Walter Prins wrote: > >> Hello, >> >> On 27 March 2013 15:59, Sayan Chatterjee wrote: >> >>> Hi Amit, >>> >>> fo = fopen('fname','r+') >>> fo.write("%d %d",j,counter) >>> >>> >>> Is giving the following error: >>> >>> File "ZA.py", line 30, in >>> fo = open('fname','r+') >>> IOError: [Errno 2] No such file or directory: 'fname' >>> >>> Where is the mistake? >>> >> >> You are trying to open a file named literally "fname" due to putting it >> in quotes, you probably want to drop the quotes. >> >> Walter >> > > > > -- > > > -------------------------------------------------------------------------- > *Sayan Chatterjee* > Dept. of Physics and Meteorology > IIT Kharagpur > Lal Bahadur Shastry Hall of Residence > Room AB 205 > Mob: +91 9874513565 > blog: www.blissprofound.blogspot.com > > Volunteer , Padakshep > www.padakshep.org > -- -------------------------------------------------------------------------- *Sayan Chatterjee* Dept. of Physics and Meteorology IIT Kharagpur Lal Bahadur Shastry Hall of Residence Room AB 205 Mob: +91 9874513565 blog: www.blissprofound.blogspot.com Volunteer , Padakshep www.padakshep.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From bodsda at googlemail.com Wed Mar 27 17:28:05 2013 From: bodsda at googlemail.com (Bod Soutar) Date: Wed, 27 Mar 2013 16:28:05 +0000 Subject: [Tutor] HELP: Creating animation from multiple plots In-Reply-To: References: Message-ID: You were opening the file for reading, rather than writing. It therefore was expecting to find a file. Change fo = open('fname','r+') to fo = open('fname','w') Bodsda On 27 March 2013 16:17, Sayan Chatterjee wrote: > for t in range(0,200): > fname = 'file_' + str(t) > > So it will assign fname values file_0, file_1 so on. Dropping the quotes is > giving me > > IOError: [Errno 2] No such file or directory: 'file_0' > > > Indeed the file is not present. In C we write,if we have to record data in a > file > > FILE *fp > > fp = fopen("file.dat","w") > > > Here I want to write different data sets in files having different name i.e > I want to create the files with the data sets. I am quite new to Python, so > you can assume zero knowledge while answering. Thanks for your support. :) > > > On 27 March 2013 21:38, Walter Prins wrote: >> >> Hello, >> >> On 27 March 2013 15:59, Sayan Chatterjee >> wrote: >>> >>> Hi Amit, >>> >>> fo = fopen('fname','r+') >>> fo.write("%d %d",j,counter) >>> >>> >>> Is giving the following error: >>> >>> File "ZA.py", line 30, in >>> fo = open('fname','r+') >>> IOError: [Errno 2] No such file or directory: 'fname' >>> >>> Where is the mistake? >> >> >> You are trying to open a file named literally "fname" due to putting it in >> quotes, you probably want to drop the quotes. >> >> Walter > > > > > -- > > > -------------------------------------------------------------------------- > Sayan Chatterjee > Dept. of Physics and Meteorology > IIT Kharagpur > Lal Bahadur Shastry Hall of Residence > Room AB 205 > Mob: +91 9874513565 > blog: www.blissprofound.blogspot.com > > Volunteer , Padakshep > www.padakshep.org > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From sayanchatterjee at gmail.com Wed Mar 27 17:31:26 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Wed, 27 Mar 2013 22:01:26 +0530 Subject: [Tutor] IndexError: index out of bounds In-Reply-To: References: Message-ID: p_za = [None]*N is not giving away the error message. for i in range(0,N): p_za.append = p_initial[i] + t*K*cos(K*p_initial[i]); is also not working. Could you please redirect me to a link where the example is demonstrated? What is the simplest way to assign an array element a value? i.e the C analogue of: int array[200] for(i=0;i<200;i++) array[i] = 2*i + 5; On 27 March 2013 21:44, Walter Prins wrote: > Hi, > > > On 27 March 2013 15:50, Sayan Chatterjee wrote: > >> Dear all, >> >> When trying to print or assign array elements, getting the following >> error: >> >> Traceback (most recent call last): >> File "ZA.py", line 32, in >> p_za[i] = p_initial[i] + t*K*cos(K*p_initial[i]); >> IndexError: index out of bounds >> >> I am using Numpy, is it due to that? I am attaching the code herewith. >> > > Not Numpy no. The p_za list appears to be empty at the point where the > above assgnment to p_za[i] is done, hence you get the "IndexError" message. > You should initialise p_za to be as long as needed first. Maybe by simply > using p_za = [None] * N instead of assigning [], or alternately perhaps by > appending instead at the point where you first reference p_ze[i]. > > Walter > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- -------------------------------------------------------------------------- *Sayan Chatterjee* Dept. of Physics and Meteorology IIT Kharagpur Lal Bahadur Shastry Hall of Residence Room AB 205 Mob: +91 9874513565 blog: www.blissprofound.blogspot.com Volunteer , Padakshep www.padakshep.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From sayanchatterjee at gmail.com Wed Mar 27 17:32:03 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Wed, 27 Mar 2013 22:02:03 +0530 Subject: [Tutor] HELP: Creating animation from multiple plots In-Reply-To: References: Message-ID: Oh yes, thanks. That worked. :) On 27 March 2013 21:58, Bod Soutar wrote: > You were opening the file for reading, rather than writing. It > therefore was expecting to find a file. > Change > fo = open('fname','r+') > to > fo = open('fname','w') > > Bodsda > > On 27 March 2013 16:17, Sayan Chatterjee > wrote: > > for t in range(0,200): > > fname = 'file_' + str(t) > > > > So it will assign fname values file_0, file_1 so on. Dropping the quotes > is > > giving me > > > > IOError: [Errno 2] No such file or directory: 'file_0' > > > > > > Indeed the file is not present. In C we write,if we have to record data > in a > > file > > > > FILE *fp > > > > fp = fopen("file.dat","w") > > > > > > Here I want to write different data sets in files having different name > i.e > > I want to create the files with the data sets. I am quite new to Python, > so > > you can assume zero knowledge while answering. Thanks for your support. > :) > > > > > > On 27 March 2013 21:38, Walter Prins wrote: > >> > >> Hello, > >> > >> On 27 March 2013 15:59, Sayan Chatterjee > >> wrote: > >>> > >>> Hi Amit, > >>> > >>> fo = fopen('fname','r+') > >>> fo.write("%d %d",j,counter) > >>> > >>> > >>> Is giving the following error: > >>> > >>> File "ZA.py", line 30, in > >>> fo = open('fname','r+') > >>> IOError: [Errno 2] No such file or directory: 'fname' > >>> > >>> Where is the mistake? > >> > >> > >> You are trying to open a file named literally "fname" due to putting it > in > >> quotes, you probably want to drop the quotes. > >> > >> Walter > > > > > > > > > > -- > > > > > > > -------------------------------------------------------------------------- > > Sayan Chatterjee > > Dept. of Physics and Meteorology > > IIT Kharagpur > > Lal Bahadur Shastry Hall of Residence > > Room AB 205 > > Mob: +91 9874513565 > > blog: www.blissprofound.blogspot.com > > > > Volunteer , Padakshep > > www.padakshep.org > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > > -- -------------------------------------------------------------------------- *Sayan Chatterjee* Dept. of Physics and Meteorology IIT Kharagpur Lal Bahadur Shastry Hall of Residence Room AB 205 Mob: +91 9874513565 blog: www.blissprofound.blogspot.com Volunteer , Padakshep www.padakshep.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Mar 27 17:36:52 2013 From: __peter__ at web.de (Peter Otten) Date: Wed, 27 Mar 2013 17:36:52 +0100 Subject: [Tutor] HELP: Creating animation from multiple plots References: Message-ID: Sayan Chatterjee wrote: > for t in range(0,200): > fname = 'file_' + str(t) > > So it will assign fname values file_0, file_1 so on. Dropping the quotes > is giving me > > IOError: [Errno 2] No such file or directory: 'file_0' > > > Indeed the file is not present. In C we write,if we have to record data in > a file > > FILE *fp > > fp = fopen("file.dat","w") > > > Here I want to write different data sets in files having different name > i.e I want to create the files with the data sets. I am quite new to > Python, so you can assume zero knowledge while answering. Thanks for your > support. :) If you try to open a non-existent file in "r+" mode in C you should get an error, too. The following C code FILE * f; int i; char filename[100]; for (i=0; i<10; i++) { sprintf(filename, "foo%d.dat", i); FILE * f = fopen(filename, "w"); /* write stuff to file */ ... fclose(f); } translates into this piece of Python: for i in range(10): filename = "foo%d.dat" % i with open(filename, "w") as f: # write stuff to file ... From wprins at gmail.com Wed Mar 27 17:59:59 2013 From: wprins at gmail.com (Walter Prins) Date: Wed, 27 Mar 2013 16:59:59 +0000 Subject: [Tutor] IndexError: index out of bounds In-Reply-To: References: Message-ID: Hi Sayan, On 27 March 2013 16:31, Sayan Chatterjee wrote: > p_za = [None]*N is not giving away the error message. > > for i in range(0,N): > p_za.append = p_initial[i] + t*K*cos(K*p_initial[i]); is also not > working. > append() is a method, so using append you want something like: for i in range(0,N): p_za.append( p_initial[i] + t*K*cos(K*p_initial[i]) ); After every loop iteration, the list grows by having one item appended to it, being the result of the expression: p_initial[i] + t*K*cos(K*p_initial[i]) > Could you please redirect me to a link where the example is demonstrated? > http://courses.cms.caltech.edu/cs11/material/python/misc/python_idioms.html See the paragraph on "Sequence multiplication". > What is the simplest way to assign an array element a value? > What you have is fine for assignment to a particular slot in the list. What you've missed and has already been pointed out, is to initialise/set the length of your list first, before trying to set the value of arbitrary slots. In the C example you posted the array is declared with length 200 up front. In your Python code however you assign [], which is a list of length 0. By contrast, the expression I gave you before, e.g. [None] * N, generates a list of length N, with each element in the list being the None object, thus initialising the list, ensuring that you can later assign to arbitrary slots when needed. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Mar 27 18:13:30 2013 From: __peter__ at web.de (Peter Otten) Date: Wed, 27 Mar 2013 18:13:30 +0100 Subject: [Tutor] IndexError: index out of bounds References: Message-ID: Sayan Chatterjee wrote: > When trying to print or assign array elements, getting the following > error: > > Traceback (most recent call last): > File "ZA.py", line 32, in > p_za[i] = p_initial[i] + t*K*cos(K*p_initial[i]); > IndexError: index out of bounds > > I am using Numpy, is it due to that? I am attaching the code herewith. If you are using numpy it is likely that you don't need to loop over the index explicitly. Assuming t and K are scalars, and p_initial is a numpy array you can write p_za = p_initial + t * K * numpy.cos(K*p_initial) For example: >>> import numpy >>> p_initial = numpy.array([1.2, 3.4, 5.6]) >>> t = 1.1 >>> K = 2.2 >>> p_initial + t*K*numpy.cos(K*p_initial) array([-0.92189929, 4.28408588, 7.94692559]) Quite powerful, once you get the knack of it. From sayanchatterjee at gmail.com Wed Mar 27 18:36:01 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Wed, 27 Mar 2013 23:06:01 +0530 Subject: [Tutor] IndexError: index out of bounds In-Reply-To: References: Message-ID: Hi Walter, Thanks a lot! Yes, now I get your point. append is working perfectly fine. Hi Peter: Exactly. It's very nice. Indices needn't have to be mentioned explicitly. No explicit looping and the thing is done! But I have a question, whenever we want to do operations on the individual array elements, don't we have to mention the indices explicitly i.e p_za[i]? 1) Traceback (most recent call last): File "ZA.py", line 44, in p_za = p_za % 4 TypeError: unsupported operand type(s) for %: 'list' and 'int' 2) Traceback (most recent call last): File "ZA.py", line 43, in if p_za[i] > 4.0: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() When the i indices are removed * (1) * error message is showing up and when i is included *(2) *is shown.* * On 27 March 2013 22:29, Walter Prins wrote: > Hi Sayan, > > On 27 March 2013 16:31, Sayan Chatterjee wrote: > >> p_za = [None]*N is not giving away the error message. >> >> for i in range(0,N): >> p_za.append = p_initial[i] + t*K*cos(K*p_initial[i]); is also not >> working. >> > > append() is a method, so using append you want something like: > > for i in range(0,N): > p_za.append( p_initial[i] + t*K*cos(K*p_initial[i]) ); > > After every loop iteration, the list grows by having one item appended to > it, being the result of the expression: p_initial[i] + > t*K*cos(K*p_initial[i]) > > >> Could you please redirect me to a link where the example is demonstrated? >> > > http://courses.cms.caltech.edu/cs11/material/python/misc/python_idioms.html > > See the paragraph on "Sequence multiplication". > > > >> What is the simplest way to assign an array element a value? >> > > What you have is fine for assignment to a particular slot in the list. > What you've missed and has already been pointed out, is to initialise/set > the length of your list first, before trying to set the value of arbitrary > slots. In the C example you posted the array is declared with length 200 > up front. In your Python code however you assign [], which is a list of > length 0. By contrast, the expression I gave you before, e.g. [None] * N, > generates a list of length N, with each element in the list being the None > object, thus initialising the list, ensuring that you can later assign to > arbitrary slots when needed. > > Walter > > > -- -------------------------------------------------------------------------- *Sayan Chatterjee* Dept. of Physics and Meteorology IIT Kharagpur Lal Bahadur Shastry Hall of Residence Room AB 205 Mob: +91 9874513565 blog: www.blissprofound.blogspot.com Volunteer , Padakshep www.padakshep.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Mar 27 19:05:11 2013 From: __peter__ at web.de (Peter Otten) Date: Wed, 27 Mar 2013 19:05:11 +0100 Subject: [Tutor] IndexError: index out of bounds References: Message-ID: Sayan Chatterjee wrote: > Hi Walter, > Thanks a lot! > > Yes, now I get your point. append is working perfectly fine. > > Hi Peter: > > Exactly. It's very nice. Indices needn't have to be mentioned explicitly. > No explicit looping and the thing is done! > > But I have a question, whenever we want to do operations on the individual > array elements, don't we have to mention the indices explicitly i.e > p_za[i]? For Python's built-in list, yes, but not for numpy arrays. > 1) Traceback (most recent call last): > File "ZA.py", line 44, in > p_za = p_za % 4 > TypeError: unsupported operand type(s) for %: 'list' and 'int' >>> items = [3, 4, 5] >>> items % 2 Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for %: 'list' and 'int' >>> items = numpy.array(items) >>> items % 2 array([1, 0, 1]) Even for lists you can do better than using an explicit index, you can iterate over its members: >>> items = [3, 4, 5] >>> [v % 2 for v in items] [1, 0, 1] > 2) Traceback (most recent call last): > File "ZA.py", line 43, in > if p_za[i] > 4.0: > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() > > When the i indices are removed * (1) * error message is showing up and > when i is included *(2) *is shown.* * You are probably seeing that error because p_za[i] is a numpy.array, i. e. you have a list of arrays: >>> items = [numpy.array([1,2]), numpy.array([3,4])] >>> items[0] > 4 array([False, False], dtype=bool) >>> if items[0] > 4: pass ... Traceback (most recent call last): File "", line 1, in ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() How you managed to get there and what you actually want to achieve -- I can't tell from what you provide. Perhaps you can give a little more context, in code, but more importantly in prose. From alan.gauld at btinternet.com Wed Mar 27 19:07:18 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 27 Mar 2013 18:07:18 +0000 Subject: [Tutor] IndexError: index out of bounds In-Reply-To: References: Message-ID: On 27/03/13 17:36, Sayan Chatterjee wrote: > 2) Traceback (most recent call last): > File "ZA.py", line 43, in > if p_za[i] > 4.0: > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() This implies that p_za[i] is actually an array. So maybe p_za is a list (of arrays)? Try printing it to see. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sayanchatterjee at gmail.com Wed Mar 27 19:54:13 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Thu, 28 Mar 2013 00:24:13 +0530 Subject: [Tutor] IndexError: index out of bounds In-Reply-To: References: Message-ID: Hi Peter, Thanks!! Yes, when handled as a numpy array, it's working fine! Traceback (most recent call last): File "ZA.py", line 59, in if temp_za == j: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() This error occurs when the temp_za ( a numpy array, print temp_za works fine) is compared with j. I am attaching the code. Another question how do I get an integer value for p_za / 2 . Type casting with int says: TypeError: only length-1 arrays can be converted to Python scalars. On 27 March 2013 23:37, Alan Gauld wrote: > On 27/03/13 17:36, Sayan Chatterjee wrote: > > 2) Traceback (most recent call last): >> File "ZA.py", line 43, in >> if p_za[i] > 4.0: >> ValueError: The truth value of an array with more than one element is >> ambiguous. Use a.any() or a.all() >> > > This implies that p_za[i] is actually an array. > So maybe p_za is a list (of arrays)? > Try printing it to see. > > > > -- > Alan G > 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 > -- -------------------------------------------------------------------------- *Sayan Chatterjee* Dept. of Physics and Meteorology IIT Kharagpur Lal Bahadur Shastry Hall of Residence Room AB 205 Mob: +91 9874513565 blog: www.blissprofound.blogspot.com Volunteer , Padakshep www.padakshep.org -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: ZA.py Type: application/octet-stream Size: 1083 bytes Desc: not available URL: From cheisterkamp at gmail.com Wed Mar 27 20:34:14 2013 From: cheisterkamp at gmail.com (Cor Heisterkamp) Date: Wed, 27 Mar 2013 20:34:14 +0100 Subject: [Tutor] Modules Message-ID: Hi, I just started with Python and found a course named "Python programming" by Jody S. Gunther. My problem starts with the chapter "Introduction to Modules". The first line in the program is: from tkinter import * and here I'm getting an error: ImportError: No module named tkinter What to do? -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Wed Mar 27 21:00:54 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 27 Mar 2013 14:00:54 -0600 Subject: [Tutor] Modules In-Reply-To: References: Message-ID: > I just started with Python and found a course named "Python programming" by > Jody S. Gunther. > My problem starts with the chapter "Introduction to Modules". > The first line in the program is: > from tkinter import * > and here I'm getting an error: > ImportError: No module named tkinter Case matters. "Tkinter" should be capitalized. Best of wishes! From breamoreboy at yahoo.co.uk Wed Mar 27 21:12:08 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 27 Mar 2013 20:12:08 +0000 Subject: [Tutor] Modules In-Reply-To: References: Message-ID: On 27/03/2013 19:34, Cor Heisterkamp wrote: > Hi, > > I just started with Python and found a course named "Python programming" > by Jody S. Gunther. > My problem starts with the chapter "Introduction to Modules". > The first line in the program is: > from tkinter import * > and here I'm getting an error: > ImportError: No module named tkinter > > What to do? > > This works for me with Python 3.3 on Windows Vista. What OS and Python version are you using, as I believe that this was tKinter in Python 2? -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From joel.goldstick at gmail.com Wed Mar 27 21:31:45 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 27 Mar 2013 16:31:45 -0400 Subject: [Tutor] Modules In-Reply-To: References: Message-ID: On Wed, Mar 27, 2013 at 4:12 PM, Mark Lawrence wrote: > On 27/03/2013 19:34, Cor Heisterkamp wrote: > >> Hi, >> >> I just started with Python and found a course named "Python programming" >> by Jody S. Gunther. >> My problem starts with the chapter "Introduction to Modules". >> The first line in the program is: >> from tkinter import * >> and here I'm getting an error: >> ImportError: No module named tkinter >> >> What to do? >> >> google it and you find: http://wiki.python.org/moin/TkInter >> > Step 2 - can Tkinter be imported? Try the correct command for your version at the Python prompt: >>> import Tkinter # no underscore, uppercase 'T' for versions prior to V3.0 >>> import tkinter # no underscore, lowercase 't' for V3.0 and later > > This works for me with Python 3.3 on Windows Vista. What OS and Python > version are you using, as I believe that this was tKinter in Python 2? > > -- > If you're using GoogleCrap? please read this http://wiki.python.org/moin/* > *GoogleGroupsPython . > > Mark Lawrence > > > ______________________________**_________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Mar 27 22:09:26 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 27 Mar 2013 21:09:26 +0000 Subject: [Tutor] Modules In-Reply-To: References: Message-ID: On 27/03/13 19:34, Cor Heisterkamp wrote: > My problem starts with the chapter "Introduction to Modules". > The first line in the program is: > from tkinter import * > and here I'm getting an error: > ImportError: No module named tkinter Thats an unfortunate exampole the author has chosen. Tkinter is an unusual module in that it requires support for Tcl/Tk to be compiled into the interpreter. This is not always the case. So there are 3 possible causes of the error: 1) Your python does not have support for Tcl/Tk built in. Which version of Python and which OS are you using? If your version does not support Tcl you need to either build a version from source or find a copy for your OS with Tkinter support. The default downloads for MacOS, Windows and most Linuxes have it but the OS installed versions often don't. 2) The tutor is aimed at Python v3 but you are using v2 Which version of Python are you running? What does it say when you start the Python interpreter >>> prompt? 3) The tutor and you are both on V2 but you mistyped (or it has a typo) that says tkinter when it should say Tkinter. Try typing import Tkinter HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From __peter__ at web.de Wed Mar 27 22:22:10 2013 From: __peter__ at web.de (Peter Otten) Date: Wed, 27 Mar 2013 22:22:10 +0100 Subject: [Tutor] IndexError: index out of bounds References: Message-ID: Sayan Chatterjee wrote: > Yes, when handled as a numpy array, it's working fine! > > Traceback (most recent call last): > File "ZA.py", line 59, in > if temp_za == j: > ValueError: The truth value of an array with more than one element is > ambiguous. Use a.any() or a.all() >From the attached script: > if temp_za == j: > counter += 1 Do you want to count the entries? >>> temp_za = numpy.array([1, 2, 3, 2, 1, 1]) >>> (temp_za == 1).sum() 3 > This error occurs when the temp_za ( a numpy array, print temp_za works > fine) is compared with j. I am attaching the code. I'm sorry, I am lacking the domain knowledge to make sense of it. Just one more remark: [] < 0.0 is always False, regardless of the contents of the list > Another question how do I get an integer value for p_za / 2 . Type > casting with int says: > TypeError: only length-1 arrays can be converted to Python scalars. I'd use numpy.array(p_za//2, dtype=int) but I'm not a numpy expert. As you dig deeper the tutor mailing list may not be the best place to ask -- numpy has a dedicated mailing list of its own. From amitsaha.in at gmail.com Wed Mar 27 23:08:31 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Thu, 28 Mar 2013 08:08:31 +1000 Subject: [Tutor] Building Python 2.7.3 on RHEL 5.8 x86_64 -- Syntax Error In-Reply-To: References: Message-ID: On Wed, Mar 27, 2013 at 11:05 PM, Sean Carolan wrote: > >> But, where did you get the idea that you could build Python RPMs using >> $python setup.py bdist_rpm ? I thought that was only limited to >> building RPMs for python packages (including extensions), but not the >> Python interpreter itself. Please correct me if i am wrong. > > > Ok, so it's only for module distributions? I assumed it could package > Python itself as well, because it creates a *.spec file that reads like > this: > > %define name Python > %define version 2.7.3 > %define unmangled_version 2.7.3 > %define release 1 > > Summary: A high-level object-oriented programming language Hmm. Let's see, it was a guess on my part as well. > >> >> Okay, here is something for you to try in the meantime. Download the >> Python 2.7 SRPM (source RPM) from >> http://koji.fedoraproject.org/koji/packageinfo?packageID=130. May be >> the F17 version. >> Extract it to get the source files, patches and the SPEC file. > > > Thank you, I will try this today. In the meantime I have started a thread > on the "distutils" mailing list, so as not to spam "Tutor" with my build > woes. I will follow the thread there and see what comes out of it. This is interesting! FWIW, I tried to get the SRPM and build Python 2.7 on RHEL 5. Quickly realized that it lacks, yum-builddep, yumdownloader, etc :-/ So, just left it there for then. I will have to try again the manual way. -Amit. -- http://amitsaha.github.com/ From eryksun at gmail.com Thu Mar 28 00:05:53 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 27 Mar 2013 19:05:53 -0400 Subject: [Tutor] Modules In-Reply-To: References: Message-ID: On Wed, Mar 27, 2013 at 5:09 PM, Alan Gauld wrote: > > Tkinter is an unusual module in that it requires support for Tcl/Tk to be > compiled into the interpreter. This is not always the case. The _tkinter module is a C extension that links to Tcl/Tk. On Debian Linux, _tkinter (_tkinter.so) is in the package python-tk / python3-tk. The ImportError raised by "import tkinter" suggests the required package. Except for Python 3.2 it incorrectly suggests the 2.x package: ImportError: No module named _tkinter, please install the python-tk package IIRC the official Python installer on Windows defaults to installing tkinter, but it is optional. From mcooganj at gmail.com Thu Mar 28 07:27:15 2013 From: mcooganj at gmail.com (Matthew Johnson) Date: Thu, 28 Mar 2013 17:27:15 +1100 Subject: [Tutor] Help with iterators In-Reply-To: References: Message-ID: <7826743254286429930@unknownmsgid> Dear list, Sorry for the delay -- it has taken some time for me to get these emails. It appears i made some dumb error when typing out the description. Mitya Sirenef was correct to ignore my words and to focus on my code. Thanks for your help. I may ask again / for more help when i feel i have tried sufficiently hard to absorb the answers below. Thanks again mj On 22/03/2013, at 6:24 PM, "tutor-request at python.org" 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: Help with iterators (Mitya Sirenef) > 2. Re: Help with iterators (Steven D'Aprano) > 3. Re: Help with iterators (Steven D'Aprano) > 4. Re: Help with iterators (Mitya Sirenef) > 5. Please Help (Arijit Ukil) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Thu, 21 Mar 2013 21:39:12 -0400 > From: Mitya Sirenef > To: tutor at python.org > Subject: Re: [Tutor] Help with iterators > Message-ID: <514BB640.5050406 at lightbird.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 03/21/2013 08:39 PM, Matthew Johnson wrote: >> Dear list, >> >> I have been trying to understand out how to use iterators and in >> particular groupby statements. I am, however, quite lost. >> >> I wish to subset the below list, selecting the observations that have >> an ID ('realtime_start') value that is greater than some date (i've >> used the variable name maxDate), and in the case that there is more >> than one such record, returning only the one that has the largest ID >> ('realtime_start'). >> >> The code below does the job, however i have the impression that it >> might be done in a more python way using iterators and groupby >> statements. >> >> could someone please help me understand how to go from this code to >> the pythonic idiom? >> >> thanks in advance, >> >> Matt Johnson >> >> _________________ >> >> ## Code example >> >> import pprint >> >> obs = [{'date': '2012-09-01', >> 'realtime_end': '2013-02-18', >> 'realtime_start': '2012-10-15', >> 'value': '231.951'}, >> {'date': '2012-09-01', >> 'realtime_end': '2013-02-18', >> 'realtime_start': '2012-11-15', >> 'value': '231.881'}, >> {'date': '2012-10-01', >> 'realtime_end': '2013-02-18', >> 'realtime_start': '2012-11-15', >> 'value': '231.751'}, >> {'date': '2012-10-01', >> 'realtime_end': '9999-12-31', >> 'realtime_start': '2012-12-19', >> 'value': '231.623'}, >> {'date': '2013-02-01', >> 'realtime_end': '9999-12-31', >> 'realtime_start': '2013-03-21', >> 'value': '231.157'}, >> {'date': '2012-11-01', >> 'realtime_end': '2013-02-18', >> 'realtime_start': '2012-12-14', >> 'value': '231.025'}, >> {'date': '2012-11-01', >> 'realtime_end': '9999-12-31', >> 'realtime_start': '2013-01-19', >> 'value': '231.071'}, >> {'date': '2012-12-01', >> 'realtime_end': '2013-02-18', >> 'realtime_start': '2013-01-16', >> 'value': '230.979'}, >> {'date': '2012-12-01', >> 'realtime_end': '9999-12-31', >> 'realtime_start': '2013-02-19', >> 'value': '231.137'}, >> {'date': '2012-12-01', >> 'realtime_end': '9999-12-31', >> 'realtime_start': '2013-03-19', >> 'value': '231.197'}, >> {'date': '2013-01-01', >> 'realtime_end': '9999-12-31', >> 'realtime_start': '2013-02-21', >> 'value': '231.198'}, >> {'date': '2013-01-01', >> 'realtime_end': '9999-12-31', >> 'realtime_start': '2013-03-21', >> 'value': '231.222'}] >> >> maxDate = "2013-03-21" >> >> dobs = dict([(d, []) for d in set([e['date'] for e in obs])]) >> >> for o in obs: >> dobs[o['date']].append(o) >> >> dobs_subMax = dict([(k, [d for d in v if d['realtime_start'] <= maxDate]) >> for k, v in dobs.items()]) >> >> rts = lambda x: x['realtime_start'] >> >> mmax = [sorted(e, key=rts)[-1] for e in dobs_subMax.values() if e] >> >> mmax.sort(key = lambda x: x['date']) >> >> pprint.pprint(mmax) >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor > > > You can do it with groupby like so: > > > from itertools import groupby > from operator import itemgetter > > > maxDate = "2013-03-21" > mmax = list() > > obs.sort(key=itemgetter('date')) > > for k, group in groupby(obs, key=itemgetter('date')): > group = [dob for dob in group if dob['realtime_start'] <= maxDate] > if group: > group.sort(key=itemgetter('realtime_start')) > mmax.append(group[-1]) > > pprint.pprint(mmax) > > > Note that writing multiply-nested comprehensions like you did results in > very unreadable code. Do you find this code more readable? > > -m > > > -- > Lark's Tongue Guide to Python: http://lightbird.net/larks/ > > Many a man fails as an original thinker simply because his memory it too > good. Friedrich Nietzsche > > > > ------------------------------ > > Message: 2 > Date: Fri, 22 Mar 2013 13:05:38 +1100 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] Help with iterators > Message-ID: <514BBC72.8040802 at pearwood.info> > Content-Type: text/plain; charset=UTF-8; format=flowed > > On 22/03/13 11:39, Matthew Johnson wrote: >> Dear list, >> >> I have been trying to understand out how to use iterators and in >> particular groupby statements. I am, however, quite lost. > > groupby is a very specialist function which is not very intuitive to > use. Sometimes I think that groupby is an excellent solution in search > of a problem. > > >> I wish to subset the below list, selecting the observations that have >> an ID ('realtime_start') value that is greater than some date (i've >> used the variable name maxDate), and in the case that there is more >> than one such record, returning only the one that has the largest ID >> ('realtime_start'). > > > The code that you show does not so what you describe here. The most > obvious difference is that it doesn't return or display a single record, > but shows multiple records. > > In your case, it selects six records, four of which have a realtime_start > that occurs BEFORE the given maxDate. > > To solve the problem you describe here, of finding at most a single > record, the solution is much simpler than what you have done. Prepare a > list of observations, sorted by realtime_start. Take the latest such > observation. If the realtime_start is greater than the maxDate, you have > your answer. If not, there is no answer. > > The simplest solution is usually the best. The simpler your code, the fewer > bugs it will contain. > > > obs.sort(key=lambda rec: rec['realtime_start']) > rec = obs[-1] > if rec['realtime_start'] > maxDate: > print rec > else: > print "no record found" > > > which prints: > > {'date': '2013-01-01', 'realtime_start': '2013-03-21', 'realtime_end': '9999-12-31', 'value': '231.222'} > > > > > -- > Steven > > > ------------------------------ > > Message: 3 > Date: Fri, 22 Mar 2013 13:20:09 +1100 > From: Steven D'Aprano > To: tutor at python.org > Subject: Re: [Tutor] Help with iterators > Message-ID: <514BBFD9.3090801 at pearwood.info> > Content-Type: text/plain; charset=UTF-8; format=flowed > > On 22/03/13 12:39, Mitya Sirenef wrote: > >> You can do it with groupby like so: >> >> >> from itertools import groupby >> from operator import itemgetter >> >> maxDate = "2013-03-21" >> mmax = list() >> >> obs.sort(key=itemgetter('date')) >> >> for k, group in groupby(obs, key=itemgetter('date')): >> group = [dob for dob in group if dob['realtime_start'] <= maxDate] >> if group: >> group.sort(key=itemgetter('realtime_start')) >> mmax.append(group[-1]) >> >> pprint.pprint(mmax) > > > This suffers from the same problem of finding six records instead of one, > and that four of the six have start dates before the given date instead > of after it. > > Here's another solution that finds all the records that start on or after > the given data (the poorly named "maxDate") and displays them sorted by > date. > > > selected = [rec for rec in obs if rec['realtime_start'] >= maxDate] > selected.sort(key=lambda rec: rec['date']) > print selected > > > > > -- > Steven > > > ------------------------------ > > Message: 4 > Date: Thu, 21 Mar 2013 22:31:53 -0400 > From: Mitya Sirenef > To: tutor at python.org > Subject: Re: [Tutor] Help with iterators > Message-ID: <514BC299.1070600 at lightbird.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > On 03/21/2013 10:20 PM, Steven D'Aprano wrote: >> On 22/03/13 12:39, Mitya Sirenef wrote: >> >>> You can do it with groupby like so: >>> >>> >>> from itertools import groupby >>> from operator import itemgetter >>> >>> maxDate = "2013-03-21" >>> mmax = list() >>> >>> obs.sort(key=itemgetter('date')) >>> >>> for k, group in groupby(obs, key=itemgetter('date')): >>> group = [dob for dob in group if dob['realtime_start'] <= maxDate] >>> if group: >>> group.sort(key=itemgetter('realtime_start')) >>> mmax.append(group[-1]) >>> >>> pprint.pprint(mmax) >> >> >> This suffers from the same problem of finding six records instead of one, >> and that four of the six have start dates before the given date instead >> of after it. > > > OP said his code produces the needed result and I think his description > probably doesn't match what he really intends to do (he also said he > wants the same code rewritten using groupby). I reproduced the logic of > his code... hopefully he can step in and clarify! > > > >> >> Here's another solution that finds all the records that start on or after >> the given data (the poorly named "maxDate") and displays them sorted by >> date. >> >> >> selected = [rec for rec in obs if rec['realtime_start'] >= maxDate] >> selected.sort(key=lambda rec: rec['date']) >> print selected > > > -- > Lark's Tongue Guide to Python: http://lightbird.net/larks/ > > A little bad taste is like a nice dash of paprika. > Dorothy Parker > > > > ------------------------------ > > Message: 5 > Date: Fri, 22 Mar 2013 12:54:01 +0530 > From: Arijit Ukil > To: tutor at python.org > Subject: [Tutor] Please Help > Message-ID: > > Content-Type: text/plain; charset="us-ascii" > > Hi, > > I have another small problem. Pls help. > > I have written the following code: > > f = open ("digi_2.txt", "r+") > lines = f.readlines() > for line in lines: > number_list = [] > for number in line.split(','): > number_list.append(float(number)) > > s_data = [] > for i in range(len(number_list)): > if number_list[i] > 5: > s_data = number_list[i] > > print 'Data val:', s_data > > > The problem is: it is printing only the last value, not all the values. In > this case '10', not '9,8,6,10'. > > > > Regards, > Arijit Ukil > Tata Consultancy Services > Mailto: arijit.ukil at tcs.com > Website: http://www.tcs.com > ____________________________________________ > Experience certainty. IT Services > Business Solutions > Outsourcing > ____________________________________________ > > > > From: > Amit Saha > To: > Arijit Ukil > Cc: > tutor at python.org > Date: > 03/21/2013 05:30 PM > Subject: > Re: [Tutor] Please Help > > > > Hi Arijit, > > On Thu, Mar 21, 2013 at 8:42 PM, Arijit Ukil wrote: >> >> I am new to python. I like to calculate average of the numbers by > reading >> the file 'digi_2.txt'. I have written the following code: >> >> def average(s): return sum(s) * 1.0 / len(s) >> >> f = open ("digi_2.txt", "r+") >> >> list_of_lists1 = f.readlines() >> >> >> for index in range(len(list_of_lists1)): >> >> >> tt = list_of_lists1[index] >> >> print 'Current value :', tt >> >> avg =average (tt) >> >> >> This gives an error: >> >> def average(s): return sum(s) * 1.0 / len(s) >> TypeError: unsupported operand type(s) for +: 'int' and 'str' >> >> I also attach the file i am reading. >> >> >> >> Please help to rectify. > > The main issue here is that when you are reading from a file, to > Python, its all strings. And although, 'abc' + 'def' is valid, 'abc' + > 5 isn't (for example). Hence, besides the fact that your average > calculation is not right, you will have to 'convert' the string to an > integer/float to do any arithmetic operation on them. (If you know C, > this is similar to typecasting). So, coming back to your program, I > will first demonstrate you a few things and then you can write the > program yourself. > > If you were to break down this program into simple steps, they would be: > > 1. Read the lines from a file (Assume a generic case, where you have > more than one line in the file, and you have to calculate the average > for each such row) > 2. Create a list of floating point numbers for each of those lines > 3. And call your average function on each of these lists > > You could of course do 2 & 3 together, so you create the list and call > the average function. > > So, here is step 1: > > with open('digi.txt','r') as f: > lines = f.readlines() > > Please refer to > http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects > for an explanation of the advantage of using 'with'. > > Now, you have *all* the lines of the file in 'lines'. Now, you want to > perform step 2 for each line in this file. Here you go: > > for line in lines: > number_list = [] > for number in line.split(','): > number_list.append(float(number)) > > (To learn more about Python lists, see > http://effbot.org/zone/python-list.htm). It is certainly possible to > use the index of an element to access elements from a list, but this > is more Pythonic way of doing it. To understand this better, in the > variable 'line', you will have a list of numbers on a single line. For > example: 1350696461, 448.0, 538660.0, 1350696466, 448.0. Note how they > are separated by a ',' ? To get each element, we use the split( ) > function, which returns a list of the individual numbers. (See: > http://docs.python.org/2/library/stdtypes.html#str.split). And then, > we use the .append() method to create the list. Now, you have a > number_list which is a list of floating point numbers for each line. > > Now, step 2 & 3 combined: > > for line in lines: > number_list = [] > for number in line.split(','): > number_list.append(float(number)) > print average(number_list) > > Where average( ) is defined as: > > def average(num_list): > return sum(num_list)/len(num_list) > > > > There may be a number of unknown things I may have talked about, but i > hope the links will help you learn more and write your program now. > > Good Luck. > -Amit. > > > -- > http://amitsaha.github.com/ > > > =====-----=====-----===== > Notice: The information contained in this e-mail > message and/or attachments to it may contain > confidential or privileged information. If you are > not the intended recipient, any dissemination, use, > review, distribution, printing or copying of the > information contained in this e-mail message > and/or attachments to it are strictly prohibited. If > you have received this communication in error, > please notify us by reply e-mail or telephone and > immediately and permanently delete the message > and any attachments. Thank you > > > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: > -------------- next part -------------- > An embedded and charset-unspecified text was scrubbed... > Name: digi_2.txt > URL: > > ------------------------------ > > Subject: Digest Footer > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > ------------------------------ > > End of Tutor Digest, Vol 109, Issue 75 > ************************************** From ghasemmg01 at leedslearning.net Fri Mar 29 12:33:20 2013 From: ghasemmg01 at leedslearning.net (Ghadir Ghasemi) Date: Fri, 29 Mar 2013 11:33:20 +0000 Subject: [Tutor] How to check if user input is an integer Message-ID: <010FB2F3C55002408EE1404538D1B6AE035D895CD107@LLN-SPP-ES-04.user01.lln.local> Hi guys I am trying to create part of a vending machine. The section below is if the user wants to insert 50p coins. It works but when I entered a non integer like 'dfsdf', the program just broke. Is there a way that the program can check if the input is an integer, and if it is, then the program does all the calculations, but if it isn't the program just keeps asking for an input? Thanks. Here is the section. fiftypencecoins = int(input("how many 50p coins do you want to insert or press 'e' to exit : ")) if fiftypencecoins == 'e': break else: currentmoney += fiftypencecoins * 5/10 print("your newly updated credit is ?" + str(currentmoney) + "0") From amitsaha.in at gmail.com Fri Mar 29 12:35:27 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Fri, 29 Mar 2013 21:35:27 +1000 Subject: [Tutor] How to check if user input is an integer In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE035D895CD107@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE035D895CD107@LLN-SPP-ES-04.user01.lln.local> Message-ID: On Fri, Mar 29, 2013 at 9:33 PM, Ghadir Ghasemi wrote: > Hi guys I am trying to create part of a vending machine. The section below is if the user wants to insert 50p coins. It works but when I entered a non integer like 'dfsdf', the program just broke. Is there a way that the program can check if the input is an integer, and if it is, then the program does all the calculations, but if it isn't the program just keeps asking for an input? Thanks. Here is the section. > > fiftypencecoins = int(input("how many 50p coins do you want to insert or press 'e' to exit : ")) > if fiftypencecoins == 'e': > break > else: > currentmoney += fiftypencecoins * 5/10 > print("your newly updated credit is ?" + str(currentmoney) + "0") Is this Python 3 or Python 2 ? -Amit. -- http://amitsaha.github.com/ From amitsaha.in at gmail.com Fri Mar 29 12:43:25 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Fri, 29 Mar 2013 21:43:25 +1000 Subject: [Tutor] How to check if user input is an integer In-Reply-To: References: <010FB2F3C55002408EE1404538D1B6AE035D895CD107@LLN-SPP-ES-04.user01.lln.local> Message-ID: On Fri, Mar 29, 2013 at 9:39 PM, Amit Saha wrote: > On Fri, Mar 29, 2013 at 9:35 PM, Amit Saha wrote: >> On Fri, Mar 29, 2013 at 9:33 PM, Ghadir Ghasemi >> wrote: >>> Hi guys I am trying to create part of a vending machine. The section below is if the user wants to insert 50p coins. It works but when I entered a non integer like 'dfsdf', the program just broke. Is there a way that the program can check if the input is an integer, and if it is, then the program does all the calculations, but if it isn't the program just keeps asking for an input? Thanks. Here is the section. >>> >>> fiftypencecoins = int(input("how many 50p coins do you want to insert or press 'e' to exit : ")) >>> if fiftypencecoins == 'e': >>> break >>> else: >>> currentmoney += fiftypencecoins * 5/10 >>> print("your newly updated credit is ?" + str(currentmoney) + "0") >> >> Is this Python 3 or Python 2 ? > > May be that's not relevant. So anyway, if you want to see whether the > int() function will be successful on your input, you need to check > whether the input constitutes of only digits. > > I can think of two ways: > > 1. Easy and naive way: for each character in the input, check whether > it is between [0-1] Oh lord. That should be [0-9]. Sorry. -- http://amitsaha.github.com/ From amitsaha.in at gmail.com Fri Mar 29 12:39:36 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Fri, 29 Mar 2013 21:39:36 +1000 Subject: [Tutor] How to check if user input is an integer In-Reply-To: References: <010FB2F3C55002408EE1404538D1B6AE035D895CD107@LLN-SPP-ES-04.user01.lln.local> Message-ID: On Fri, Mar 29, 2013 at 9:35 PM, Amit Saha wrote: > On Fri, Mar 29, 2013 at 9:33 PM, Ghadir Ghasemi > wrote: >> Hi guys I am trying to create part of a vending machine. The section below is if the user wants to insert 50p coins. It works but when I entered a non integer like 'dfsdf', the program just broke. Is there a way that the program can check if the input is an integer, and if it is, then the program does all the calculations, but if it isn't the program just keeps asking for an input? Thanks. Here is the section. >> >> fiftypencecoins = int(input("how many 50p coins do you want to insert or press 'e' to exit : ")) >> if fiftypencecoins == 'e': >> break >> else: >> currentmoney += fiftypencecoins * 5/10 >> print("your newly updated credit is ?" + str(currentmoney) + "0") > > Is this Python 3 or Python 2 ? May be that's not relevant. So anyway, if you want to see whether the int() function will be successful on your input, you need to check whether the input constitutes of only digits. I can think of two ways: 1. Easy and naive way: for each character in the input, check whether it is between [0-1] 2. Use regular expressions: http://docs.python.org/2/library/re.html -Amit. -- http://amitsaha.github.com/ From alan.gauld at btinternet.com Fri Mar 29 13:34:20 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 29 Mar 2013 12:34:20 +0000 Subject: [Tutor] How to check if user input is an integer In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE035D895CD107@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE035D895CD107@LLN-SPP-ES-04.user01.lln.local> Message-ID: On 29/03/13 11:33, Ghadir Ghasemi wrote: > Hi guys I am trying to create part of a vending machine. > when I entered a non integer like 'dfsdf', the program just broke. > Is there a way that the program can check if the input is an integer, Yes you can use try/except to catch the failure. > if it isn't the program just keeps asking for an input? and a while loop will keep you circulating. You may not have come across these in your tutorial/course yet > fiftypencecoins = int(input("how many 50p coins do you want to insert or press 'e' to exit : ")) > if fiftypencecoins == 'e': > break But this check needs to be before you convert to int() otherwise the 'e' will always raise an error when you try to convert it! > else: > currentmoney += fiftypencecoins * 5/10 > print("your newly updated credit is ?" + str(currentmoney) + "0") So in pseudo code you should have while True: read input if exit condition break try: convert to int except ValueError: continue process the value HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sydney.shall at kcl.ac.uk Fri Mar 29 13:21:38 2013 From: sydney.shall at kcl.ac.uk (Shall, Sydney) Date: Fri, 29 Mar 2013 12:21:38 +0000 Subject: [Tutor] How to check if user input is an integer In-Reply-To: References: <010FB2F3C55002408EE1404538D1B6AE035D895CD107@LLN-SPP-ES-04.user01.lln.local> Message-ID: <51558752.3010700@kcl.ac.uk> On 29/03/2013 11:39, Amit Saha wrote: > On Fri, Mar 29, 2013 at 9:35 PM, Amit Saha wrote: >> On Fri, Mar 29, 2013 at 9:33 PM, Ghadir Ghasemi >> wrote: >>> Hi guys I am trying to create part of a vending machine. The section below is if the user wants to insert 50p coins. It works but when I entered a non integer like 'dfsdf', the program just broke. Is there a way that the program can check if the input is an integer, and if it is, then the program does all the calculations, but if it isn't the program just keeps asking for an input? Thanks. Here is the section. >>> >>> fiftypencecoins = int(input("how many 50p coins do you want to insert or press 'e' to exit : ")) >>> if fiftypencecoins == 'e': >>> break >>> else: >>> currentmoney += fiftypencecoins * 5/10 >>> print("your newly updated credit is ?" + str(currentmoney) + "0") >> Is this Python 3 or Python 2 ? > May be that's not relevant. So anyway, if you want to see whether the > int() function will be successful on your input, you need to check > whether the input constitutes of only digits. > > I can think of two ways: > > 1. Easy and naive way: for each character in the input, check whether > it is between [0-1] > 2. Use regular expressions: http://docs.python.org/2/library/re.html > > -Amit. > > or; where x is the input == fiftypencecoins; return isinstance(x, int) will return True or False Then you can proceed as you wish. -- Professor Sydney Shall, Department of Haematological Medicine, King's College London, Medical School, 123 Coldharbour Lane, LONDON SE5 9NU, Tel & Fax: +44 (0)207 848 5902, E-Mail: sydney.shall, [correspondents outside the College should add; @kcl.ac.uk] www.kcl.ac.uk -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Fri Mar 29 14:13:37 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 29 Mar 2013 13:13:37 +0000 Subject: [Tutor] How to check if user input is an integer In-Reply-To: <51558752.3010700@kcl.ac.uk> References: <010FB2F3C55002408EE1404538D1B6AE035D895CD107@LLN-SPP-ES-04.user01.lln.local> <51558752.3010700@kcl.ac.uk> Message-ID: On 29/03/2013 12:21, Shall, Sydney wrote: > or; > where x is the input == fiftypencecoins; > > return isinstance(x, int) > > will return True or False > > Then you can proceed as you wish. If you enter invalid input you'll never get x to be an int so how can you test it with isinstance? -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From breamoreboy at yahoo.co.uk Fri Mar 29 14:15:28 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 29 Mar 2013 13:15:28 +0000 Subject: [Tutor] How to check if user input is an integer In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE035D895CD107@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE035D895CD107@LLN-SPP-ES-04.user01.lln.local> Message-ID: On 29/03/2013 11:33, Ghadir Ghasemi wrote: > Hi guys I am trying to create part of a vending machine. The section below is if the user wants to insert 50p coins. It works but when I entered a non integer like 'dfsdf', the program just broke. Is there a way that the program can check if the input is an integer, and if it is, then the program does all the calculations, but if it isn't the program just keeps asking for an input? Thanks. Here is the section. > > fiftypencecoins = int(input("how many 50p coins do you want to insert or press 'e' to exit : ")) > if fiftypencecoins == 'e': > break > else: > currentmoney += fiftypencecoins * 5/10 > print("your newly updated credit is ?" + str(currentmoney) + "0") > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Alan Gauld has already pointed you in the right direction. But in future can you please give us the entire traceback or state exactly what the problem is. "the program just broke" usually doesn't tell us much, although in this case it's easy enough to work out. Also state your OS and Python version. TIA. -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From msirenef at lightbird.net Fri Mar 29 14:46:52 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Fri, 29 Mar 2013 09:46:52 -0400 Subject: [Tutor] How to check if user input is an integer In-Reply-To: <010FB2F3C55002408EE1404538D1B6AE035D895CD107@LLN-SPP-ES-04.user01.lln.local> References: <010FB2F3C55002408EE1404538D1B6AE035D895CD107@LLN-SPP-ES-04.user01.lln.local> Message-ID: <51559B4C.6040100@lightbird.net> On 03/29/2013 07:33 AM, Ghadir Ghasemi wrote: > Hi guys I am trying to create part of a vending machine. The section below is if the user wants to insert 50p coins. It works but when I entered a non integer like 'dfsdf', the program just broke. Is there a way that the program can check if the input is an integer, and if it is, then the program does all the calculations, but if it isn't the program just keeps asking for an input? Thanks. Here is the section. > > fiftypencecoins = int(input("how many 50p coins do you want to insert or press 'e' to exit : ")) > if fiftypencecoins == 'e': > break > else: > currentmoney += fiftypencecoins * 5/10 > print("your newly updated credit is ?" + str(currentmoney) + "0") > _______________________________________________ > I've recently made a couple of functions that do this in a more general way. There are some usage examples at the end, including y/n input. The difference between them is that the 2nd function adds more options. import re def simpleinp(pattern, prompt="> ", convert=None, errmsg="Invalid Input", blank=False): """Keep asking user for input until it matches `pattern`.""" if pattern == "%d": pattern = "\d+"; convert = int if pattern == "%s": pattern = ".+" while True: i = input(prompt).strip() if blank and not i: return None if re.match('^'+pattern+'$', i): return convert(i) if convert and i else i else: print(errmsg) def getinp(pattern, prompt="> ", convert=None, errmsg="Invalid Input", ignorecase=False, lower=False, blank=True): """Keep asking user for input until it matches `pattern`.""" if pattern == "%d": pattern = "\d+" convert = int if pattern == "%f": pattern = "\d+.?\d*" convert = float if pattern == "%s": pattern = "\S+" while True: i = input(prompt).strip() if blank and not i: return None if lower: i = i.lower() flags = re.I if ignorecase else 0 if re.match('^'+pattern+'$', i, flags=flags): return convert(i) if convert else i else: print(errmsg) # print( getinp("%d", "integer: ") ) # print( getinp("%f", "float: ") ) # print( getinp("%s", "string: ") ) # print( getinp("(y|n)", "y/n: ", lower=True) ) # print( simpleinp("%d", "integer: ") ) # print( simpleinp("%s", "string: ") ) # print( simpleinp(".*", "string or blank: ") ) # print( simpleinp("[ynYN]", "y/n: ") ) HTH, -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ Blessed are the forgetful: for they get the better even of their blunders. Friedrich Nietzsche From alan.gauld at btinternet.com Fri Mar 29 19:14:21 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 29 Mar 2013 18:14:21 +0000 Subject: [Tutor] How to check if user input is an integer In-Reply-To: References: <010FB2F3C55002408EE1404538D1B6AE035D895CD107@LLN-SPP-ES-04.user01.lln.local> Message-ID: On 29/03/13 12:34, Alan Gauld wrote: A slight tweak to the solution; you probably need: > So in pseudo code you should have while True: read input if exit condition break try: convert to int break except ValueError: continue process the value HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From clydew at clydew.org Sat Mar 30 01:00:56 2013 From: clydew at clydew.org (Clyde Wilson) Date: Fri, 29 Mar 2013 17:00:56 -0700 (PDT) Subject: [Tutor] tkinter and messagebox Message-ID: <1364601656.13405.YahooMailClassic@web184306.mail.ne1.yahoo.com> The following code works fine under IDLE but errors when run as a standalone: ? from tkinter import * root=Tk() main=Frame(root) main.grid() def doit(): ??? messagebox.showinfo("Hello") btn1=Button(main,width=10,text="In") btn1.grid() lbl1=Label(main) lbl1.grid() btn2=Button(main,width=10,text="Out",command=doit) btn2.grid() lbl2=Label(main) lbl2.grid() root.mainloop() ? Exception in Tkinter callback Traceback (most recent call last): ? File "C:\Python33\lib\tkinter\__init__.py", line 1442, in __call__ ??? return self.func(*args) ? File "C:\Users\Wilson\Documents\Old Documents\My Stuff\Python Pgms\temp.py", l ine 6, in doit ??? messagebox.showinfo("Hello") NameError: global name 'messagebox' is not defined ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Sat Mar 30 01:17:51 2013 From: eryksun at gmail.com (eryksun) Date: Fri, 29 Mar 2013 20:17:51 -0400 Subject: [Tutor] tkinter and messagebox In-Reply-To: <1364601656.13405.YahooMailClassic@web184306.mail.ne1.yahoo.com> References: <1364601656.13405.YahooMailClassic@web184306.mail.ne1.yahoo.com> Message-ID: On Fri, Mar 29, 2013 at 8:00 PM, Clyde Wilson wrote: > > from tkinter import * > root=Tk() > main=Frame(root) > main.grid() > def doit(): > messagebox.showinfo("Hello") You have to import the module first: from tkinter import messagebox http://hg.python.org/cpython/file/bd8afb90ebf2/Lib/tkinter From clydew at clydew.org Sun Mar 31 00:16:54 2013 From: clydew at clydew.org (Clyde Wilson) Date: Sat, 30 Mar 2013 16:16:54 -0700 (PDT) Subject: [Tutor] Tkinter Documentation Message-ID: <1364685414.21661.YahooMailClassic@web184301.mail.ne1.yahoo.com> Is there a fairly complete set of documentation on-line?for Tkinter? I'm using Python 3.3 on Windows. ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sun Mar 31 00:25:56 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 30 Mar 2013 23:25:56 +0000 Subject: [Tutor] Tkinter Documentation In-Reply-To: <1364685414.21661.YahooMailClassic@web184301.mail.ne1.yahoo.com> References: <1364685414.21661.YahooMailClassic@web184301.mail.ne1.yahoo.com> Message-ID: On 30/03/2013 23:16, Clyde Wilson wrote: > Is there a fairly complete set of documentation on-line for Tkinter? > I'm using Python 3.3 on Windows. http://docs.python.org/3/library/tkinter.html -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From alan.gauld at btinternet.com Sun Mar 31 01:44:10 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 31 Mar 2013 00:44:10 +0000 Subject: [Tutor] Tkinter Documentation In-Reply-To: References: <1364685414.21661.YahooMailClassic@web184301.mail.ne1.yahoo.com> Message-ID: On 30/03/13 23:25, Mark Lawrence wrote: > On 30/03/2013 23:16, Clyde Wilson wrote: >> Is there a fairly complete set of documentation on-line for Tkinter? >> I'm using Python 3.3 on Windows. > > http://docs.python.org/3/library/tkinter.html This contains links to most of the resources you need but its important to remember when dealing with Tkinter that it is tracking the underlying Tk widget set. There are a lot of undocumented or poorly documented features and options in that set and it changes on a fairly regular basis with new releases. For example the original Ousterhout book is now so far out of date it is really only useful for understanding the basic philosophy and structure of Tcl/Tk. There are several good Tk reference sites but you have to translate Tcl/Tk into Python to use them. Some sites give multi-lingual examples, for example: http://www.tkdocs.com/ Which is incomplete but slowly growing and has examples in Tcl and Ruby. (The tutorial section has Perl and Python too...) This is the official Tk site (all tcl based) http://www.tcl.tk/man/tcl8.5/TkCmd/contents.htm And of course don't forget Tix which is also part of the Tkinter library support in Python now. http://tix.sourceforge.net/man/html/TixCmd/TixIntro.htm#M11 -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ysoliman at uncc.edu Sun Mar 31 03:49:44 2013 From: ysoliman at uncc.edu (Soliman, Yasmin) Date: Sun, 31 Mar 2013 01:49:44 +0000 Subject: [Tutor] (no subject) Message-ID: <211A029E048A2245A6E00BA02FEFF88A581E3662@BL2PRD0310MB373.namprd03.prod.outlook.com> Hello everyone. How can I get a program to stop only when the user enters 'Quit'? From amitsaha.in at gmail.com Sun Mar 31 03:52:02 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Sun, 31 Mar 2013 11:52:02 +1000 Subject: [Tutor] (no subject) In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A581E3662@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A581E3662@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: On Sun, Mar 31, 2013 at 11:49 AM, Soliman, Yasmin wrote: > Hello everyone. How can I get a program to stop only when the user enters 'Quit'? You would need an "infinite" loop in your program, where you take user input. Check if the input entered was 'Quit', and only exit/break out of your loop then, else continue doing something else. HTH, -Amit. -- http://amitsaha.github.com/ From steve at pearwood.info Sun Mar 31 04:02:57 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 31 Mar 2013 13:02:57 +1100 Subject: [Tutor] (no subject) In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A581E3662@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A581E3662@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: <51579951.1080801@pearwood.info> On 31/03/13 12:49, Soliman, Yasmin wrote: > Hello everyone. How can I get a program to stop only when the user enters 'Quit'? First you need a program that never stops. Most programs automatically stop when they're done, so you need to have a program which repeats forever. Do you have that? Then you need to add code that asks the user for input. Then you need to add code that compares that input to "Quit". And finally you need to add code that exits when they match. # Step 1. A program that never stops. while True: print "Hello world" # Or do something useful. # Step 2. Add code that repeatedly gets input from the user. while True: print "Hello world" response = raw_input("What do you want to do? ") # Step 3. Inspect that input. while True: print "Hello world" response = raw_input("What do you want to do? ") if response == "Quit": print "Exiting now" # Well, not now, but soon. # Step 4. Exit when done. while True: print "Hello world" response = raw_input("What do you want to do? ") if response == "Quit": break # escapes from the while loop Step 5. Make the program useful. That's up to you. -- Steven From amitsaha.in at gmail.com Sun Mar 31 04:33:22 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Sun, 31 Mar 2013 12:33:22 +1000 Subject: [Tutor] Fwd: (no subject) In-Reply-To: References: <211A029E048A2245A6E00BA02FEFF88A581E3662@BL2PRD0310MB373.namprd03.prod.outlook.com> <211A029E048A2245A6E00BA02FEFF88A581E3676@BL2PRD0310MB373.namprd03.prod.outlook.com> <211A029E048A2245A6E00BA02FEFF88A581E3693@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: Sorry, forgot to have tutor in the CC. On Sun, Mar 31, 2013 at 12:08 PM, Soliman, Yasmin wrote: > Sure here it is: > > import weekday_string1 > while True: > ryear = raw_input("year= ") > print ryear > if not ryear.isdigit(): > print '\nThank you for using this program! Bye.' > break if ryear == 'Quit': print '\nThank you for using this program! Bye.' break This will exit out of the While loop. So, if you have code after the while loop, they will be executed. If you want to completely exit the program, use the sys.exit() function from the sys module. Does that help? -Amit. -- http://amitsaha.github.com/ From amitsaha.in at gmail.com Sun Mar 31 05:00:13 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Sun, 31 Mar 2013 13:00:13 +1000 Subject: [Tutor] FW: Fwd: (no subject) In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A581E36C3@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A581E3662@BL2PRD0310MB373.namprd03.prod.outlook.com> <211A029E048A2245A6E00BA02FEFF88A581E3676@BL2PRD0310MB373.namprd03.prod.outlook.com> <211A029E048A2245A6E00BA02FEFF88A581E3693@BL2PRD0310MB373.namprd03.prod.outlook.com> <211A029E048A2245A6E00BA02FEFF88A581E36AF@BL2PRD0310MB373.namprd03.prod.outlook.com> <211A029E048A2245A6E00BA02FEFF88A581E36C3@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: On Sun, Mar 31, 2013 at 12:51 PM, Soliman, Yasmin wrote: > yes, your program does work. The problem is if I run that similar statment in my program, say I enter the year and for month I write Quit, it says quit is not defined. I suppose in this senerio I would have to use the sys.exit()? Do you mean that you want to quit if *any* of your inputs is given as 'Quit' ? The something like this should work: import weekday_string1 while True: ryear = raw_input("year= ") print ryear if ryear=='Quit': print '\nThank you for using this program! Bye.' break else: year = int(ryear) month = raw_input("month= ") day = raw_input("day= ") if month=='Quit' or day == 'Quit': break wd = weekday_string1.weekday_string(year, int(month), int(day)) print "The given date: %2d/%2d/%4d is a %s." % (month, day, year, wd) print "======================================" Couple of things here: 1. I have used raw_input() to take the input for month and day as well (Why? See the differences between input() and raw_input(): http://echorand.me/2012/10/11/input-and-raw_input-in-python/) 2. Since raw_input() returns its input as a string, I use the int() function when I call your weekday_string() function with month and date. Does that help? -Amit. -- http://amitsaha.github.com/ From amitsaha.in at gmail.com Sun Mar 31 04:43:04 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Sun, 31 Mar 2013 12:43:04 +1000 Subject: [Tutor] FW: Fwd: (no subject) In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A581E36AF@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A581E3662@BL2PRD0310MB373.namprd03.prod.outlook.com> <211A029E048A2245A6E00BA02FEFF88A581E3676@BL2PRD0310MB373.namprd03.prod.outlook.com> <211A029E048A2245A6E00BA02FEFF88A581E3693@BL2PRD0310MB373.namprd03.prod.outlook.com> <211A029E048A2245A6E00BA02FEFF88A581E36AF@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: On Sun, Mar 31, 2013 at 12:39 PM, Soliman, Yasmin wrote: > So if it should look like this, it gives error that says Quit is not defined, also why does it not recognize the sys import when I run it? > > import weekday_string1 > import sys > while True: > ryear = raw_input("year= ") > print ryear > > if ryear == 'Quit': > print '\nThank you for using this program! Bye.' > break Okay, here is a small program: while True: ryear = raw_input("year= ") print ryear if ryear == 'Quit': print '\nThank you for using this program! Bye.' break else: print 'Not quitting' When I run this, I see: year= 10 10 Not quitting year= 10 10 Not quitting year= 20 20 Not quitting year= Quit Quit Thank you for using this program! Bye. As you can see, when I enter "Quit", it exists. Can you try and see if that works for you? Best, Amit. -- http://amitsaha.github.com/ From amitsaha.in at gmail.com Sun Mar 31 05:15:30 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Sun, 31 Mar 2013 13:15:30 +1000 Subject: [Tutor] FW: Fwd: (no subject) In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A581E36D6@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A581E3662@BL2PRD0310MB373.namprd03.prod.outlook.com> <211A029E048A2245A6E00BA02FEFF88A581E3676@BL2PRD0310MB373.namprd03.prod.outlook.com> <211A029E048A2245A6E00BA02FEFF88A581E3693@BL2PRD0310MB373.namprd03.prod.outlook.com> <211A029E048A2245A6E00BA02FEFF88A581E36AF@BL2PRD0310MB373.namprd03.prod.outlook.com> <211A029E048A2245A6E00BA02FEFF88A581E36C3@BL2PRD0310MB373.namprd03.prod.outlook.com> <211A029E048A2245A6E00BA02FEFF88A581E36D6@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: On Sun, Mar 31, 2013 at 1:14 PM, Soliman, Yasmin wrote: > Yes this does help. I'm going to play around with it a bit, thank you so much for your patience and time! Great. Good Luck! From phil_lor at bigpond.com Sun Mar 31 06:29:58 2013 From: phil_lor at bigpond.com (Phil) Date: Sun, 31 Mar 2013 14:29:58 +1000 Subject: [Tutor] pyqt4 set horizontal header item Message-ID: <5157BBC6.20408@bigpond.com> Thank you for reading this. I want to set a table widget header based on its cell contents. The following sets all of the headers; self.tableWidget.setHorizontalHeaderLabels(["One", "Two", "Etc"]) However, self.setHorizontalHeaderItem ( 1, ["test"]) and self.setHorizontalHeaderItem ( 1, "test") fail with the following error; "'MainWindow' object has no attribute 'setHorizontalHeaderItem'" setHorizontalHeaderItem() exists in the documentation so I must be using it incorrectly. I've played with this for quite some time and searched the Internet for an answer. Can anyone offer a suggestion? -- Regards, Phil From phil_lor at bigpond.com Sun Mar 31 09:30:20 2013 From: phil_lor at bigpond.com (Phil) Date: Sun, 31 Mar 2013 17:30:20 +1000 Subject: [Tutor] pyqt4 set horizontal header item - extra info In-Reply-To: <5157BBC6.20408@bigpond.com> References: <5157BBC6.20408@bigpond.com> Message-ID: <5157E60C.9000601@bigpond.com> On 31/03/13 14:29, Phil wrote: > Thank you for reading this. > > I want to set a table widget header based on its cell contents. > > The following sets all of the headers; > > self.tableWidget.setHorizontalHeaderLabels(["One", "Two", "Etc"]) > > However, self.setHorizontalHeaderItem ( 1, ["test"]) and > self.setHorizontalHeaderItem ( 1, "test") fail with the following error; > > "'MainWindow' object has no attribute 'setHorizontalHeaderItem'" > > setHorizontalHeaderItem() exists in the documentation so I must be using > it incorrectly. I've played with this for quite some time and searched > the Internet for an answer. Can anyone offer a suggestion? > I now realise the correct syntax is; self.tableWidget.setHorizontalHeaderItem (1, QTableWidgetItem *item) I have done this many years ago in C++ but I don't quite see how to get a QTableWidgetItem in Python. -- Regards, Phil From alan.gauld at btinternet.com Sun Mar 31 10:23:56 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 31 Mar 2013 09:23:56 +0100 Subject: [Tutor] pyqt4 set horizontal header item - extra info In-Reply-To: <5157E60C.9000601@bigpond.com> References: <5157BBC6.20408@bigpond.com> <5157E60C.9000601@bigpond.com> Message-ID: On 31/03/13 08:30, Phil wrote: > self.tableWidget.setHorizontalHeaderItem (1, QTableWidgetItem *item) > > I have done this many years ago in C++ but I don't quite see how to get > a QTableWidgetItem in Python. Presumably by instantiating a TableWidgetItem class? But you will likely get better help on Qt topics by asking on a Qt specific forum rather than a Python beginners list like this. There are a few Qt users here but most are not. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From eryksun at gmail.com Sun Mar 31 13:43:24 2013 From: eryksun at gmail.com (eryksun) Date: Sun, 31 Mar 2013 07:43:24 -0400 Subject: [Tutor] pyqt4 set horizontal header item - extra info In-Reply-To: References: <5157BBC6.20408@bigpond.com> <5157E60C.9000601@bigpond.com> Message-ID: On Sun, Mar 31, 2013 at 4:23 AM, Alan Gauld wrote: > On 31/03/13 08:30, Phil wrote: > >> self.tableWidget.setHorizontalHeaderItem (1, QTableWidgetItem *item) >> >> I have done this many years ago in C++ but I don't quite see how to get >> a QTableWidgetItem in Python. > > Presumably by instantiating a TableWidgetItem class? > But you will likely get better help on Qt topics by asking on a Qt specific > forum rather than a Python beginners list like this. > There are a few Qt users here but most are not. You can use setHorizontalHeaderItem(0, QTableWidgetItem('col 0'), and so on. It may be simpler to use setHorizontalHeaderLabels(['col 0', 'col 1', 'etc']). From chandankumar.093047 at gmail.com Sun Mar 31 17:09:02 2013 From: chandankumar.093047 at gmail.com (chandan kumar) Date: Sun, 31 Mar 2013 20:39:02 +0530 Subject: [Tutor] Want to create a facebook Application for linux desktop Message-ID: Hello, I want to create a facebook application for Linux desktop. This application will download all the news feeds of all my friends to whom i am subscribed. It also helps to update status and upload photos. I donot know how to get started. I have searched google, but not found any relevant information for this. Please tell me to how to get started to execute this using python. Thanks, With Best Wishes, Chandan Kumar Final Year, Computer Science and Engineering Dr.B.C.Roy Engineering College, Durgapur https://ciypro.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From mannavak at gmail.com Sun Mar 31 18:30:52 2013 From: mannavak at gmail.com (Murali Mannava) Date: Sun, 31 Mar 2013 09:30:52 -0700 Subject: [Tutor] Traceback problem Message-ID: Hi, I am trying to execute a program and it's giving the following problem and preventing me to go further. Can you please tell me what the problem is? Thank you, Murali. Traceback (most recent call last): File "pwp_client.py", line 58, in RESULTS = client.run_project(models[action] , areq ) File "C:\Users\mmannava\downloads\\network\clents\socket_tcp.py", line 127, in run_project return ast.literal_eval(res) File "C:\Python27\lib\ast.py", line 49, in literal_eval node_or_string = parse(node_or_string, mode='eval') File "C:\Python27\lib\ast.py", line 37, in parse return compile(source, filename, mode, PyCF_ONLY_AST) File "", line 0 ^ SyntaxError: unexpected EOF while parsing -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sun Mar 31 18:39:46 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 31 Mar 2013 17:39:46 +0100 Subject: [Tutor] Traceback problem In-Reply-To: References: Message-ID: On 31/03/2013 17:30, Murali Mannava wrote: > Hi, > I am trying to execute a program and it's giving the following problem > and preventing me to go further. Can you please tell me what the problem is? > Thank you, > Murali. > > Traceback (most recent call last): > > File "pwp_client.py", line 58, in > > RESULTS = client.run_project(models[action] , areq ) > > File "C:\Users\mmannava\downloads\\network\clents\socket_tcp.py", > line 127, in run_project > > return ast.literal_eval(res) > > File "C:\Python27\lib\ast.py", line 49, in literal_eval > > node_or_string = parse(node_or_string, mode='eval') > > File "C:\Python27\lib\ast.py", line 37, in parse > > return compile(source, filename, mode, PyCF_ONLY_AST) > > File "", line 0 > > ^ > > SyntaxError: unexpected EOF while parsing > Can't be definitive without seeing your source but this error often occurs when you've missed a closing bracket of some kind. A combination of any semi-decent editor that's got syntax highlighting and the MKI eyeball can often fix this :) -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From alan.gauld at btinternet.com Sun Mar 31 18:44:57 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 31 Mar 2013 17:44:57 +0100 Subject: [Tutor] Want to create a facebook Application for linux desktop In-Reply-To: References: Message-ID: On 31/03/13 16:09, chandan kumar wrote: > I have searched google, but not found any relevant information for this. > Please tell me to how to get started to execute this using python. What is your background? Can you already program in Python? Can you program in other languages? Given your .sig I assume the answer is yes to both? What did you Google? I don't know if Facebook has a published API? If not you will have to web scrape it in which case you need libraries like Beautiful Soup, or maybe etree. You'll also need to read up on the urllib and HTML family. Have you any idea how to structure the program? Have you got an overall architecture in mind? Will it be a daemon? A web server? A traditional client/server? Or will it be a homogenous desktop app? What about data stores? Will you cache data locally or assume permanent 'cloud' access? Do you have a data or object model in mind? Are you using OOP or procedural style? Hopefully those questions will help you formulate your ideas if you have not already done so. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Mar 31 18:48:45 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 31 Mar 2013 17:48:45 +0100 Subject: [Tutor] Traceback problem In-Reply-To: References: Message-ID: On 31/03/13 17:30, Murali Mannava wrote: > and preventing me to go further. Can you please tell me what the problem is? > File "C:\Python27\lib\ast.py", line 37, in parse > return compile(source, filename, mode, PyCF_ONLY_AST) > File "", line 0 > ^ > SyntaxError: unexpected EOF while parsing You apparently have a syntax error in the file that it is trying to parse. As a result the parser unexpectedly reached the end of the file. Does that help? If not, we will need a bit more information. Like what are you trying to do? And with what data? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From chandankumar.093047 at gmail.com Sun Mar 31 18:37:18 2013 From: chandankumar.093047 at gmail.com (chandan kumar) Date: Sun, 31 Mar 2013 22:07:18 +0530 Subject: [Tutor] create a facebook Application for linux desktop Message-ID: Hello, I want to create a facebook application for Linux desktop. This application will download all the news feeds of all my friends to whom i am subscribed. It also helps to update status and upload photos. I donot know how to get started. I have searched google, but not found any relevant information for this. Please tell me to how to get started to execute this using python. Thanks, With Best Wishes, Chandan Kumar Final Year, Computer Science and Engineering Dr.B.C.Roy Engineering College, Durgapur https://ciypro.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From delegbede at dudupay.com Sun Mar 31 17:31:22 2013 From: delegbede at dudupay.com (Dipo Elegbede) Date: Sun, 31 Mar 2013 16:31:22 +0100 Subject: [Tutor] change of email Message-ID: Hi, I would like to have my email changed from delegbede at dudupay.com to dipo.elegbede at dipoelegbede.com I have not in a long time used this email and as such would like all correspondences sent to the new email so that I can resume my participation in the group. I sincerely hope this would be given a top priority while I'm quite aware of your very busy schedule. I appreciate your efforts and look forward to resuming participation as soon as my email address is changed. Thank you. -- Elegbede Muhammed Oladipupo OCA +2348077682428 +2347042171716 www.dudupay.com Mobile Banking Solutions | Transaction Processing | Enterprise Application Development -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwpolska at gmail.com Sun Mar 31 19:34:26 2013 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Sun, 31 Mar 2013 19:34:26 +0200 Subject: [Tutor] change of email In-Reply-To: References: Message-ID: On Sun, Mar 31, 2013 at 5:31 PM, Dipo Elegbede wrote: > > Hi, > > I would like to have my email changed from delegbede at dudupay.com to dipo.elegbede at dipoelegbede.com > [snip bullshit] > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Unsubscribe and resubscribe at http://mail.python.org/mailman/listinfo/tutor ? just as the signature below your mail claims! BTW, did you perchance produce your mail address through having a cat sit on your keyboard? -- Kwpolska | GPG KEY: 5EAAEA16 stop html mail | always bottom-post http://asciiribbon.org | http://caliburn.nl/topposting.html From joel.goldstick at gmail.com Sun Mar 31 20:04:51 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 31 Mar 2013 14:04:51 -0400 Subject: [Tutor] create a facebook Application for linux desktop In-Reply-To: References: Message-ID: On Sun, Mar 31, 2013 at 12:37 PM, chandan kumar < chandankumar.093047 at gmail.com> wrote: > Hello, > I want to create a facebook application for Linux desktop. > This application will download all the news feeds of all my friends to > whom i am subscribed. > It also helps to update status and upload photos. > I donot know how to get started. > I have searched google, but not found any relevant information for this. > Please tell me to how to get started to execute this using python. > > Maybe start here: http://developers.facebook.com/ > Thanks, > > With Best Wishes, > > Chandan Kumar > Final Year, Computer Science and Engineering > Dr.B.C.Roy Engineering College, Durgapur > https://ciypro.wordpress.com > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sun Mar 31 20:35:33 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 31 Mar 2013 19:35:33 +0100 Subject: [Tutor] create a facebook Application for linux desktop In-Reply-To: References: Message-ID: On 31/03/2013 17:37, chandan kumar wrote: > Hello, > I want to create a facebook application for Linux desktop. > This application will download all the news feeds of all my friends to > whom i am subscribed. > It also helps to update status and upload photos. > I donot know how to get started. > I have searched google, but not found any relevant information for this. > Please tell me to how to get started to execute this using python. > > Thanks, > > With Best Wishes, > > Chandan Kumar > Final Year, Computer Science and Engineering > Dr.B.C.Roy Engineering College, Durgapur > https://ciypro.wordpress.com > Did you really have to post this one hour and 28 minutes after your first post with a slightly different title? -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From joel.goldstick at gmail.com Sun Mar 31 19:42:16 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 31 Mar 2013 13:42:16 -0400 Subject: [Tutor] change of email In-Reply-To: References: Message-ID: On Sun, Mar 31, 2013 at 11:31 AM, Dipo Elegbede wrote: > Hi, > > I would like to have my email changed from delegbede at dudupay.com to > dipo.elegbede at dipoelegbede.com > > I have not in a long time used this email and as such would like all > correspondences sent to the new email so that I can resume my participation > in the group. > > I sincerely hope this would be given a top priority while I'm quite aware > of your very busy schedule. > > I appreciate your efforts and look forward to resuming participation as > soon as my email address is changed. > > Thank you. > > You need to do this yourself. See the address below to subscribe and unsubscribe > -- > 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 > > -- Joel Goldstick http://joelgoldstick.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From arijit.ukil at tcs.com Wed Mar 20 07:14:06 2013 From: arijit.ukil at tcs.com (Arijit Ukil) Date: Wed, 20 Mar 2013 06:14:06 -0000 Subject: [Tutor] Help required Message-ID: I am new to python. My intention is to read the file digi.txt and store in separate arrays all the values of each columns. However, the following program prints only the last value, i.e. 1350696500.0. Please help to rectify this. f = open ("digi.txt", "r+") datafile = f.readlines() list_of_lists = datafile for data in list_of_lists: lstval = data.split (',') timest = float(lstval[0]) energy = float(lstval[1]) f.close() print timest Regards, Arijit Ukil Tata Consultancy Services Mailto: arijit.ukil at tcs.com Website: http://www.tcs.com ____________________________________________ Experience certainty. IT Services Business Solutions Outsourcing ____________________________________________ =====-----=====-----===== Notice: The information contained in this e-mail message and/or attachments to it may contain confidential or privileged information. If you are not the intended recipient, any dissemination, use, review, distribution, printing or copying of the information contained in this e-mail message and/or attachments to it are strictly prohibited. If you have received this communication in error, please notify us by reply e-mail or telephone and immediately and permanently delete the message and any attachments. Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From clarktt at miamioh.edu Tue Mar 19 04:14:14 2013 From: clarktt at miamioh.edu (Clark, Tristan) Date: Tue, 19 Mar 2013 03:14:14 -0000 Subject: [Tutor] File Import Message-ID: Hi, I am importing data produced from an external code. The data is organized into columns. I would like to be able to assign each column to a variable or array. How would you recommend doing this? I have been looking into the pickle function, as well as "f.readline" and "for line in f:" and I got all of those ideas from the Python Tutorial. I am a little new to python. Thank you, Tristan Clark -------------- next part -------------- An HTML attachment was scrubbed... URL: From marocko_87 at hotmail.com Wed Mar 27 13:30:59 2013 From: marocko_87 at hotmail.com (Yasin El Guennouni) Date: Wed, 27 Mar 2013 13:30:59 +0100 Subject: [Tutor] The game of nim in python Message-ID: Hello, I am trying to modify a game of nim code. The game in the code works as: "You need to remove from 1 to 3 straws from the pile. The player that removes the final straw is the loser." But I would like it to be like the classic game, where you have 4 piles containing 1,3,5 and 7 sticks where the drawer of the last stick is the winner. It would be awsome if I could print how many sticks there are left in each pile, e.g. : I III IIIII IIIIIII. Thanks in advance! The code I have: player1=str(input("Enter your name. ")) player2="Computer" howMany=0 gameover=False strawsNumber=random.randint(10,20) if (strawsNumber%4)==1: strawsNumber+=1 def removingStrawsComputer(): removedNumber=random.randint(1,3) global strawsNumber while removedNumber>strawsNumber: removedNumber=random.randint(1,3) strawsNumber-=removedNumber return strawsNumber def removingStrawsHuman(): global strawsNumber strawsNumber-=howMany return strawsNumber def humanLegalMove(): global howMany legalMove=False while not legalMove: print("It's your turn, ",player1) howMany=int(input("How many straws do you want to remove?(from 1 to 3) ")) if howMany>3 or howMany<1: print("Enter a number between 1 and 3.") else: legalMove=True while howMany>strawsNumber: print("The entered number is greater than a number of straws remained.") howMany=int(input("How many straws do you want to remove?")) return howMany def checkWinner(player): if strawsNumber==0: print(player," wins.") global gameover gameover=True return gameover def resetGameover(): global gameover gameover=False return gameover def game(): while gameover==False: print("It's ",player2,"turn. The number of straws left: ",removingStrawsComputer()) checkWinner(player1) if gameover==True: break humanLegalMove() print("The number of straws left: ",removingStrawsHuman()) checkWinner(player2) game() -------------- next part -------------- An HTML attachment was scrubbed... URL: From mcooganj at gmail.com Thu Mar 21 02:14:28 2013 From: mcooganj at gmail.com (Matthew Johnson) Date: Thu, 21 Mar 2013 09:14:28 +0800 Subject: [Tutor] Tutor Digest, Vol 109, Issue 71 In-Reply-To: References: Message-ID: <-1797977811238906169@unknownmsgid> I recently asked a question on SO: http://stackoverflow.com/questions/15180767/subset-list-based-on-value-of-dictionary-element and got very confused when trying to generalise the answer. The problem is as follows: say i have this list, and would like to get the value at each date that has the largest value for realtime_start (date) value. obs = [{'date': '2012-10-01', 'realtime_end': '2013-02-18', 'realtime_start': '2012-11-15', 'value': '231.751'}, {'date': '2012-10-01', 'realtime_end': '9999-12-31', 'realtime_start': '2012-12-19', 'value': '231.623'}, {'date': '2012-11-01', 'realtime_end': '2013-02-18', 'realtime_start': '2012-12-14', 'value': '231.025'}, {'date': '2012-11-01', 'realtime_end': '9999-12-31', 'realtime_start': '2013-01-19', 'value': '231.071'}, {'date': '2012-12-01', 'realtime_end': '2013-02-18', 'realtime_start': '2013-01-16', 'value': '230.979'}, {'date': '2012-12-01', 'realtime_end': '9999-12-31', 'realtime_start': '2013-02-19', 'value': '231.137'}, {'date': '2012-12-01', 'realtime_end': '9999-12-31', 'realtime_start': '2013-03-19', 'value': '231.197'}, {'date': '2013-01-01', 'realtime_end': '9999-12-31', 'realtime_start': '2013-02-21', 'value': '231.198'}, {'date': '2013-01-01', 'realtime_end': '9999-12-31', 'realtime_start': '2013-03-21', 'value': '231.222'}] maxDate = "2013-02-21" The answer suggested itertools, and it worked for the exact maxDate that's above. However, when i move the date (say to "2013-01-21") it throws the error: ValueError: max() arg is an empty sequence. I can see from the list that there are elements that have realtime_start values that are lower than 2013-01-21 so this is a bug. I have read the documents for itertools, but cannot quite work out this groupby stuff. there's a snip of the SO solution below -- help understanding as well as the bug fix would be much appreciated. thanks in advance, Matt Johnson ______ ## subset on maxDate grouped2 = itertools.groupby(obs, lambda x: x['date']) m2 = [max((w for w in g if w['realtime_start'] <= maxDate), key=lambda x: x['realtime_start']) for k, g in grouped2] pprint.pprint(m2) On 21/03/2013, at 8:30 AM, "tutor-request at python.org" < tutor-request at python.org> 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: Help (Dave Angel) 2. Re: Help (xDog Walker) 3. Re: Help (Robert Sjoblom) 4. Re: Scripting Calligra sheets with Python (Jim Byrnes) 5. Re: Help (Alan Gauld) ---------------------------------------------------------------------- Message: 1 Date: Wed, 20 Mar 2013 16:53:19 -0400 From: Dave Angel To: tutor at python.org Subject: Re: [Tutor] Help Message-ID: <514A21BF.9030303 at davea.name> Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 03/20/2013 03:57 PM, travis jeanfrancois wrote: Hello, I am a beginning python student and I am having trouble with a program I am writing . The problem requires me to use "while" and that I create a function that allows the user to a create sentence by inputing a string and to end the sentence with a period meaning inputing "." .The problem is while keeps overwriting the previuos input and it still asks for a string even after it prints out . Here is the output I am getting Enter the first word in your sentence: I Enter the next word in your sentence: am Enter the next word in your sentence: a Enter the next word in your sentence: novice Enter the next word in your sentence: . I . . Enter the next word in your sentence: Here is the desired output: : Enter the first word in your sentence: I Enter the next word in your sentence: am Enter the next word in your sentence: a Enter the next word in your sentence: novice Enter the next word in your sentence: . I am a novice. Here is my code: def B1(): #Creates a function called B1 period = "." # The variable period is assigned first = input("Enter the first word in your sentence ") #The variable first is assigned next1 = input("Enter the next word in you sentence or enter period:") #The variable next 1 is assigned # I need store the value so when while overwrites next1 with the next input the previous input is stored and will print output when I call it later along with last one # I believe the solution is some how implenting this expression x = x+ variable You need a new variable that accumulates the whole sentence. I'd use a list, but many people would use a string. Since I don't know what concepts you know yet, I'll stick to string here. Anyway, you have to initialize it before the loop, and then you can print it after the loop. sentence = "" while next1 != (period) : next1 = input("Enter the next word in you sentence or enter period:") At this point, add the word to the sentence. if next1 == (period): next1 = next1 + period print ("Your sentence is:",first,next1,period) No need for these three lines inside the loop, since the loop will end when next1 is equal to the period. So put the print after the end of the loop, and I'll let you figure out what it should print. PS : The" #" is I just type so I can understand what each line does -- DaveA ------------------------------ Message: 2 Date: Wed, 20 Mar 2013 14:47:39 -0700 From: xDog Walker To: tutor at python.org Subject: Re: [Tutor] Help Message-ID: <201303201447.39643.thudfoo at gmail.com> Content-Type: text/plain; charset="iso-8859-1" On Wednesday 2013 March 20 13:39, Robert Sjoblom wrote: A word of advice: next is a keyword in python ~/Packages/Python/Notable-0.1.5b> python Python 2.5 (r25:51908, May 25 2007, 16:14:04) [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. import keyword keyword.iskeyword('next') False 14:44 Wed 2013 Mar 20 ~/Packages/Python/Notable-0.1.5b> python2.7 Python 2.7.2 (default, Oct 10 2011, 10:47:36) [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. import keyword keyword.iskeyword('next') False 14:44 Wed 2013 Mar 20 ~/Packages/Python/Notable-0.1.5b> python3.3 Python 3.3.0 (default, Sep 30 2012, 09:02:56) [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux Type "help", "copyright", "credits" or "license" for more information. import keyword keyword.iskeyword('next') False -- Yonder nor sorghum stenches shut ladle gulls stopper torque wet strainers. ------------------------------ Message: 3 Date: Wed, 20 Mar 2013 22:59:04 +0100 From: Robert Sjoblom To: xDog Walker Cc: Tutor - python List Subject: Re: [Tutor] Help Message-ID: Content-Type: text/plain; charset="iso-8859-1" On Mar 20, 2013 10:49 p.m., "xDog Walker" wrote: On Wednesday 2013 March 20 13:39, Robert Sjoblom wrote: A word of advice: next is a keyword in python ~/Packages/Python/Notable-0.1.5b> python Python 2.5 (r25:51908, May 25 2007, 16:14:04) [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. import keyword keyword.iskeyword('next') False 14:44 Wed 2013 Mar 20 ~/Packages/Python/Notable-0.1.5b> python2.7 Python 2.7.2 (default, Oct 10 2011, 10:47:36) [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. import keyword keyword.iskeyword('next') False 14:44 Wed 2013 Mar 20 ~/Packages/Python/Notable-0.1.5b> python3.3 Python 3.3.0 (default, Sep 30 2012, 09:02:56) [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux Type "help", "copyright", "credits" or "license" for more information. import keyword keyword.iskeyword('next') False -- Yonder nor sorghum stenches shut ladle gulls stopper torque wet strainers. Fine, it's a method, my bad. -------------- next part -------------- An HTML attachment was scrubbed... URL: < http://mail.python.org/pipermail/tutor/attachments/20130320/b646443c/attachment-0001.html > ------------------------------ Message: 4 Date: Wed, 20 Mar 2013 19:26:54 -0500 From: Jim Byrnes To: tutor at python.org Subject: Re: [Tutor] Scripting Calligra sheets with Python Message-ID: Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 03/19/2013 09:16 PM, Jim Byrnes wrote: On 03/18/2013 11:25 PM, Dave Angel wrote: On 03/18/2013 09:56 PM, Jim Byrnes wrote: On 03/18/2013 07:54 PM, Dave Angel wrote: On 03/18/2013 12:18 PM, Jim Byrnes wrote: I am trying to script Calligra Sheets (formerly KSpread) with python. I have gotten some of the included example scripts to run so I know python scripting is running. I found the following snippet on their website: import KSpread sheet = KSpread.view().sheet() # swap text of B5 and C6 t1 = sheet.text("B5") t2 = sheet.text(6,3) sheet.setText("B5", t2) sheet.setText(6, 3, t1) # swap value of D7 and E8 v1 = sheet.value("D7") v2 = sheet.value(8,5) sheet.setValue("D7", v2) sheet.setValue(8, 5, v1) Error: 'str' object has no attribute 'text' File "file:///usr/share/kde4/apps/sheets/scripts/extensions/myswap.py", line 4, in This error message appeared in a dialog box. I've taught myself some Python but I don't understand what is happening here. Shouldn't t1 be a sheet object? What would cause it to be a str instead? Since somebody has censored the rest of the error traceback, we can't even tell what line is giving the error. Assuming you know it's t1 = sheet.text("85") I think line wrapping obscured that it is line 4 t1 = sheet.text("B5"). I saw the line 4, but didn't see anyplace where it showed me line 4. So i had to guess. And for all I knew, the error isn't happening on that line, but on some line called indirectly by that one. The full stack trace would be reassuring. But apparently your Calligra environment is censoring it. then it has nothing to do with the type of t1, but with the type of sheet. If that's the case, then print out type(sheet) and see what it actually is. Then consult the documentation for the KSpread.view().sheet() function and see what it's documented to return. The docs say: Returns the KSpread::ViewAdaptor object in which the document is displayed. I would like to follow your advice and print out type(sheet) but right now I don't know how. This is all running inside Calligra sheets and so far the only thing I have gotten out if it is the error message. Are you permitted to edit this myswap.py file? If so, add a line that prints the useful information immediately before the line which causes the exception. And if print is also swallowed by your helpful environment, then write to a file. Yes I can and it does swallow it, so I redirected to a file and it says . Same as the error message. So now I need to figure out why it's not returning the object expected. I can run the sample scripts that were installed but not something I originate. I guess I must be missing something procedural that is keeping them from running properly. Thanks for you help. Regards, Jim Just a follow up for completeness in case some else finds this and has the same problem. Replace line 2 sheet = KSpread.view().sheet() with sheetname = KSpread.currentSheet().sheetName() sheet = KSpread.sheetByName(sheetname) Then it will run with no errors. Regards, Jim ------------------------------ Message: 5 Date: Thu, 21 Mar 2013 00:26:56 +0000 From: Alan Gauld To: tutor at python.org Subject: Re: [Tutor] Help Message-ID: Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 20/03/13 19:57, travis jeanfrancois wrote: I create a function that allows the user to a create sentence by inputing a string and to end the sentence with a period meaning inputing "." .The problem is while keeps overwriting the previuos input 'While' does not do any such thing. Your code is doing that all by itself. What while does is repeat your code until a condition becomes false or you explicitly break out of the loop. Here is my code: def B1(): Try to give your functions names that describe what they do. B1() is meaningless, readSentence() would be better. period = "." # The variable period is assigned Its normal programming practice to put the comment above the code not after it. Also comments should indicate why you are doing something not what you are doing - we can see that from the code. first = input("Enter the first word in your sentence ") next1 = input("Enter the next word in you sentence or enter period:") # I need store the value so when while overwrites next1 with the next input the previous input is stored and will print output when I call it later along with last one # I believe the solution is some how implenting this expression x = x+ variable You could be right. Addition works for strings as well as numbers. Although there are other (better) options but you may not have covered them in your class yet. while next1 != (period) : You don;t need the parentheses around period. Also nextWord might be a better name than next1. Saving 3 characters of typing is not usually worthwhile. next1 = input("Enter the next word in you sentence or enter period:") Right, here you are overwriting next1. It's not the while's fault - it is just repeating your code. It is you who are overwriting the variable. Notice that you are not using the first that you captured? Maybe you should add next1 to first at some point? Then you can safely overwrite next1 as much as you like? if next1 == (period): Again you don;t need the parentheses around period next1 = next1 + period Here, you add the period to next1 which the 'if' has already established is now a period. print ("Your sentence is:",first,next1,period) And now you print out the first word plus next1 (= 2 periods) plus a period = 3 periods in total... preceded by the phrase "Your sentence is:" This tells us that the sample output you posted is not from this program... Always match the program and the output when debugging or you will be led seriously astray! PS : The" #" is I just type so I can understand what each line does The # is a comment marker. Comments are a very powerful tool that programmers use to explain to themselves and other programmers why they have done what they have. When trying to debug faults like this it is often worthwhile grabbing a pen and drawing a chart of your variables and their values after each time round the loop. In this case it would have looked like iteration period first next1 0 . I am 1 . I a 2 . I novice 3 . I .. If you aren't sure of the values insert a print statement and get the program to tell you, but working it out in your head is more likely to show you the error. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ ------------------------------ Subject: Digest Footer _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ------------------------------ End of Tutor Digest, Vol 109, Issue 71 ************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From michelle_low at zoho.com Sun Mar 24 07:50:05 2013 From: michelle_low at zoho.com (michelle_low) Date: Sat, 23 Mar 2013 23:50:05 -0700 Subject: [Tutor] Phyton script for fasta file (seek help) Message-ID: <13d9b2944c8.-4757810490957638786.6251647252550083523@zoho.com> Hi everyone, Can someone please help me with the following phyton script? I received the error message DeprecationWarning: the sets module is deprecated from sets import Set. After googling, I have tried the methods others suggest: change sets to set or delete the from sets import Set but none of them works. Can someone suggest me how to modify the following codes so that the input file is read from standard input? I'd like to execute them with unix command script.py < sequence.fna Thanks a bunch. #!/usr/local/bin/python import math from sets import Set line = file("sequence.fna", "r") for x in line: if x [0] == ">" : #determine the length of sequences s=line.next() s=s.rstrip() length = len(s) # determine the GC content G = s.count('G') C = s.count('C') GC= 100 * (float(G + C) / length) stList = list(s) alphabet = list(Set(stList)) freqList = [] for symbol in alphabet: ctr = 0 for sym in stList: if sym == symbol: ctr += 1 freqList.append(float(ctr)/len(stList)) # Shannon entropy ent = 0.0 for freq in freqList: ent = ent + freq * math.log(freq, 2) ent = -ent print x print "Length:" , length print "G+C:" ,round(GC),"%" print 'Shannon entropy:' print ent print 'Minimum number of bits required to encode each symbol:' print int(math.ceil(ent)) -------------- next part -------------- An HTML attachment was scrubbed... URL: