From phil_lor at bigpond.com Mon Apr 1 02:01:47 2013 From: phil_lor at bigpond.com (Phil) Date: Mon, 01 Apr 2013 10:01:47 +1000 Subject: [Tutor] pyqt4 set horizontal header item - extra info In-Reply-To: References: <5157BBC6.20408@bigpond.com> <5157E60C.9000601@bigpond.com> Message-ID: <5158CE6B.2090502@bigpond.com> On 31/03/13 21:43, eryksun wrote: > > You can use setHorizontalHeaderItem(0, QTableWidgetItem('col 0'), and > so on. It may be simpler to use setHorizontalHeaderLabels(['col 0', > 'col 1', 'etc']). > Thanks Eryksun, I had already tried your suggestion last night and this is the result; "global name 'QTableWidgetItem' is not defined" You are correct, I can easily set all of the labels at once but only one label needs to be modified according to it's cell contents. I'm sure I'm missing something very basic. -- Regards, Phil From arwh at yahoo.com Mon Apr 1 03:18:52 2013 From: arwh at yahoo.com (ah) Date: Sun, 31 Mar 2013 18:18:52 -0700 (PDT) Subject: [Tutor] is there a simple stand alone python app I can use on my Kindle fire? Message-ID: <1364779132.91062.YahooMailNeo@web162401.mail.bf1.yahoo.com> Hello, I'm enjoying learning python, and would like to be able to study and practice on the go, using my kindle fire reader. (wifi enabled). Amazon does have an app, Qpython lite, but requires a? live wifi connection to the internet to run. I'm looking for a simple python app, stand alone that i can run on my kindle, without an internet connection,? just to practice while i learn. (Just a simple terminal, and text editor, and python? like ubuntu offers.) I've tried downloading portable python, and couldnt' get it to run ('can't run in DOS mode?'), I've tried downloading ubuntu to my kindle and couldn't, and tried downloading the whole 2.7 python app, but couldn't get it to run. I tried to root my kindle, but as I'm inexperienced in things tech, i'm not sure if I was successful, and not sure how this helps (if I was successful.) I have both windows 7 and ubuntu (dual boot) on my laptop, and can connect my kindle to the laptop via usb cable. I have "accept downloads from other applications" enabled on my kindle. On my kindle I have 'better terminal emulator pro' , ES file explorer, and droidedit. Any help is appreciated, I'm willing to follow step by step instructions to get python running on my kindle. I will supply any other details required. My kindle fire specs are : Model D01400 The Kindle Fire features a 7? display module from LG Display. The display is dual-sourced between LG Display and E Ink Holdings. The display touchscreen appears to be conventional capacitive glass on glass and the control IC on the touchscreen is from a previously unseen source. Meanwhile, the OMAP4430 applications processor from Texas Instruments is a dual-core RM Cortex-A9, 1GHz processor with IVA 3 Hardware Accelerator, SGX540 3D Graphic Core, 1080P 2D, 720P 3D and is produced in 45nm process geometry. Other key features include a 8GB eMMC NAND Flash Memory, 4Gbits of low power DDR2, a 3.7V battery with 4400mAh capacity (or about 16 Wh), and a module from Jorjin, which is based on Texas Instruments? WL1270. -------------- next part -------------- An HTML attachment was scrubbed... URL: From phil_lor at bigpond.com Mon Apr 1 02:13:00 2013 From: phil_lor at bigpond.com (Phil) Date: Mon, 01 Apr 2013 10:13:00 +1000 Subject: [Tutor] pyqt4 set horizontal header item - solved In-Reply-To: References: <5157BBC6.20408@bigpond.com> <5157E60C.9000601@bigpond.com> Message-ID: <5158D10C.8080706@bigpond.com> On 31/03/13 21:43, eryksun wrote: > You can use setHorizontalHeaderItem(0, QTableWidgetItem('col 0'), and > so on. It may be simpler to use setHorizontalHeaderLabels(['col 0', > 'col 1', 'etc']). > I have the answer (provided by a member of another list) and I was correct, it was something basic. from PyQt4 import QtGui QtGui.QTable etc As I previously said, I had done this under C++ many years ago. The Python method is far simpler, especially once you know how. -- Regards, Phil From steve at pearwood.info Mon Apr 1 06:33:20 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 01 Apr 2013 15:33:20 +1100 Subject: [Tutor] is there a simple stand alone python app I can use on my Kindle fire? In-Reply-To: <1364779132.91062.YahooMailNeo@web162401.mail.bf1.yahoo.com> References: <1364779132.91062.YahooMailNeo@web162401.mail.bf1.yahoo.com> Message-ID: <51590E10.2030202@pearwood.info> On 01/04/13 12:18, ah wrote: > Hello, > > > I'm enjoying learning python, and would like to be able to study and practice on the go, using my kindle fire reader. (wifi enabled). > > > Amazon does have an app, Qpython lite, but requires a live wifi connection to the internet to run. I'm looking for a simple python app, stand alone that i can run on my kindle, without an internet connection, just to practice while i learn. (Just a simple terminal, and text editor, and python? like ubuntu offers.) This is a list for learning Python, not the details of arbitrary locked-down proprietary platforms. You might be lucky and have a response from somebody who knows how to get Python working on a Kindle, but probably not. Your best bet is to ask on a Kindle forum, or failing that, try on the main Python mailing list: python-list at python.org also available on Usenet: comp.lang.python Because there are a lot more people on that list, you have a better chance of finding someone with a Kindle who knows how to get Python working on it. The first step should be to try goggling: https://www.google.com.au/search?q=running+python+on+kindle If you do get an answer on some other forum, please post the answer here so anyone searching the archives will find the answer. -- Steven From eryksun at gmail.com Mon Apr 1 11:47:36 2013 From: eryksun at gmail.com (eryksun) Date: Mon, 1 Apr 2013 05:47:36 -0400 Subject: [Tutor] pyqt4 set horizontal header item - solved In-Reply-To: <5158D10C.8080706@bigpond.com> References: <5157BBC6.20408@bigpond.com> <5157E60C.9000601@bigpond.com> <5158D10C.8080706@bigpond.com> Message-ID: On Sun, Mar 31, 2013 at 8:13 PM, Phil wrote: > > I have the answer (provided by a member of another list) and I was correct, > it was something basic. > > from PyQt4 import QtGui > QtGui.QTable etc Sorry, I assumed you were familiar with the package layout. http://pyqt.sourceforge.net/Docs/PyQt4/qtablewidgetitem.html Notice the subtitle that says "[QtGui module]". http://pyqt.sourceforge.net/Docs/PyQt4/classes.html http://pyqt.sourceforge.net/Docs/PyQt4/qtgui.html http://pyqt.sourceforge.net/Docs/PyQt4/qtcore.html http://pyqt.sourceforge.net/Docs/PyQt4/qt.html From phil_lor at bigpond.com Mon Apr 1 11:59:23 2013 From: phil_lor at bigpond.com (Phil) Date: Mon, 01 Apr 2013 19:59:23 +1000 Subject: [Tutor] pyqt4 set horizontal header item - solved In-Reply-To: References: <5157BBC6.20408@bigpond.com> <5157E60C.9000601@bigpond.com> <5158D10C.8080706@bigpond.com> Message-ID: <51595A7B.6010702@bigpond.com> On 01/04/13 19:47, eryksun wrote: > On Sun, Mar 31, 2013 at 8:13 PM, Phil wrote: >> >> I have the answer (provided by a member of another list) and I was correct, >> it was something basic. >> >> from PyQt4 import QtGui >> QtGui.QTable etc > > Sorry, I assumed you were familiar with the package layout. > > http://pyqt.sourceforge.net/Docs/PyQt4/qtablewidgetitem.html > > Notice the subtitle that says "[QtGui module]". > > http://pyqt.sourceforge.net/Docs/PyQt4/classes.html > http://pyqt.sourceforge.net/Docs/PyQt4/qtgui.html > http://pyqt.sourceforge.net/Docs/PyQt4/qtcore.html > http://pyqt.sourceforge.net/Docs/PyQt4/qt.html Thanks for the links Eryksun, it's all now starting to make sense. -- Regards, Phil From fomcl at yahoo.com Mon Apr 1 22:04:21 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 1 Apr 2013 13:04:21 -0700 (PDT) Subject: [Tutor] tadaahh! But how to identify zLinux? Message-ID: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com> tadaah, I uploaded my first package some time ago: http://pypi.python.org/pypi/savReaderWriter Let me use this opportunity to say THANKS to all of you for all your advise! I'm still stuck with a question though. The program is supposed to work with zLinux (IBM system Z). But how do I know that this system is used? Here's my attempt: # https://pic.dhe.ibm.com/infocenter/tivihelp/v10r1/index.jsp?topic=%2Fcom.ibm.tsam.doc_7.1%2Fc_prep_ms_for_lx_sysz.html import sys, platform if sys.platform.startswith("lin"): ?? #isSuSe = platform.linux_distribution() == "SuSe" ?? sysname, nodename, release, version, machine = os.uname() ?? isSLES = "suse linux enterprise server" in version.lower() ?? isRelease2dot6 = release.startswith("2.6") ?? isSystemZ = machine.startswith("s390")? # ???? ?? isZLinux = isSLES and isRelease2dot6 and isSystemZ ?? if isZLinux: ????? pass Regards, Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ?~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? From eryksun at gmail.com Mon Apr 1 22:43:56 2013 From: eryksun at gmail.com (eryksun) Date: Mon, 1 Apr 2013 16:43:56 -0400 Subject: [Tutor] tadaahh! But how to identify zLinux? In-Reply-To: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com> References: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: On Mon, Apr 1, 2013 at 4:04 PM, Albert-Jan Roskam wrote: > > I'm still stuck with a question though. The program is supposed to work > with zLinux (IBM system Z). But how do I know that this system is used? Have a look at the platform module for info on the Python version/implementation, machine, and OS (e.g. linux_distribution): http://docs.python.org/2.6/library/platform From alan.gauld at btinternet.com Tue Apr 2 00:00:07 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 01 Apr 2013 23:00:07 +0100 Subject: [Tutor] tadaahh! But how to identify zLinux? In-Reply-To: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com> References: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: On 01/04/13 21:04, Albert-Jan Roskam wrote: > program is supposed to work with zLinux (IBM system Z). But how do I > know that this system is used? I have no idea what the answer is but I'm curious why you would care? Are you expecting that your code will be run on an IBM mainframe? I'd have thought that in most cases those boxes would only be running Python in situations where the admins have carefully controlled the code that's loaded - and by implication taken care of whatever you are trying to do - or, they would be running virtual machines that look like non-mainframes? Now, I have no experience of either zLinux or of using Python on a mainframe so I don't know if my guesses are accurate, but I am curious why you are concerned? Is it a known issue or are you just being super careful? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Tue Apr 2 00:42:54 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 02 Apr 2013 09:42:54 +1100 Subject: [Tutor] tadaahh! But how to identify zLinux? In-Reply-To: References: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com> Message-ID: <515A0D6E.5080609@pearwood.info> On 02/04/13 09:00, Alan Gauld wrote: > On 01/04/13 21:04, Albert-Jan Roskam wrote: > >> program is supposed to work with zLinux (IBM system Z). But how do I >> know that this system is used? > > I have no idea what the answer is but I'm curious why you would care? > Are you expecting that your code will be run on an IBM mainframe? Perhaps he is :-) Albert-Jan asks because his package is an interface to an external binary library, and the location of that library differs according to the platform: https://bitbucket.org/fomcl/savreaderwriter/src/09b9c82406e82d43223d6610ba9cbfbf234b16d4/savReaderWriter/generic.py?at=master By the way, I don't know that changing directory is a good idea, if you can avoid it at all. I for one would be *extremely* annoyed if, after calling what otherwise seems like an innocent library routine, opening files suddenly started failing (or worse, the wrong file was opened!) because the current directory was different. Even though you do restore the current directory when you are done, that makes your routines unsafe for threads. -- Steven From kendy at kendy.org Tue Apr 2 02:31:10 2013 From: kendy at kendy.org (kendy at kendy.org) Date: Mon, 01 Apr 2013 17:31:10 PDT Subject: [Tutor] argparse iterable Message-ID: <52285.1364862670@speakeasy.net> Dear Tutor I want to compare command line options, to options in a dictionary from a YAML file. The command line will over-ride the options in my file. (The YAML file, and its dictionary are not shown. That part works.) My distilled code: ------------------------------------------------------------------------- $ cat h.py #!/usr/bin/python import argparse parser = argparse.ArgumentParser(description='Short sample app') def GetArgs(parser): parser.add_argument('-a', action="store_true", default=False) parser.add_argument('-b', action="store", dest="b") parser.add_argument('-c', action="store", dest="c", type=int) return parser GetArgs(parser) print(parser.parse_args()) print("But this doesn't iter through a b and c:") for k,v in parser.parse_args(): print('This arg is %s %s' % k, k[str(v)]) $ ------------------------------------------------------------------------- My error: $ h.py -a -b hi -c 42 Namespace(a=True, b='hi', c=42) But this doesn't iter through a b and c: Traceback (most recent call last): File "./h.py", line 16, in for k,v in parser.parse_args(): TypeError: 'Namespace' object is not iterable $ How can I get parser to be iterable? After I get it to iter, I suppose that I'll be bitten by the boolean and integer type conversions. I'm not sure how to handle that either. Will 'str()' save me? Thanks a million (again!), Ken From jsf80238 at gmail.com Tue Apr 2 03:24:04 2013 From: jsf80238 at gmail.com (Jason Friedman) Date: Mon, 1 Apr 2013 19:24:04 -0600 Subject: [Tutor] argparse iterable In-Reply-To: <52285.1364862670@speakeasy.net> References: <52285.1364862670@speakeasy.net> Message-ID: #!/usr/bin/python import argparse parser = argparse.ArgumentParser(description='Short sample app') parser.add_argument('-a', action="store_true", default=False) parser.add_argument('-b', action="store", dest="b") parser.add_argument('-c', action="store", dest="c", type=int) parser.parse_args() for k,v in parser.parse_args().__dict__.items(): print('This arg is %s %s' % (k, v)) On Mon, Apr 1, 2013 at 6:31 PM, wrote: > Dear Tutor > > I want to compare command line options, to options in a dictionary from a > YAML > file. The command line will over-ride the options in my file. (The YAML > file, and > its dictionary are not shown. That part works.) > > My distilled code: > > ------------------------------------------------------------------------- > $ cat h.py > #!/usr/bin/python > > import argparse > parser = argparse.ArgumentParser(description='Short sample app') > > def GetArgs(parser): > parser.add_argument('-a', action="store_true", default=False) > parser.add_argument('-b', action="store", dest="b") > parser.add_argument('-c', action="store", dest="c", type=int) > return parser > > GetArgs(parser) > > print(parser.parse_args()) > print("But this doesn't iter through a b and c:") > for k,v in parser.parse_args(): > print('This arg is %s %s' % k, k[str(v)]) > $ > ------------------------------------------------------------------------- > > My error: > $ h.py -a -b hi -c 42 > Namespace(a=True, b='hi', c=42) > But this doesn't iter through a b and c: > Traceback (most recent call last): > File "./h.py", line 16, in > for k,v in parser.parse_args(): > TypeError: 'Namespace' object is not iterable > $ > > How can I get parser to be iterable? > > After I get it to iter, I suppose that I'll be bitten by the boolean and > integer > type conversions. I'm not sure how to handle that either. Will 'str()' > save me? > > Thanks a million (again!), > Ken > > _______________________________________________ > 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 Tue Apr 2 03:31:24 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 02 Apr 2013 02:31:24 +0100 Subject: [Tutor] argparse iterable In-Reply-To: <52285.1364862670@speakeasy.net> References: <52285.1364862670@speakeasy.net> Message-ID: On 02/04/2013 01:31, kendy at kendy.org wrote: > Dear Tutor > > I want to compare command line options, to options in a dictionary from a YAML > file. The command line will over-ride the options in my file. (The YAML file, and > its dictionary are not shown. That part works.) > > My distilled code: > > ------------------------------------------------------------------------- > $ cat h.py > #!/usr/bin/python > > import argparse > parser = argparse.ArgumentParser(description='Short sample app') > > def GetArgs(parser): > parser.add_argument('-a', action="store_true", default=False) > parser.add_argument('-b', action="store", dest="b") > parser.add_argument('-c', action="store", dest="c", type=int) > return parser > > GetArgs(parser) > > print(parser.parse_args()) > print("But this doesn't iter through a b and c:") > for k,v in parser.parse_args(): > print('This arg is %s %s' % k, k[str(v)]) for a in vars(parser.parse_args()): print('This arg is %s' % a) http://docs.python.org/3/library/argparse.html#the-namespace-object Please don't ask me for an explanation as it took me long enough to work this out from the docs :) > $ > ------------------------------------------------------------------------- > > My error: > $ h.py -a -b hi -c 42 > Namespace(a=True, b='hi', c=42) > But this doesn't iter through a b and c: > Traceback (most recent call last): > File "./h.py", line 16, in > for k,v in parser.parse_args(): > TypeError: 'Namespace' object is not iterable > $ > > How can I get parser to be iterable? > > After I get it to iter, I suppose that I'll be bitten by the boolean and integer > type conversions. I'm not sure how to handle that either. Will 'str()' save me? > > Thanks a million (again!), > Ken > > -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From davea at davea.name Tue Apr 2 03:37:16 2013 From: davea at davea.name (Dave Angel) Date: Mon, 01 Apr 2013 21:37:16 -0400 Subject: [Tutor] argparse iterable In-Reply-To: References: <52285.1364862670@speakeasy.net> Message-ID: <515A364C.4040604@davea.name> On 04/01/2013 09:31 PM, Mark Lawrence wrote: > On 02/04/2013 01:31, kendy at kendy.org wrote: >> Dear Tutor >> >> I want to compare command line options, to options in a dictionary >> from a YAML >> file. The command line will over-ride the options in my file. (The >> YAML file, and >> its dictionary are not shown. That part works.) >> >> My distilled code: >> >> ------------------------------------------------------------------------- >> $ cat h.py >> #!/usr/bin/python >> >> import argparse >> parser = argparse.ArgumentParser(description='Short sample app') >> >> def GetArgs(parser): >> parser.add_argument('-a', action="store_true", default=False) >> parser.add_argument('-b', action="store", dest="b") >> parser.add_argument('-c', action="store", dest="c", type=int) >> return parser >> >> GetArgs(parser) >> >> print(parser.parse_args()) >> print("But this doesn't iter through a b and c:") >> for k,v in parser.parse_args(): >> print('This arg is %s %s' % k, k[str(v)]) > > for a in vars(parser.parse_args()): > print('This arg is %s' % a) > > http://docs.python.org/3/library/argparse.html#the-namespace-object > > Please don't ask me for an explanation as it took me long enough to work > this out from the docs :) > http://docs.python.org/2/library/argparse.html see section 15.4.4.6 for a very brief explanation of vars() >> $ >> ------------------------------------------------------------------------- >> >> My error: >> $ h.py -a -b hi -c 42 >> Namespace(a=True, b='hi', c=42) >> But this doesn't iter through a b and c: >> Traceback (most recent call last): >> File "./h.py", line 16, in >> for k,v in parser.parse_args(): >> TypeError: 'Namespace' object is not iterable >> $ >> >> How can I get parser to be iterable? >> >> After I get it to iter, I suppose that I'll be bitten by the boolean >> and integer >> type conversions. I'm not sure how to handle that either. Will 'str()' >> save me? >> >> Thanks a million (again!), >> Ken >> >> > > -- DaveA From dfjennings at gmail.com Tue Apr 2 03:56:16 2013 From: dfjennings at gmail.com (Don Jennings) Date: Mon, 1 Apr 2013 21:56:16 -0400 Subject: [Tutor] argparse iterable In-Reply-To: <52285.1364862670@speakeasy.net> References: <52285.1364862670@speakeasy.net> Message-ID: On Apr 1, 2013, at 8:31 PM, wrote: > > > print("But this doesn't iter through a b and c:") > for k,v in parser.parse_args(): > print('This arg is %s %s' % k, k[str(v)]) > $ > ------------------------------------------------------------------------- > > My error: > $ h.py -a -b hi -c 42 > Namespace(a=True, b='hi', c=42) > But this doesn't iter through a b and c: > Traceback (most recent call last): > File "./h.py", line 16, in > for k,v in parser.parse_args(): > TypeError: 'Namespace' object is not iterable > $ > > How can I get parser to be iterable? Jason, Mark and Dave have addressed this part of your question already. > > After I get it to iter, I suppose that I'll be bitten by the boolean and integer > type conversions. I'm not sure how to handle that either. Will 'str()' save me? What do you mean here? You're thinking that you have to convert them to strings before passing them to the print function? Actually, the string formatting operator, the percent sign, combined with the 's' will convert for you, using the str() method. So, the code above is redundant. Just use: print('This arg is %s %s' % k, v) Take care, Don From kendy at kendy.org Tue Apr 2 04:28:53 2013 From: kendy at kendy.org (kendy at kendy.org) Date: Mon, 01 Apr 2013 19:28:53 PDT Subject: [Tutor] argparse iterable Message-ID: <35358.1364869733@speakeasy.net> You guys are awesome! You make it look easy and I learn every time. Thank you Ken From breamoreboy at yahoo.co.uk Tue Apr 2 04:34:26 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 02 Apr 2013 03:34:26 +0100 Subject: [Tutor] argparse iterable In-Reply-To: <515A364C.4040604@davea.name> References: <52285.1364862670@speakeasy.net> <515A364C.4040604@davea.name> Message-ID: On 02/04/2013 02:37, Dave Angel wrote: > On 04/01/2013 09:31 PM, Mark Lawrence wrote: >> >> for a in vars(parser.parse_args()): >> print('This arg is %s' % a) >> >> http://docs.python.org/3/library/argparse.html#the-namespace-object >> >> Please don't ask me for an explanation as it took me long enough to work >> this out from the docs :) >> > > http://docs.python.org/2/library/argparse.html > > see section 15.4.4.6 for a very brief explanation of vars() > > Section 15.4.4.6. The Namespace object, but I can't for the life of me remember what my link referred to :) -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From breamoreboy at yahoo.co.uk Tue Apr 2 04:37:04 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 02 Apr 2013 03:37:04 +0100 Subject: [Tutor] argparse iterable In-Reply-To: <35358.1364869733@speakeasy.net> References: <35358.1364869733@speakeasy.net> Message-ID: On 02/04/2013 03:28, kendy at kendy.org wrote: > You guys are awesome! You make it look easy and I learn every time. > > Thank you > Ken Think yourself lucky, I'm currently on the wagon or it'd cost you a couple of pints :) -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From eryksun at gmail.com Tue Apr 2 04:57:16 2013 From: eryksun at gmail.com (eryksun) Date: Mon, 1 Apr 2013 22:57:16 -0400 Subject: [Tutor] tadaahh! But how to identify zLinux? In-Reply-To: <515A0D6E.5080609@pearwood.info> References: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com> <515A0D6E.5080609@pearwood.info> Message-ID: On Mon, Apr 1, 2013 at 6:42 PM, Steven D'Aprano wrote: > By the way, I don't know that changing directory is a good idea, if you can > avoid it at all. As far as loading linked libraries goes, changing the current directory works on Windows, and I think OS X, but it doesn't work on Linux. On Windows you can also add the directory to the system PATH at run time. I see 3 deb files in spssio/lin32. It doesn't seem like your plan is to install these since you don't have them for lin64 as well. Is this savReaderWriter supposed to be a self-contained system for reading/writing IBM SPSS files, or dependent on an existing installation of SPSS? (Not being a user of SPSS, I have no idea how foolish that question may or may not sound. Oh well.) Anyway, I downloaded and extracted the deb files to a temp directory on a 32-bit Debian system. In addition to the libs that you've already extracted, ldd determined that I also needed the following libs: libimf.so [intel-icc8-libs_8.0-1_i386.deb] libcxaguard.so.5 [intel-icc8-libs_8.0-1_i386.deb libstdc++.so.5.0.7 [libstdc++5_3.3.6-20_i386.deb] and links for the ELF soname fields: libstdc++.so.5 -> libstdc++.so.5.0.7 libicudata.so.32 -> libicudata.so.32.0 libicui18n.so.32 -> libicui18n.so.32.0 libicuuc.so.32 -> libicuuc.so.32.0 After setting up the above, I patched a runpath of $ORIGIN into libspssdio.so.1. This instructs the loader to look for dependencies in the same directory. $ patchelf --set-rpath '$ORIGIN' libspssdio.so.1 Now I can load the library with ctypes: >>> from ctypes import * >>> spssio = CDLL('spssio/lin32/libspssdio.so.1') >>> spssio.spssOpenRead <_FuncPtr object at 0xb753b094> From davea at davea.name Tue Apr 2 11:48:17 2013 From: davea at davea.name (Dave Angel) Date: Tue, 02 Apr 2013 05:48:17 -0400 Subject: [Tutor] argparse iterable In-Reply-To: References: <52285.1364862670@speakeasy.net> <515A364C.4040604@davea.name> Message-ID: <515AA961.1070909@davea.name> On 04/01/2013 10:34 PM, Mark Lawrence wrote: > On 02/04/2013 02:37, Dave Angel wrote: >> On 04/01/2013 09:31 PM, Mark Lawrence wrote: >>> >>> for a in vars(parser.parse_args()): >>> print('This arg is %s' % a) >>> >>> http://docs.python.org/3/library/argparse.html#the-namespace-object >>> >>> Please don't ask me for an explanation as it took me long enough to work >>> this out from the docs :) >>> >> >> http://docs.python.org/2/library/argparse.html >> >> see section 15.4.4.6 for a very brief explanation of vars() >> >> > > Section 15.4.4.6. The Namespace object, but I can't for the life of me > remember what my link referred to :) > Whoops, sorry. I didn't notice your link was equivalent to (better than) mine. I had worked it out before your message showed up, then abandoned all of my message except for the link. BTW, can you tell me how you get the #the-namespace-object part of your link? Is there some technique (without actually looking in the source code for the page) for finding the nearest id= ? I've now figured out how to do it for pages like this one with a TOC, but is there a more general way? For others like me: If there's a TOC (table of contents) for a page, you can right-click on the link to the particular section of the page, and COPY it to the clipboard. It'll then have the form like: http://docs.python.org/3/library/argparse.html#the-namespace-object where the last field specifies the particular section of the page desired. -- DaveA From davea at davea.name Tue Apr 2 11:50:43 2013 From: davea at davea.name (Dave Angel) Date: Tue, 02 Apr 2013 05:50:43 -0400 Subject: [Tutor] argparse iterable In-Reply-To: <35358.1364869733@speakeasy.net> References: <35358.1364869733@speakeasy.net> Message-ID: <515AA9F3.2010208@davea.name> On 04/01/2013 10:28 PM, kendy at kendy.org wrote: > You guys are awesome! You make it look easy and I learn every time. > Once you've got the two dicts, take a look into the update method. It may make any loops unnecessary, except for debugging. -- DaveA From fomcl at yahoo.com Tue Apr 2 12:44:22 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 2 Apr 2013 03:44:22 -0700 (PDT) Subject: [Tutor] tadaahh! But how to identify zLinux? In-Reply-To: <515A0D6E.5080609@pearwood.info> References: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com> <515A0D6E.5080609@pearwood.info> Message-ID: <1364899462.29381.YahooMailNeo@web163802.mail.gq1.yahoo.com> > Subject: Re: [Tutor] tadaahh! But how to identify zLinux? > > On 02/04/13 09:00, Alan Gauld wrote: >> On 01/04/13 21:04, Albert-Jan Roskam wrote: >> >>> program is supposed to work with zLinux (IBM system Z). But how do I >>> know that this system is used? >> >> I have no idea what the answer is but I'm curious why you would care? >> Are you expecting that your code will be run on an IBM mainframe? > > Perhaps he is :-) Umm, well it'd be cool. And it's also kind of to satisfy my intellectual hunger/curiosity. I had never heard of zLinux before, but now I've read a thing or two about it. ? > Albert-Jan asks because his package is an interface to an external binary > library, and the location of that library differs according to the platform: ? Yes, exactly right. It's cool if it just works for all supported platforms. ? >https://bitbucket.org/fomcl/savreaderwriter/src/09b9c82406e82d43223d6610ba9cbfbf234b16d4/savReaderWriter/generic.py?at=master > > By the way, I don't know that changing directory is a good idea, if you can > avoid it at all. I for one would be *extremely* annoyed if, after calling > what otherwise seems like an innocent library routine, opening files suddenly > started failing (or worse, the wrong file was opened!) because the current > directory was different. Even though you do restore the current directory > when you are done, that makes your routines unsafe for threads. ? That loadLibrary method has been kind of a challenge. The chdir may very well be only needed on Windows. I'd have to test this (in sofar as I've access to any of these platforms). I like the fact that, under Windows, things work out of the box, without needing to modify PATH. From fomcl at yahoo.com Tue Apr 2 13:19:06 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 2 Apr 2013 04:19:06 -0700 (PDT) Subject: [Tutor] tadaahh! But how to identify zLinux? In-Reply-To: References: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com> <515A0D6E.5080609@pearwood.info> Message-ID: <1364901546.38378.YahooMailNeo@web163804.mail.gq1.yahoo.com> > From: eryksun > To: Albert-Jan Roskam > Cc: tutor at python.org > Sent: Tuesday, April 2, 2013 4:57 AM > Subject: Re: [Tutor] tadaahh! But how to identify zLinux? > > On Mon, Apr 1, 2013 at 6:42 PM, Steven D'Aprano > wrote: >> By the way, I don't know that changing directory is a good idea, if you > can >> avoid it at all. > > As far as loading linked libraries goes, changing the current > directory works on Windows, and I think OS X, but it doesn't work on > Linux. On Windows you can also add the directory to the system PATH at > run time. Ok, I'll improve that method and ditch the os.chdir calls. > I see 3 deb files in spssio/lin32. It doesn't seem like your plan is > to install these since you don't have them for lin64 as well. Is this > savReaderWriter supposed to be a self-contained system for > reading/writing IBM SPSS files, or dependent on an existing > installation of SPSS? (Not being a user of SPSS, I have no idea how > foolish that question may or may not sound. Oh well.) Yes, savReaderWriter is supposed to be a self-contained system, without the need for an expensive license. I put the?3 .deb files there as a convenience. I run Linux on a 32-bit system, so I thought I 'd just also include those files. In the help I mentioned these specific dependencies: http://pythonhosted.org/savReaderWriter/ > Anyway, I downloaded and extracted the deb files to a temp directory > on a 32-bit Debian system. In addition to the libs that you've already > extracted, ldd determined that I also needed the following libs: > > libimf.so? ? ? ? ? [intel-icc8-libs_8.0-1_i386.deb] > libcxaguard.so.5? [intel-icc8-libs_8.0-1_i386.deb > libstdc++.so.5.0.7 [libstdc++5_3.3.6-20_i386.deb] > > and links for the ELF soname fields: > > libstdc++.so.5? ? ->? libstdc++.so.5.0.7 > libicudata.so.32? ->? libicudata.so.32.0 > libicui18n.so.32? ->? libicui18n.so.32.0 > libicuuc.so.32? ? ->? libicuuc.so.32.0 How exactly did you do this? > After setting up the above, I patched a runpath of $ORIGIN into > libspssdio.so.1. This instructs the loader to look for dependencies in > the same directory. > > ? ? $ patchelf --set-rpath '$ORIGIN' libspssdio.so.1 > > Now I can load the library with ctypes: > > ? ? >>> from ctypes import * > ? ? >>> spssio = CDLL('spssio/lin32/libspssdio.so.1') > ? ? >>> spssio.spssOpenRead > ? ? <_FuncPtr object at 0xb753b094> Awesome. I knew about patchelf but I didn't feel confident enough to use this (I believe I fainted when I did 'man ld' ;-). Moreover, as we discussed before, I wasn't sure whether patching the ELF header would somehow be in violation of the IBM license agreement. I guess that including as shell script with the savReaderWriter package with the patchelf code would be okay. I'll look into this in more detail when I'm on a Linux box again. I might be back with more questions. ;-) May I ask if you run Linux 64 bit? I haven't been able to try the program on Linux 64 (only win32, win64, lin32, mac and, shortly, also aix64). I would be really pleased to know if this also works on Linux 64 (zLinux will?remain a surprise, for now ;-). This code should run without errors: import tempfile, os from savReaderWriter import * ? savFileName = os.path.join(tempfile.gettempdir(), "someFile.sav") records = [['Test1', 1, 1], ['Test2', 2, 1]] varNames = ['var1', 'v2', 'v3'] varTypes = {'var1': 5, 'v2': 0, 'v3': 0} with SavWriter(savFileName, varNames, varTypes) as writer: ??? for record in records: ??????? writer.writerow(record) with SavReader(savFileName, returnHeader=True) as reader: ???? header = reader.next() ???? print header ???? for record in reader: ?????????print record? Tutors, thanks again! ? Albert-Jan From eryksun at gmail.com Tue Apr 2 13:23:06 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 2 Apr 2013 07:23:06 -0400 Subject: [Tutor] argparse iterable In-Reply-To: <515AA961.1070909@davea.name> References: <52285.1364862670@speakeasy.net> <515A364C.4040604@davea.name> <515AA961.1070909@davea.name> Message-ID: On Tue, Apr 2, 2013 at 5:48 AM, Dave Angel wrote: > > BTW, can you tell me how you get the #the-namespace-object part of your > link? Is there some technique (without actually looking in the source code > for the page) for finding the nearest id= ?

16.4.4.6. The Namespace object ?

The paragraph symbol (?) appears when you hover over the heading. Click it to get the anchor. Here's the bit of CSS that makes the headerlink visible when you hover: a.headerlink { visibility: hidden; } h1:hover > a.headerlink, h2:hover > a.headerlink, h3:hover > a.headerlink, h4:hover > a.headerlink, h5:hover > a.headerlink, h6:hover > a.headerlink, dt:hover > a.headerlink { visibility: visible; } http://docs.python.org/3/_static/basic.css From breamoreboy at yahoo.co.uk Tue Apr 2 15:49:00 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 02 Apr 2013 14:49:00 +0100 Subject: [Tutor] argparse iterable In-Reply-To: <515AA961.1070909@davea.name> References: <52285.1364862670@speakeasy.net> <515A364C.4040604@davea.name> <515AA961.1070909@davea.name> Message-ID: On 02/04/2013 10:48, Dave Angel wrote: > > BTW, can you tell me how you get the #the-namespace-object part of your > link? Is there some technique (without actually looking in the source > code for the page) for finding the nearest id= ? I've now figured out > how to do it for pages like this one with a TOC, but is there a more > general way? I'm not aware of one, which obviously doesn't mean there's no such beast. > > For others like me: > If there's a TOC (table of contents) for a page, you can right-click on > the link to the particular section of the page, and COPY it to the > clipboard. It'll then have the form like: > http://docs.python.org/3/library/argparse.html#the-namespace-object > > where the last field specifies the particular section of the page desired. > I also go for the cut and paste approach. Maybe we need Bicycle Repair Man to do some searching for us? :) -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From d_mitchell89 at hotmail.com Tue Apr 2 18:49:32 2013 From: d_mitchell89 at hotmail.com (David Mitchell) Date: Tue, 2 Apr 2013 12:49:32 -0400 Subject: [Tutor] Python help!! Message-ID: Hi! How do I go through a text file, finding specific words/numbers/phrases and edit them to say different things? I do not want to edit the text file, I would rather open and read from the text file and write to a new file. I do NOT want to know how to replace a specific word with another every time it appears. There are some "OFF" 's that i would like to change to "ON" 's and some that I would like to change to "OPEN" for example. I am doing all this in Linux Fedora with gedit. It is a project assigned to me from my boss and I'm just a co-op student so I could really use the help. Any help would be greatly appreciated!! Thanks, David -------------- next part -------------- An HTML attachment was scrubbed... URL: From taserian at gmail.com Tue Apr 2 19:13:13 2013 From: taserian at gmail.com (taserian) Date: Tue, 2 Apr 2013 13:13:13 -0400 Subject: [Tutor] Python help!! In-Reply-To: References: Message-ID: On Tue, Apr 2, 2013 at 12:49 PM, David Mitchell wrote: > Hi! > > How do I go through a text file, finding specific words/numbers/phrases > and edit them to say different things? I do not want to edit the text file, > I would rather open and read from the text file and write to a new file. > > I do NOT want to know how to replace a specific word with another every > time it appears. There are some "OFF" 's that i would like to change to > "ON" 's and some that I would like to change to "OPEN" for example. > How would you know which ones to change to "ON" and which ones to change to "OPEN"? Additionally, how would you describe those conditions in Python? Antonio Rodriguez -------------- next part -------------- An HTML attachment was scrubbed... URL: From bodsda at googlemail.com Tue Apr 2 19:15:55 2013 From: bodsda at googlemail.com (Bod Soutar) Date: Tue, 2 Apr 2013 18:15:55 +0100 Subject: [Tutor] Python help!! In-Reply-To: References: Message-ID: On 2 April 2013 17:49, David Mitchell wrote: > Hi! > > How do I go through a text file, finding specific words/numbers/phrases and > edit them to say different things? I do not want to edit the text file, I > would rather open and read from the text file and write to a new file. > > I do NOT want to know how to replace a specific word with another every time > it appears. There are some "OFF" 's that i would like to change to "ON" 's > and some that I would like to change to "OPEN" for example. > > I am doing all this in Linux Fedora with gedit. It is a project assigned to > me from my boss and I'm just a co-op student so I could really use the help. > > Any help would be greatly appreciated!! > > Thanks, > > David Can you give us some idea of your skill level, and perhaps some code that you've already tried? Your general approach will be something like open read_file open write_file read read_file into a list close read_file iterate over the list if you find a line you want to change make the change and write to write_file else write to write_file close write_file HTH, Bodsda From dipo.elegbede at dipoelegbede.com Tue Apr 2 19:16:42 2013 From: dipo.elegbede at dipoelegbede.com (Elegbede Muhammed Oladipupo) Date: Tue, 2 Apr 2013 17:16:42 +0000 Subject: [Tutor] Python help!! In-Reply-To: References: Message-ID: <751666533-1364923002-cardhu_decombobulator_blackberry.rim.net-1888420087-@b12.c13.bise7.blackberry> What exactly do you know how to do? Can you read files? Can you replace words? This way, I can know how to help. What is hard for me to help with is the fact that you are planning to replace the same word with two different words depending on location e.g when you said you want to change off to either on or open. Let's see what you can do or have done, then help should be on the way. Regards. Regards. Sent from my BlackBerry? PORSCHE? DESIGN wireless handheld from Glo Mobile. -----Original Message----- From: David Mitchell Sender: "Tutor" Date: Tue, 2 Apr 2013 12:49:32 To: tutor at python.org Subject: [Tutor] Python help!! _______________________________________________ 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 Apr 2 19:48:44 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 02 Apr 2013 18:48:44 +0100 Subject: [Tutor] Python help!! In-Reply-To: References: Message-ID: On 02/04/13 17:49, David Mitchell wrote: > How do I go through a text file, finding specific words/numbers/phrases > and edit them to say different things? I do not want to edit the text > file, I would rather open and read from the text file and write to a new > file. OK That's easy, you just write the old file to the new file with the changes in place. > I do NOT want to know how to replace a specific word with another every > time it appears. There are some "OFF" 's that i would like to change to > "ON" 's and some that I would like to change to "OPEN" for example. OK so, instead of calling replace, you want to stop and ask the user for a replacement text? Is that the idea? > I am doing all this in Linux Fedora with gedit. I don't know gedit but both vim and emacs have interactive replacement functions, maybe gedit has too. Both vi and emacs can create macros and you can auto run macros when you start the editor, so you could automate it all using those tools. But Python can work almost as easily (and probably the finished article will be faster) > Any help would be greatly appreciated!! Why don't you tell us how you think it should work? Its likely that all the bits you need are already available to you with a little thought. Research the string methods (and if you want to get (too) clever the re module too). (I'm assuming these files are short enough to read them all into memory as a single string? If not we need to get slightly smarter.) Try a solution and tell us where you get stuck. Even pseudo code if you aren't confident with real Python. If that's too hard at least try to produce a hypothetical user session showing us what you expect the program to look like in use. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From Ankesh.Pratap at cognizant.com Tue Apr 2 20:19:34 2013 From: Ankesh.Pratap at cognizant.com (Ankesh.Pratap at cognizant.com) Date: Tue, 2 Apr 2013 18:19:34 +0000 Subject: [Tutor] Need help on win32 application error Message-ID: Hi Team, I am facing folowing erro while executing python code: Win32 exception occurred releasing IUnknown at 0x03210eb8 Please let me know the resolution of the same.PFA the version details of python exe that I am using. Thanks and Regards, Ankesh Pratap Programmer Analyst Mobile: 91-9884928733 This e-mail and any files transmitted with it are for the sole use of the intended recipient(s) and may contain confidential and privileged information. If you are not the intended recipient(s), please reply to the sender and destroy all copies of the original message. Any unauthorized review, use, disclosure, dissemination, forwarding, printing or copying of this email, and/or any action taken in reliance on the contents of this e-mail is strictly prohibited and may be unlawful. -------------- next part -------------- A non-text attachment was scrubbed... Name: IdleVersion.JPG Type: image/pjpeg Size: 18776 bytes Desc: IdleVersion.JPG URL: From bodsda at googlemail.com Tue Apr 2 20:27:36 2013 From: bodsda at googlemail.com (Bod Soutar) Date: Tue, 2 Apr 2013 19:27:36 +0100 Subject: [Tutor] Need help on win32 application error In-Reply-To: References: Message-ID: On 2 April 2013 19:19, wrote: > Hi Team, > I am facing folowing erro while executing python code: > Win32 exception occurred releasing IUnknown at 0x03210eb8 > Please let me know the resolution of the same.PFA the version details of python exe that I am using. > > > Thanks and Regards, > Ankesh Pratap > > Programmer Analyst > Mobile: 91-9884928733 > This e-mail and any files transmitted with it are for the sole use of the intended recipient(s) and may contain confidential and privileged information. If you are not the intended recipient(s), please reply to the sender and destroy all copies of the original message. Any unauthorized review, use, disclosure, dissemination, forwarding, printing or copying of this email, and/or any action taken in reliance on the contents of this e-mail is strictly prohibited and may be unlawful. > I'd say the Win32 module threw an exception when trying to release something at the memory address 0x03210eb8...... But that's just a rough guess you understand. Bodsda From eryksun at gmail.com Tue Apr 2 20:59:32 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 2 Apr 2013 14:59:32 -0400 Subject: [Tutor] tadaahh! But how to identify zLinux? In-Reply-To: <1364901546.38378.YahooMailNeo@web163804.mail.gq1.yahoo.com> References: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com> <515A0D6E.5080609@pearwood.info> <1364901546.38378.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: On Tue, Apr 2, 2013 at 7:19 AM, Albert-Jan Roskam wrote: >> On Windows you can also add the directory to the system PATH at >> run time. > > Ok, I'll improve that method and ditch the os.chdir calls. Win32 LoadLibrary searches system directories, the executable's directory, the current directory, and finally PATH. It's simple to update the PATH environment variable for the current process: os.environ['PATH'] = ';'.join([absolute_lib_path, os.environ['PATH']]) You can also call kernel32.SetDllDirectoryW(absolute_lib_path) to insert a path to be searched immediately after the executable's directory. Afterward call kernel32.SetDllDirectoryW(None) to restore the normal safe search order. >> Anyway, I downloaded and extracted the deb files >> .... >> and links for the ELF soname fields > > How exactly did you do this? I extracted the debs: dpkg-deb -x Then I copied the required .so files to the lin32 directory and created the symbolic links with "ln". > Moreover, as we discussed before, I wasn't sure whether patching > the ELF header would somehow be in violation of the IBM license > agreement. I guess that including as shell script with the > savReaderWriter package with the patchelf code would be okay. The Debian repo has ICU 4.8 (libicu48). It also has libstdc++5. I'm sure the same applies to other Linux distros. That leaves only Intel's C++ libraries to be installed: libimf.so, libirc.so, and libcxaguard.so.5. I think Intel's license allows you to redistribute these with an application. Anything less would be unreasonable. But... Actually, the fact the lin32 and lin64 versions in your repo were linked to different versions of ICU made me suspicious. I decided to downloaded "IO_Module_for_SPSS_Statistics_21001.zip" (version 21) to get the lin32 directory from the source. Turns out this version doesn't depend on Intel's libs at all, and it's linked to the ICU 4.8 libs and libstdc++.so.6. It does add libzlib123spss.so, but that's simple to preload. In fact, if you'd rather not tinker with PATH on Windows, or install libraries to the system, or patch the ELF runpath -- then you could simply load the required libraries manually in the following sequence (version 21): Linux Windows ------------------------------------- libicudata.so.48.1 icudt48.dll libicuuc.so.48.1 icuuc48.dll libicui18n.so.48.1 icuin48.dll libzlib123spss.so zlib123spss.dll libspssdio.so.1 spssio32.dll [spssio64.dll] From kendy at kendy.org Tue Apr 2 21:24:41 2013 From: kendy at kendy.org (kendy at kendy.org) Date: Tue, 02 Apr 2013 12:24:41 PDT Subject: [Tutor] argparse iterable Message-ID: <24984.1364930681@speakeasy.net> I forgot about update. It's nice and clean: a.update(b) However, when 'a' has values and 'b' is None, the 'a' item gets clobbered with None. I found this on stackoverflow.com: ------------------ old = {1: 'one', 2: 'two'} new = {1: 'newone', 2: None, 3: 'new'} old.update( (k,v) for k,v in new.iteritems() if v is not None) ------------------ Exactly what I need. Thanks for the update hint! Ken On Tue Apr 2 2:50 , Dave Angel sent: >On 04/01/2013 10:28 PM, kendy at kendy.org wrote: >> You guys are awesome! You make it look easy and I learn every time. >> > >Once you've got the two dicts, take a look into the update method. It >may make any loops unnecessary, except for debugging. > > >-- >DaveA >_______________________________________________ >Tutor maillist - Tutor at python.org >To unsubscribe or change subscription options: >http://mail.python.org/mailman/listinfo/tutor From alan.gauld at btinternet.com Tue Apr 2 21:45:03 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 02 Apr 2013 20:45:03 +0100 Subject: [Tutor] Need help on win32 application error In-Reply-To: References: Message-ID: On 02/04/13 19:19, Ankesh.Pratap at cognizant.com wrote: > Hi Team, > I am facing folowing erro while executing python code: > Win32 exception occurred releasing IUnknown at 0x03210eb8 > Please let me know the resolution of the same.PFA the version details of python exe that I am using. The solution is that you need to fix an error in your code. But without any clue as to what your code looks like how are we supposed to guess what caused the error? I assume you don't get this just starting IDLE? What code are you running? How are you running it? Do you get any other output - like a window displayed, text in the shell window of IDLE? Anything? Which version of windows are you using? From the screenshot it looks like XP but that could just be a UI setting... We need more detail. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mail at timgolden.me.uk Tue Apr 2 21:50:27 2013 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 02 Apr 2013 20:50:27 +0100 Subject: [Tutor] Need help on win32 application error In-Reply-To: References: Message-ID: <515B3683.4000500@timgolden.me.uk> On 02/04/2013 19:19, Ankesh.Pratap at cognizant.com wrote: > I am facing folowing erro while executing python code: > Win32 exception occurred releasing IUnknown at 0x03210eb8 You need to give us a bit more of a clue as to what your code does. My guess is that you're using the pywin32 packages and, possibly, the MAPI COM interface? That occasionally throws up that sort of exception. Assuming I'm right, you're better off asking on the python-win32 mailing list, ideally with a reproducible code sample. TJG From doark at mail.com Wed Apr 3 21:43:02 2013 From: doark at mail.com (frank ernest) Date: Wed, 03 Apr 2013 15:43:02 -0400 Subject: [Tutor] Proper uses of classes Message-ID: <20130403194302.327670@gmx.com> Hi guys, it's been a while since I posted and I've learned a lot since then. Today I have a question on classes, I can't get mine to work. class alist(list): def __init__(self, b, a): self = list() self.append(b) a = a + b def appendit(self): self.append(a) ? print(alist(2,4)) [] #It's blank! c = alist(2,4) c.appendit() print(c) [[...]] #It's still blank! If I add this: a = a + b ? the last line of my deffinition I get: c = alist(2,4) c.appendit() Traceback (most recent call last): File "", line 1, in File "", line 7, in appendit UnboundLocalError: local variable 'a' referenced before assignment If I make a nonlocal I get SyntaxError: name 'a' is parameter and nonlocal I want it to get my list and all the members in it when printing for instance. I also would like to without making them global create two variables which I can use throughout the whole class as their value will not change. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Wed Apr 3 23:16:15 2013 From: davea at davea.name (Dave Angel) Date: Wed, 03 Apr 2013 17:16:15 -0400 Subject: [Tutor] Proper uses of classes In-Reply-To: <20130403194302.327670@gmx.com> References: <20130403194302.327670@gmx.com> Message-ID: <515C9C1F.3070600@davea.name> On 04/03/2013 03:43 PM, frank ernest wrote: > Hi guys, it's been a while since I posted and I've learned a lot since then. Today I have a question on classes, I can't get mine to work. Welcome back. I'll try. First comment is that indentation ought to be 4 columns, until you have enough experience to prefer something different. Certainly one column makes the code nearly illegible to me. Second comment is that deriving from a built-in class like list is tricky. It won't be enough to define an __init__() method, and it turns out you're not using the inheritance anyway. So please get this working using only object as your base. You're probably using Python3.x, where object is implied, but it doesn't hurt to be specific. class alist(object): > class alist(list): > def __init__(self, b, a): > self = list() You forgot to indent the body of the method. That's an IndentationError during compile, so I suspect this code is NOT what you tried. I'll assume you indent the lines from here through the 'def appendit' line. Please use copy/paste to put your code into your email message. If you retype it, you waste everybody's time. Don't assign to 'self,' as once you do, you no longer have any access to the class instance. It's a parameter, automatically passed to your method. You probably want to add an attribute to hold the new list. I'll assume you change it to: self.mylist = list() self.mylist.append(b) > self.append(b) > a = a + b > def appendit(self): > self.append(a) You didn't indent again. Further, you referenced a, which was a parameter to an entirely different method. If you meant for it to be saved, you could have made it a new attribute in the first method, by using self.a = a > ? > print(alist(2,4)) You never added anything to the list, so of course it prints out as empty. You created a new one inside your class. > [] > #It's blank! > c = alist(2,4) > c.appendit() > print(c) > [[...]] > #It's still blank! > If I add this: > a = a + b > ? > the last line of my deffinition I get: > c = alist(2,4) > c.appendit() > Traceback (most recent call last): > File "", line 1, in > File "", line 7, in appendit > UnboundLocalError: local variable 'a' referenced before assignment > If I make a nonlocal I get > SyntaxError: name 'a' is parameter and nonlocal > I want it to get my list and all the members in it when printing for instance. I also would like to without making them global create two variables which I can use throughout the whole class as their value will not change. > If you want a custom printing behavior, you'd need to define a __str__() method in your class. Since you don't, and since you inherit from list, you get its behavior. I made the assumption throughout that it was a mistake to inherit from list. Most of my answers could have been different if you were really deliberate about inheriting from list. For example, you wouldn't be able to create your own list, but would have to use the one that you inherited from. You'd have to define a __new__() method, and call list's __new__() method from it. And if you created extra instances as your last sentence says, you'd have to define your own __str__() method, as the built in list logic wouldn't recognize anything you added. In any case, I'd write a few successful plain classes before even beginning to do inheritance. HTH -- DaveA From alan.gauld at btinternet.com Thu Apr 4 00:09:17 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 03 Apr 2013 23:09:17 +0100 Subject: [Tutor] Proper uses of classes In-Reply-To: <20130403194302.327670@gmx.com> References: <20130403194302.327670@gmx.com> Message-ID: On 03/04/13 20:43, frank ernest wrote: > Hi guys, it's been a while since I posted and I've learned a lot since > then. Today I have a question on classes, I can't get mine to work. Dave has already addressed many issues but there are a few more to consider > class alist(list): > > def __init__(self, b, a): > self = list() This should be indented but it makes no sense. You are trying to create a subclass of list but by assigning self to list you no longer have a reference to your class, self now points at an instance of the builtin list. self is already a list by the time you get to __init__. > self.append(b) This could work without the list() assignment above. > a = a + b this makes no sense since a and b are arguments passed into the method and you don't store the result so it gets thrown away, I assume you intended self.a = a+b > def appendit(self): > self.append(a) Again I assume you meant self.append(self.a) And this is odd indeed since it can only ever keep adding the 'a' specified during initialization. Normally I'd expect an item to be appended to be included in the method call? But then you already have that with the inherited append method son maybe this odd behaviour is what distinguishes your list from the built in list? > print(alist(2,4)) > > [] > > #It's blank! Yes because you changed self to be a list and so your alist object had no changes made to it. > c = alist(2,4) > c.appendit() > print(c) > [[...]] > > #It's still blank! No, it now has a list inside, although how that got there I'm not sure! > If I add this: > a = a + b > the last line of my deffinition I get: Again you omit self so you are only redefining the local variables, except there is no 'a' or 'b' to refer to. > c = alist(2,4) > > c.appendit() > > Traceback (most recent call last): > File "", line 1, in > File "", line 7, in appendit > UnboundLocalError: local variable 'a' referenced before assignment Since you didn't pass an a into the method you can't assign it to a. > If I make a nonlocal I get What do you mean by making it non local? What did you do? > SyntaxError: name 'a' is parameter and nonlocal > > I want it to get my list and all the members in it when printing for > instance. I also would like to without making them global create two > variables which I can use throughout the whole class as their value will > not change. Your problems lie in how you build the class in init... Get the initialisation right and the append/print methods will be easy. But see Dave's comments re __str__... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From phil_lor at bigpond.com Thu Apr 4 01:14:21 2013 From: phil_lor at bigpond.com (Phil) Date: Thu, 04 Apr 2013 09:14:21 +1000 Subject: [Tutor] Classes in multiple files Message-ID: <515CB7CD.2030506@bigpond.com> Thank you for reading this. The recent question relating to classes has prompted to ask this one. I have a main window class and a dialog class and they are defined in separate files. I'm attempting to display the dialog when a menu item is selected in the main window but it doesn't work because, I think, the main window class isn't aware of the dialog class in another file. This is the beginning of the main window class; class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent = None): And this is the beginning of the dialog class; class SatelliteListDialog(QDialog, Ui_Dialog): def __init__(self, parent = None): If this was C++ then I'd need to include a class header and so I'm thinking that an import statement is needed in the main window class referring to the dialog class. Import SatelliteListDialog isn't correct. There are many on-line examples that deal with displaying dialogs, however, both classes are in the same file rather that being separated. No doubt, this is a trivial question but, as yet, I have not found an answer. -- Regards, Phil From alan.gauld at btinternet.com Thu Apr 4 01:32:43 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 04 Apr 2013 00:32:43 +0100 Subject: [Tutor] Classes in multiple files In-Reply-To: <515CB7CD.2030506@bigpond.com> References: <515CB7CD.2030506@bigpond.com> Message-ID: On 04/04/13 00:14, Phil wrote: > If this was C++ then I'd need to include a class header and so I'm > thinking that an import statement is needed in the main window class > referring to the dialog class. Import SatelliteListDialog isn't correct. Reme,ber that in python its the file name you need to use to import So if SatelliteListDialog is defined in satellite.py you need import satellite in your main window file. And satellite.py has to be in your library path too... Then in your main window class you need to access the dialog with self.sld = satellite.SatelliteListDialog(...) or whatever. In other words you need the module name prefix. If that still doesn't work post some code and any error messages. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bessenkphilip at gmail.com Thu Apr 4 03:29:02 2013 From: bessenkphilip at gmail.com (bessenkphilip) Date: Thu, 04 Apr 2013 06:59:02 +0530 Subject: [Tutor] Doubt in for loop Message-ID: <515CD75E.3030306@gmail.com> Hi all, I'm having a doubt in the below program's 2n'd "for" loop. >>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print n, 'equals', x, '*', n/x ... break ... else: ... # loop fell through without finding a factor ... print n, 'is a prime number' ... 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 My doubt is that "will 'x' be always of value 2, if so why that for loop "for x in range(2, n):" i don't know how the first output , as If 2%2==0:(this satisfies the if loop as x =2) , so how the else part came to output i.e 2 is a prime number. Please educate me in this. Thanks in advance, -Bessen From phil_lor at bigpond.com Thu Apr 4 02:22:11 2013 From: phil_lor at bigpond.com (Phil) Date: Thu, 04 Apr 2013 10:22:11 +1000 Subject: [Tutor] Classes in multiple files In-Reply-To: References: <515CB7CD.2030506@bigpond.com> Message-ID: <515CC7B3.20204@bigpond.com> On 04/04/13 09:32, Alan Gauld wrote: > On 04/04/13 00:14, Phil wrote: > >> If this was C++ then I'd need to include a class header and so I'm >> thinking that an import statement is needed in the main window class >> referring to the dialog class. Import SatelliteListDialog isn't correct. > > Reme,ber that in python its the file name you need to use to import > > So if SatelliteListDialog is defined in satellite.py you need > > import satellite > > in your main window file. > And satellite.py has to be in your library path too... > That makes sense, much like a header file in C++. I haven't set a library path, so I'm using the default, what ever it may be. I'll investigate this. > Then in your main window class you need to access the dialog with > > self.sld = satellite.SatelliteListDialog(...) > > or whatever. In other words you need the module name prefix. > > If that still doesn't work post some code and any error messages. > At the moment I'm a little uncertain how I should proceed from here but I'll give it a go. -- Regards, Phil From phil_lor at bigpond.com Thu Apr 4 03:47:05 2013 From: phil_lor at bigpond.com (Phil) Date: Thu, 04 Apr 2013 11:47:05 +1000 Subject: [Tutor] Classes in multiple files - code included In-Reply-To: References: <515CB7CD.2030506@bigpond.com> Message-ID: <515CDB99.7010609@bigpond.com> On 04/04/13 09:32, Alan Gauld wrote: > Reme,ber that in python its the file name you need to use to import > > So if SatelliteListDialog is defined in satellite.py you need > > import satellite > > in your main window file. > And satellite.py has to be in your library path too... The Eric IDE must take care of the path. All I had to do was import the file containing the dialog class. > Then in your main window class you need to access the dialog with > > self.sld = satellite.SatelliteListDialog(...) > > or whatever. In other words you need the module name prefix. > > If that still doesn't work post some code and any error messages. I think I must be very close now so I'll post just the code that I think is relevant. This the main window class: from PyQt4.QtGui import QMainWindow from PyQt4.QtCore import pyqtSignature from Ui_mainwindow import Ui_MainWindow from PyQt4 import QtGui import satListDialog class MainWindow(QMainWindow, Ui_MainWindow): This is the function to show the dialog; def on_actionList_triggered(self): self.dialog = Ui_satListDialog.SatelliteListDialog() self.dialog.show() Finally, this is the dialog class; from PyQt4.QtGui import QDialog from PyQt4.QtCore import pyqtSignature from Ui_satListDialog import Ui_Dialog class SatelliteListDialog(QDialog, Ui_Dialog): And this is the error message; "global name 'Ui_satListDialog' is not defined" I have tried just about every conceivable combination in the on_actionList_triggered(self) function but I still end up with a "not defined" error. -- Regards, Phil From steve at pearwood.info Thu Apr 4 03:53:41 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 04 Apr 2013 12:53:41 +1100 Subject: [Tutor] Doubt in for loop In-Reply-To: <515CD75E.3030306@gmail.com> References: <515CD75E.3030306@gmail.com> Message-ID: <515CDD25.8050208@pearwood.info> On 04/04/13 12:29, bessenkphilip wrote: > Hi all, > > I'm having a doubt in the below program's 2n'd "for" loop. > >>>> for n in range(2, 10): > ... for x in range(2, n): > ... if n % x == 0: > ... print n, 'equals', x, '*', n/x > ... break > ... else: > ... # loop fell through without finding a factor > ... print n, 'is a prime number' > ... > 2 is a prime number > 3 is a prime number > 4 equals 2 * 2 > 5 is a prime number > 6 equals 2 * 3 > 7 is a prime number > 8 equals 2 * 4 > 9 equals 3 * 3 > > My doubt is that "will 'x' be always of value 2, if so why that for loop "for x in range(2, n):" > i don't know how the first output , as If 2%2==0:(this satisfies the if loop as x =2) , so how the else part came to output i.e 2 is a prime number. I'm sorry, I don't understand your question. x is *not* always of value 2. You can see with the last line, 9 equals 3 * 3 x has value 3. The outer loop just checks 2, 3, 4, ... 9 to see whether they are prime. The inner loop actually does the checking: for x in range(2, n): if n % x == 0: print n, 'equals', x, '*', n/x break This tests whether n is divisible by 2, 3, 4, 5, 6, ... up to n-1. If n is divisible by any of those numbers, then n cannot be prime. For example, with n = 9, the inner loop does this: x = 2 Test if 2 is a factor: does 9/2 have remainder zero? No. x = 3 Test if 3 is a factor: does 9/3 have remainder zero? Yes. So 9 is not prime, and 9 = 3 * (9/3) = 3 * 3 If we test it with n = 35, the inner loop would do this: x = 2 Test if 2 is a factor: does 35/2 have remainder zero? No. x = 3 Test if 3 is a factor: does 35/3 have remainder zero? No. x = 4 Test if 4 is a factor: does 35/4 have remainder zero? No. x = 5 Test if 5 is a factor: does 35/5 have remainder zero? Yes. So 35 is not prime, and 35 = 5 * (35/5) = 5 * 7 Notice that this does more work than necessary! Can you see what work it does that is unnecessary? (Hint: what even numbers are prime?) -- Steven From steve at pearwood.info Thu Apr 4 03:58:09 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 04 Apr 2013 12:58:09 +1100 Subject: [Tutor] Classes in multiple files - code included In-Reply-To: <515CDB99.7010609@bigpond.com> References: <515CB7CD.2030506@bigpond.com> <515CDB99.7010609@bigpond.com> Message-ID: <515CDE31.9010301@pearwood.info> On 04/04/13 12:47, Phil wrote: > And this is the error message; > > "global name 'Ui_satListDialog' is not defined" On its own, that is almost useless. Python gives you more debugging information than that: it gives you a complete traceback, which includes the actual line of code causing the problem. We don't even know which file gives the error, let alone which line of code! When you try to run the program, you will get an error. Please copy and paste the *complete* traceback, starting with the line "Traceback (most recent call last)" all the way to the bottom. It will show you which file contains the error, what type of error it is, and which line fails. Thank you. -- Steven From davea at davea.name Thu Apr 4 04:53:15 2013 From: davea at davea.name (Dave Angel) Date: Wed, 03 Apr 2013 22:53:15 -0400 Subject: [Tutor] Doubt in for loop In-Reply-To: <515CDD25.8050208@pearwood.info> References: <515CD75E.3030306@gmail.com> <515CDD25.8050208@pearwood.info> Message-ID: <515CEB1B.30004@davea.name> On 04/03/2013 09:53 PM, Steven D'Aprano wrote: > On 04/04/13 12:29, bessenkphilip wrote: >> Hi all, >> >> I'm having a doubt in the below program's 2n'd "for" loop. >> >>>>> for n in range(2, 10): >> ... for x in range(2, n): >> ... if n % x == 0: >> ... print n, 'equals', x, '*', n/x >> ... break >> ... else: >> ... # loop fell through without finding a factor >> ... print n, 'is a prime number' >> ... >> 2 is a prime number >> 3 is a prime number >> 4 equals 2 * 2 >> 5 is a prime number >> 6 equals 2 * 3 >> 7 is a prime number >> 8 equals 2 * 4 >> 9 equals 3 * 3 >> >> My doubt is that "will 'x' be always of value 2, if so why that for >> loop "for x in range(2, n):" >> i don't know how the first output , as If 2%2==0:(this satisfies the >> if loop as x =2) , so how the else part came to output i.e 2 is a >> prime number. > > I'm sorry, I don't understand your question. > > x is *not* always of value 2. You can see with the last line, > > 9 equals 3 * 3 > > x has value 3. > > > The outer loop just checks 2, 3, 4, ... 9 to see whether they are prime. > The inner loop actually does the checking: > > > for x in range(2, n): > if n % x == 0: > print n, 'equals', x, '*', n/x > break > > > This tests whether n is divisible by 2, 3, 4, 5, 6, ... up to n-1. If n > is divisible by any of those numbers, then n cannot be prime. > > For example, with n = 9, the inner loop does this: > > x = 2 > Test if 2 is a factor: does 9/2 have remainder zero? No. > x = 3 > Test if 3 is a factor: does 9/3 have remainder zero? Yes. > So 9 is not prime, and 9 = 3 * (9/3) = 3 * 3 > > > If we test it with n = 35, the inner loop would do this: > > x = 2 > Test if 2 is a factor: does 35/2 have remainder zero? No. > x = 3 > Test if 3 is a factor: does 35/3 have remainder zero? No. > x = 4 > Test if 4 is a factor: does 35/4 have remainder zero? No. > x = 5 > Test if 5 is a factor: does 35/5 have remainder zero? Yes. > So 35 is not prime, and 35 = 5 * (35/5) = 5 * 7 > > > > Notice that this does more work than necessary! Can you see what work it > does that is unnecessary? > > (Hint: what even numbers are prime?) > > > > I don't understand the questions either, but I can point out one thing that might be puzzling the OP: When n is 2, the inner loop does nothing, it just skips to the else clause. The reason is that range(2,2) is a null iterator. range(i,j) produces values from i to j-1, or to put it another way values for which i <= n < j If i and j are identical, there's nothing to match it. -- DaveA From antipode0 at gmail.com Thu Apr 4 05:34:10 2013 From: antipode0 at gmail.com (antipode0) Date: Wed, 3 Apr 2013 22:34:10 -0500 Subject: [Tutor] Doubt in for loop In-Reply-To: <515CEB1B.30004@davea.name> References: <515CD75E.3030306@gmail.com> <515CDD25.8050208@pearwood.info> <515CEB1B.30004@davea.name> Message-ID: I believe Dave answered the OP's intended question. On Apr 3, 2013 9:54 PM, "Dave Angel" wrote: > On 04/03/2013 09:53 PM, Steven D'Aprano wrote: > >> On 04/04/13 12:29, bessenkphilip wrote: >> >>> Hi all, >>> >>> I'm having a doubt in the below program's 2n'd "for" loop. >>> >>> for n in range(2, 10): >>>>>> >>>>> ... for x in range(2, n): >>> ... if n % x == 0: >>> ... print n, 'equals', x, '*', n/x >>> ... break >>> ... else: >>> ... # loop fell through without finding a factor >>> ... print n, 'is a prime number' >>> ... >>> 2 is a prime number >>> 3 is a prime number >>> 4 equals 2 * 2 >>> 5 is a prime number >>> 6 equals 2 * 3 >>> 7 is a prime number >>> 8 equals 2 * 4 >>> 9 equals 3 * 3 >>> >>> My doubt is that "will 'x' be always of value 2, if so why that for >>> loop "for x in range(2, n):" >>> i don't know how the first output , as If 2%2==0:(this satisfies the >>> if loop as x =2) , so how the else part came to output i.e 2 is a >>> prime number. >>> >> >> I'm sorry, I don't understand your question. >> >> x is *not* always of value 2. You can see with the last line, >> >> 9 equals 3 * 3 >> >> x has value 3. >> >> >> The outer loop just checks 2, 3, 4, ... 9 to see whether they are prime. >> The inner loop actually does the checking: >> >> >> for x in range(2, n): >> if n % x == 0: >> print n, 'equals', x, '*', n/x >> break >> >> >> This tests whether n is divisible by 2, 3, 4, 5, 6, ... up to n-1. If n >> is divisible by any of those numbers, then n cannot be prime. >> >> For example, with n = 9, the inner loop does this: >> >> x = 2 >> Test if 2 is a factor: does 9/2 have remainder zero? No. >> x = 3 >> Test if 3 is a factor: does 9/3 have remainder zero? Yes. >> So 9 is not prime, and 9 = 3 * (9/3) = 3 * 3 >> >> >> If we test it with n = 35, the inner loop would do this: >> >> x = 2 >> Test if 2 is a factor: does 35/2 have remainder zero? No. >> x = 3 >> Test if 3 is a factor: does 35/3 have remainder zero? No. >> x = 4 >> Test if 4 is a factor: does 35/4 have remainder zero? No. >> x = 5 >> Test if 5 is a factor: does 35/5 have remainder zero? Yes. >> So 35 is not prime, and 35 = 5 * (35/5) = 5 * 7 >> >> >> >> Notice that this does more work than necessary! Can you see what work it >> does that is unnecessary? >> >> (Hint: what even numbers are prime?) >> >> >> >> >> > I don't understand the questions either, but I can point out one thing > that might be puzzling the OP: > > When n is 2, the inner loop does nothing, it just skips to the else > clause. The reason is that range(2,2) is a null iterator. range(i,j) > produces values from i to j-1, or to put it another way values for which > i <= n < j > > If i and j are identical, there's nothing to match it. > > > -- > 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 phil_lor at bigpond.com Thu Apr 4 04:12:04 2013 From: phil_lor at bigpond.com (Phil) Date: Thu, 04 Apr 2013 12:12:04 +1000 Subject: [Tutor] Classes in multiple files - code included In-Reply-To: <515CDE31.9010301@pearwood.info> References: <515CB7CD.2030506@bigpond.com> <515CDB99.7010609@bigpond.com> <515CDE31.9010301@pearwood.info> Message-ID: <515CE174.9000602@bigpond.com> On 04/04/13 11:58, Steven D'Aprano wrote: > On 04/04/13 12:47, Phil wrote: > >> And this is the error message; >> >> "global name 'Ui_satListDialog' is not defined" > > On its own, that is almost useless. > > Python gives you more debugging information than that: it gives you a > complete traceback, which includes the actual line of code causing the > problem. We don't even know which file gives the error, let alone which > line of code! > > When you try to run the program, you will get an error. Please copy and > paste the *complete* traceback, starting with the line "Traceback (most > recent call last)" all the way to the bottom. It will show you which > file contains the error, what type of error it is, and which line fails. > Thank you for your reply Steven, As useless as the error message may be it's the only one given. phil at Asus:~/Eric/Pest$ python pest.py Traceback (most recent call last): File "/home/phil/Eric/Pest/ui/mainwindow.py", line 57, in on_actionList_triggered dialog = Ui_satListDialog.SatelliteListDialog(self) NameError: global name 'Ui_satListDialog' is not defined ^CTraceback (most recent call last): File "pest.py", line 9, in sys.exit(app.exec_()) -- Regards, Phil From __peter__ at web.de Thu Apr 4 08:58:01 2013 From: __peter__ at web.de (Peter Otten) Date: Thu, 04 Apr 2013 08:58:01 +0200 Subject: [Tutor] Classes in multiple files - code included References: <515CB7CD.2030506@bigpond.com> <515CDB99.7010609@bigpond.com> Message-ID: Phil wrote: > I think I must be very close now so I'll post just the code that I think > is relevant. > > This the main window class: > import satListDialog Here you are importing the module "satListDialog" > class MainWindow(QMainWindow, Ui_MainWindow): > > This is the function to show the dialog; > > def on_actionList_triggered(self): > > self.dialog = Ui_satListDialog.SatelliteListDialog() > self.dialog.show() and here you are referring to the module "Ui_satListDialog". I'd guess that should be self.dialog = satListDialog.SatelliteListDialog() instead. From phil_lor at bigpond.com Thu Apr 4 09:51:02 2013 From: phil_lor at bigpond.com (Phil) Date: Thu, 04 Apr 2013 17:51:02 +1000 Subject: [Tutor] Classes in multiple files - code included In-Reply-To: References: <515CB7CD.2030506@bigpond.com> <515CDB99.7010609@bigpond.com> Message-ID: <515D30E6.3040803@bigpond.com> On 04/04/13 16:58, Peter Otten wrote: > Phil wrote: > >> I think I must be very close now so I'll post just the code that I think >> is relevant. >> >> This the main window class: > >> import satListDialog > > Here you are importing the module "satListDialog" > >> class MainWindow(QMainWindow, Ui_MainWindow): >> >> This is the function to show the dialog; >> >> def on_actionList_triggered(self): >> >> self.dialog = Ui_satListDialog.SatelliteListDialog() >> self.dialog.show() > > and here you are referring to the module "Ui_satListDialog". I'd guess that > should be > > self.dialog = satListDialog.SatelliteListDialog() > > instead. Thanks Peter, This one of those times when I wish I could cancel a question. I discovered the answer, mostly through trial and error, a couple of hours ago. I had also accidentally commented out a line in the dialog class. Anyway, I've made some headway with PyQt today. By the way, I notice that it can take several hours for my postings to appear on the list. Possibly due to moderation? -- Regards, Phil From steve at pearwood.info Thu Apr 4 11:40:46 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Thu, 04 Apr 2013 20:40:46 +1100 Subject: [Tutor] Classes in multiple files - code included In-Reply-To: <515CE174.9000602@bigpond.com> References: <515CB7CD.2030506@bigpond.com> <515CDB99.7010609@bigpond.com> <515CDE31.9010301@pearwood.info> <515CE174.9000602@bigpond.com> Message-ID: <515D4A9E.9060005@pearwood.info> On 04/04/13 13:12, Phil wrote: > On 04/04/13 11:58, Steven D'Aprano wrote: >> On 04/04/13 12:47, Phil wrote: >> >>> And this is the error message; >>> >>> "global name 'Ui_satListDialog' is not defined" >> >> On its own, that is almost useless. >> >> Python gives you more debugging information than that: it gives you a >> complete traceback, which includes the actual line of code causing the >> problem. We don't even know which file gives the error, let alone which >> line of code! >> >> When you try to run the program, you will get an error. Please copy and >> paste the *complete* traceback, starting with the line "Traceback (most >> recent call last)" all the way to the bottom. It will show you which >> file contains the error, what type of error it is, and which line fails. >> > > Thank you for your reply Steven, > > As useless as the error message may be it's the only one given. You have misunderstood me. In your email, quoted above, you pasted ONLY the error message "global name 'Ui_satListDialog' is not defined". But now, following my prompting, you pasted the ENTIRE traceback: > phil at Asus:~/Eric/Pest$ python pest.py > Traceback (most recent call last): > File "/home/phil/Eric/Pest/ui/mainwindow.py", line 57, in on_actionList_triggered > dialog = Ui_satListDialog.SatelliteListDialog(self) > NameError: global name 'Ui_satListDialog' is not defined > ^CTraceback (most recent call last): > File "pest.py", line 9, in > sys.exit(app.exec_()) Notice how much more information there is? We learn: * the error is occurring in your mainwindow.py file * on line 57 * in the function or method "on_actionList_triggered" * with the exact line "dialog = Ui_satListDialog.SatelliteListDialog(self)" * which gives a NameError (as apposed to any of dozens of different sorts of error) * with the specific error message "global name 'Ui_satListDialog' is not defined" (and then there is a further error when you try to quit the app with Ctrl-C, but one thing at a time). One of the most critical skills for a programmer is to learn how to diagnose errors. Trying to diagnose the error from just the error message is a bit like telling the doctor you have a pain, but refusing to tell where the pain is, what sort of pain, how long you've had it, or under what circumstances it comes and goes. Debugging, at times, is hard enough even with the assistance of full tracebacks. You'll soon learn to appreciate them. -- Steven From alan.gauld at btinternet.com Thu Apr 4 14:45:04 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 04 Apr 2013 13:45:04 +0100 Subject: [Tutor] Classes in multiple files - code included In-Reply-To: <515D30E6.3040803@bigpond.com> References: <515CB7CD.2030506@bigpond.com> <515CDB99.7010609@bigpond.com> <515D30E6.3040803@bigpond.com> Message-ID: On 04/04/13 08:51, Phil wrote: > By the way, I notice that it can take several hours for my postings to > appear on the list. Possibly due to moderation? Nope, the only posts that get moderated are the ones where the poster has not subscribed to the list (or is using a different email address than the one they signed up with!) Remember email is not a high priority message type on the internet. The suggested SLA for delivery used to be 48 hours but I believe current recommendations say 24 hours. So even though mail usually gets there much faster than that you shouldn't count on it. (Note that if you are using corporate "email" like Microsoft Exchange that's not really email at all, just corporate messaging which is nearly instant!). And of course email is not guaranteed delivery either so it might never get there - if a server gets busy it's quite within its rights to just throw all the email messages away...! And the nature of the internet is that your mail may be routing through somebody's old 50MHz 486 PC server somewhere in Uzbekistan or Mongolia... Having said all that, I rarely see a post to tutor take more than 20 minutes to get onto the gmane newsfeed that I use from the list server. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cevyne at gmail.com Mon Apr 1 21:08:00 2013 From: cevyne at gmail.com (cevyn e) Date: Mon, 1 Apr 2013 15:08:00 -0400 Subject: [Tutor] os.system() with imbeded quotes Message-ID: I get the example os.system('ls -al') no problem. i'm trying to create a variable with my command built but needs to include quotes. Portion of code is as follows: someip = '192.168.01.01' var1 = 'lynx -dump http://' + someip + '/cgi-bin/xxxx.log&.submit=+++Go%21+++ > junk' print var1 os.system(var1) If I print var1 it looks right . If I use the os.system(var1) as above it seems to have a problem near the end of the string with msg sh: .submit=+++Go%21+++: command not found clearly there is some escape sequence that I don't understand . I tried combinations of single and double quotes and mixed around var1, but that generates command not found. I need it to look like how I enter it manually and works lynx -dump 'http://192.168.01.01/cgi-bin/xxxx.log&.submit=+++Go%21+++ > junk' Probably obvious to many but i'm spinning my wheels. many thanks for help . -------------- next part -------------- An HTML attachment was scrubbed... URL: From moshiri.ehsan.ns at gmail.com Tue Apr 2 05:01:55 2013 From: moshiri.ehsan.ns at gmail.com (EnkidU Moshiri) Date: Tue, 2 Apr 2013 11:01:55 +0800 Subject: [Tutor] chat-server python Message-ID: Hello there, am beginner in python. i want start my first project with chat-server. i want create a messenger which encodes msg, hides it in a image(steganography) and send it to second user. i want this messenger be available also by internet and non static ips,so i want use chat server. also i want filter incoming packets,which only trusted MAC addresses can communicate with mesenger may i get some help from u? any chat-server messenger source code for python? after i finish encoding and steganography part,i will upload my job in your site thank u -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Apr 4 14:59:48 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 04 Apr 2013 13:59:48 +0100 Subject: [Tutor] moderation queue flushed - may be old/duplicates coming through Message-ID: I've just flushed the queue so there will be some old or duplicate messages coming through. Apologies, but I hadn't looked in there for a couple of weeks! Oops. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From msirenef at lightbird.net Thu Apr 4 15:25:19 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Thu, 04 Apr 2013 09:25:19 -0400 Subject: [Tutor] File Import In-Reply-To: References: Message-ID: <515D7F3F.6050700@lightbird.net> On 03/18/2013 11:14 PM, Clark, Tristan wrote: > 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 > Take a look at csv module (for Py2, see drop down version choice for Py3): http://docs.python.org/2/library/csv.html Is the data going to be ASCII? There are some issues in regard to csv / unicode handling. -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ From msirenef at lightbird.net Thu Apr 4 15:26:47 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Thu, 04 Apr 2013 09:26:47 -0400 Subject: [Tutor] Help required In-Reply-To: References: Message-ID: <515D7F97.2060107@lightbird.net> On 03/20/2013 02:12 AM, Arijit Ukil wrote: > 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 > fordata inlist_of_lists: > lstval = data.split (/','/) > timest = float(lstval[0]) > energy = float(lstval[1]) > > f.close() > printtimest > > Regards, > Arijit Ukil You would want to create an empty list and then append values to it inside the loop. E.g. lst=[]; lst.append(val) -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ From msirenef at lightbird.net Thu Apr 4 15:32:33 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Thu, 04 Apr 2013 09:32:33 -0400 Subject: [Tutor] Tutor Digest, Vol 109, Issue 71 In-Reply-To: <-1797977811238906169@unknownmsgid> References: <-1797977811238906169@unknownmsgid> Message-ID: <515D80F1.3020601@lightbird.net> On 03/20/2013 09:14 PM, Matthew Johnson wrote: > 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 You should refer to my earlier answer using groupby -- where I sorted the list before using groupby on it; you can read some notes on this in python groupby documentation. I'm not sure why you insist on using groupby for this problem. I would also try to stay away from packing so much in a single list comp as the SO answer does, and instead split things into separate steps where each step is simple and clear, then you'd be able to print out intermediate results and see what exactly is happening. -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ From sayanchatterjee at gmail.com Thu Apr 4 15:40:33 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Thu, 4 Apr 2013 19:10:33 +0530 Subject: [Tutor] TypeError: can't multiply sequence by non-int of type 'float' Message-ID: Dear All, I know this error occurs when one tries to multiply a string with a fraction i.e float. In my case , I can't figure out how can a numpy floating point array be a string. Interestingly, the concerned expression gets printed in the loop for the first time but on the second go it fails. The concerned snippet of code is given below : for t in t_range(0,1,0.1): print t p_za=[] pv_za=[] # Opening file in file_t format fname = 'file_' + str(t) + '.dat' fo = open(fname,'w') # p_za.append(p_initial - t*K*np.sin(K*p_initial)) print 'K=',K print 'pv_za_temp =',pv_za_temp print '- t*K*np.sin(K*p_initial) = ',- t*K*np.sin(K*p_initial) print '-K*np.sin(K*pv_za_temp) = ',-K*np.sin(K*pv_za_temp) pv_za.append(-K*np.sin(K*pv_za_temp)) pv_za_temp = [] pv_za_temp.append(np.array(pv_za)) Here is paste the output,which clearly shows that the concerned expression i.e -K*np.sin(K*pv_za_temp) prints perfectly for the first looping. Also see the error that comes on the second looping. I'm clueless. 0 K= 3.14159265359 pv_za_temp = [ 0. 0.5 1. 1.5 2. ] - t*K*np.sin(K*p_initial) = [ 0. 0. -0. -0. 0.] *-K*np.sin(K*pv_za_temp) = [ -0.00000000e+00 -3.14159265e+00 6.49753967e-13 3.14159265e+00* * -1.29950793e-12] PRINTS PERFECTLY* * * 0.1 K= 3.14159265359 pv_za_temp = [array([[ -0.00000000e+00, -3.14159265e+00, 6.49753967e-13, 3.14159265e+00, -1.29950793e-12]])] - t*K*np.sin(K*p_initial) = [ -0.00000000e+00 -3.14159265e-01 6.49753967e-14 3.14159265e-01 -1.29950793e-13] -K*np.sin(K*pv_za_temp) = *ERROR* Traceback (most recent call last): File "ZA.py", line 45, in print '-K*np.sin(K*pv_za_temp) = ',-K*np.sin(K*pv_za_temp) *TypeError: can't multiply sequence by non-int of type 'float'* Please Help!!!! Cheers, 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 sayanchatterjee at gmail.com Thu Apr 4 15:41:21 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Thu, 4 Apr 2013 19:11:21 +0530 Subject: [Tutor] TypeError: can't multiply sequence by non-int of type 'float' In-Reply-To: References: Message-ID: I attach the script herewith. On 4 April 2013 19:10, Sayan Chatterjee wrote: > Dear All, > > I know this error occurs when one tries to multiply a string with a > fraction i.e float. In my case , I can't figure out how can a numpy > floating point array be a string. Interestingly, the concerned expression > gets printed in the loop for the first time but on the second go it fails. > > The concerned snippet of code is given below : > > for t in t_range(0,1,0.1): > print t > p_za=[] > pv_za=[] > > # Opening file in file_t format > fname = 'file_' + str(t) + '.dat' > fo = open(fname,'w') > > # p_za.append(p_initial - t*K*np.sin(K*p_initial)) > print 'K=',K > print 'pv_za_temp =',pv_za_temp > print '- t*K*np.sin(K*p_initial) = ',- t*K*np.sin(K*p_initial) > print '-K*np.sin(K*pv_za_temp) = ',-K*np.sin(K*pv_za_temp) > pv_za.append(-K*np.sin(K*pv_za_temp)) > pv_za_temp = [] > pv_za_temp.append(np.array(pv_za)) > > > Here is paste the output,which clearly shows that the concerned > expression i.e -K*np.sin(K*pv_za_temp) prints perfectly for the first > looping. Also see the error that comes on the second looping. I'm clueless. > > 0 > K= 3.14159265359 > pv_za_temp = [ 0. 0.5 1. 1.5 2. ] > - t*K*np.sin(K*p_initial) = [ 0. 0. -0. -0. 0.] > *-K*np.sin(K*pv_za_temp) = [ -0.00000000e+00 -3.14159265e+00 > 6.49753967e-13 3.14159265e+00* > * -1.29950793e-12] PRINTS PERFECTLY* > * > * > 0.1 > K= 3.14159265359 > pv_za_temp = [array([[ -0.00000000e+00, -3.14159265e+00, 6.49753967e-13, > 3.14159265e+00, -1.29950793e-12]])] > - t*K*np.sin(K*p_initial) = [ -0.00000000e+00 -3.14159265e-01 > 6.49753967e-14 3.14159265e-01 > -1.29950793e-13] > -K*np.sin(K*pv_za_temp) = *ERROR* > Traceback (most recent call last): > File "ZA.py", line 45, in > print '-K*np.sin(K*pv_za_temp) = ',-K*np.sin(K*pv_za_temp) > *TypeError: can't multiply sequence by non-int of type 'float'* > > Please Help!!!! > > > Cheers, > 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 > -- -------------------------------------------------------------------------- *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: 2068 bytes Desc: not available URL: From talk-noreply at google.com Thu Apr 4 15:54:27 2013 From: talk-noreply at google.com (Google Talk) Date: Thu, 4 Apr 2013 06:54:27 -0700 Subject: [Tutor] Invitation to use Google Talk Message-ID: ----------------------------------------------------------------------- You've been invited by Sayan Chatterjee to use Google Talk. If you already have a Google account, log in to Gmail and accept this chat invitation: http://mail.google.com/mail/b-8dcd51705-090ef095ef-tIz_r28PffY3z4wTZmz--hUlRBY To sign up for a Google account and get started with Google Talk, you can visit: http://mail.google.com/mail/a-8dcd51705-090ef095ef-tIz_r28PffY3z4wTZmz--hUlRBY?pc=en_gb-rf---a Learn more at: http://www.google.com/intl/en/landing/accounts/ Thanks, The Google Team From bodsda at googlemail.com Thu Apr 4 16:04:46 2013 From: bodsda at googlemail.com (Bod Soutar) Date: Thu, 4 Apr 2013 15:04:46 +0100 Subject: [Tutor] Help required In-Reply-To: References: Message-ID: On 20 March 2013 06:12, Arijit Ukil wrote: > 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 > A few questions to ask yourself. Is 'f' a descriptive name, equivalent to your other variable names? What does your third line do, and do you think it's actually required? What implications would it cause if you removed it? How do you overcome those issues? What value is stored in 'timest' the first iteration of the loop, the second, the third? (Put a print statement in the loop to find out) Are you actually doing anything with 'energy'? Do you need to wait until after the loop to close your file? HTH, Bodsda From oscar.j.benjamin at gmail.com Thu Apr 4 16:30:26 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 4 Apr 2013 15:30:26 +0100 Subject: [Tutor] TypeError: can't multiply sequence by non-int of type 'float' In-Reply-To: References: Message-ID: On 4 April 2013 14:40, Sayan Chatterjee wrote: > Dear All, > > I know this error occurs when one tries to multiply a string with a fraction > i.e float. In my case , I can't figure out how can a numpy floating point > array be a string. Interestingly, the concerned expression gets printed in > the loop for the first time but on the second go it fails. > > The concerned snippet of code is given below : > > for t in t_range(0,1,0.1): > print t > p_za=[] > pv_za=[] > > # Opening file in file_t format > fname = 'file_' + str(t) + '.dat' > fo = open(fname,'w') > > # p_za.append(p_initial - t*K*np.sin(K*p_initial)) > print 'K=',K K is somewhere above set to a float with the value 3.14... > print 'pv_za_temp =',pv_za_temp pv_za_temp is somewhere above set to a list containing an array as it's only element. > print '- t*K*np.sin(K*p_initial) = ',- t*K*np.sin(K*p_initial) > print '-K*np.sin(K*pv_za_temp) = ',-K*np.sin(K*pv_za_temp) Here you try to multiply the two. The error can be achieved like so: >>> import numpy >>> a = numpy.array([[1, 2], [3, 4]]) >>> a array([[1, 2], [3, 4]]) >>> 3.14 * a array([[ 3.14, 6.28], [ 9.42, 12.56]]) >>> 3.14 * [a] Perhaps what you want is to multiply K with pv_za_temp[0]? [SNIP] > K= 3.14159265359 > pv_za_temp = [array([[ -0.00000000e+00, -3.14159265e+00, 6.49753967e-13, > 3.14159265e+00, -1.29950793e-12]])] Oscar From andipersti at gmail.com Thu Apr 4 16:42:39 2013 From: andipersti at gmail.com (Andreas Perstinger) Date: Thu, 4 Apr 2013 16:42:39 +0200 Subject: [Tutor] TypeError: can't multiply sequence by non-int of type 'float' In-Reply-To: References: Message-ID: <20130404164239.fe2fdc5db4da7503ff9a1de8@gmail.com> Sayan Chatterjee wrote: >I know this error occurs when one tries to multiply a string with a >fraction i.e float. In my case , I can't figure out how can a numpy >floating point array be a string. The problem is not that the numpy array is a string but that you append the array to a python list: > pv_za=[] > pv_za.append(-K*np.sin(K*pv_za_temp)) > pv_za_temp = [] > pv_za_temp.append(np.array(pv_za)) Both "pv_za" and "pv_za_temp" are python lists to which you append a numpy array. But since you delete both lists in each iteration I assume you want to just assign a new numpy array to both names: pv_za = -K * np.sin(K * pv_za_temp) pv_za_temp = pv_za # "pv_za" is already a numpy array Bye, Andreas From davea at davea.name Thu Apr 4 16:55:38 2013 From: davea at davea.name (Dave Angel) Date: Thu, 04 Apr 2013 10:55:38 -0400 Subject: [Tutor] The game of nim in python In-Reply-To: References: Message-ID: <515D946A.90705@davea.name> On 03/27/2013 08:30 AM, Yasin El Guennouni wrote: > > 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. > In my opinion, you'd have to modify so much that you'd probably be better off starting from scratch. -- DaveA From breamoreboy at yahoo.co.uk Thu Apr 4 18:00:47 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 04 Apr 2013 17:00:47 +0100 Subject: [Tutor] Help required In-Reply-To: References: Message-ID: First up please give a sensible subject, say "problem parsing csv file". I'm assuming the crud shown below is due to you posting in html, please use plain text instead. On 20/03/2013 06:12, Arijit Ukil wrote: > 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+"/) You might like to use the with statement as it saves the explicit close later. Do you really need update mode? I'll assume not. with open('digi.txt', 'r') as f: > > datafile = f.readlines() datafile is a poor name, it's the contents of the file here not the file itself. > > list_of_lists = datafile This gives another name for datafile which you only use in the for loop, you can use datafile directly. > fordata inlist_of_lists: > lstval = data.split (/','/) The csv module from the standard library can look after this for you. > timest = float(lstval[0]) > energy = float(lstval[1]) You do nothing with timest and energy within the for loop. > > f.close() > printtimest You're printing the last value for timest here. So you need something like the following, I'll leave you to look up the csv module if you're interested. with open('digi.txt', 'r') as f: lines = f.readlines() timestamps = [] energies = [] for line in lines: splits = line.split(',') # I'll admit not the best name timestamps.append(float(splits[0])) energies.append(float(splits[1])) # process timestamps and energies to your heart's content > > Regards, > Arijit Ukil -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From doark at mail.com Thu Apr 4 19:01:45 2013 From: doark at mail.com (frank ernest) Date: Thu, 04 Apr 2013 13:01:45 -0400 Subject: [Tutor] Proper uses of classes Message-ID: <20130404170145.327670@gmx.com> Sorry about the indentation guys my mail service atomatically removed it when I pasted the text (I tried to fix it by hand but it was hard to tell if I was sucessful.) I was tring to create a list object (self) and change it using the list methods and some additional ones I will define in my class. I wanted to create some varibles which I pass to most if not all of my methods. Two of my variables are to be passed to the class apon creation of the object and then they in turn are to be passed to all or most of the methods I create (a, b in this case.) If I make a, b nonlocal I get the message that they are already nonlocal. I will need for debuging purposes to print my object in random places in my class. If I did this: > self.a = aWhat would that create (I'm thinking local variable?)? class alist(): def __init__(self, b, a): self.mylist = list() self.mylist.append(b) self.a = a + b def appendit(self): #I need to get a in hear without passing #it in; it must come from the init method. self.mylist.append(self.a) #(I hope I've updated the code well, I can't test it from this computer.)PS: This is not the real code that I'm Emailing: I thought I'd be better off with some simpler code that produces the same errors. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kushal.kumaran+python at gmail.com Thu Apr 4 19:11:14 2013 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Thu, 04 Apr 2013 22:41:14 +0530 Subject: [Tutor] os.system() with imbeded quotes In-Reply-To: References: Message-ID: <515db43e.06dd440a.60f5.0e66@mx.google.com> cevyn e writes: > I get the example os.system('ls -al') no problem. > > i'm trying to create a variable with my command built but needs to include > quotes. > Portion of code is as follows: > someip = '192.168.01.01' > > var1 = 'lynx -dump http://' + someip + > '/cgi-bin/xxxx.log&.submit=+++Go%21+++ > junk' > > print var1 > > os.system(var1) > > > If I print var1 it looks right . If I use the os.system(var1) as above it > seems to have a problem near the end of the string with msg > sh: .submit=+++Go%21+++: command not found > > clearly there is some escape sequence that I don't understand . > > I tried combinations of single and double quotes and mixed around var1, but > that generates command not found. > > I need it to look like how I enter it manually and works > lynx -dump 'http://192.168.01.01/cgi-bin/xxxx.log&.submit=+++Go%21+++ > > junk' > > Probably obvious to many but i'm spinning my wheels. many thanks for help . There's a pipes.quote function (in python2, available as shlex.quote in python3.3) that you can use in these circumstances. Your problem is because os.system passes the command to a shell, and the '&' character in your argument terminates the command line. Here's a transcript that shows the use of pipes.quote: In [1]: import os In [2]: os.system('echo a&b') sh: 1: b: not found a Out[2]: 32512 In [5]: os.system('echo %s' % (pipes.quote('a&b'),)) a&b Out[5]: 0 You should be able to get the effect you want by doing this: cmd = 'lynx -dump %s > junk' % (pipes.quote(url),) That said, you should take a look at the subprocess module. The functions in that module can invoke commands without invoking a shell, which avoids such problems. Untested example: with open('junk', 'wb') as output_stream: p = subprocess.Popen(['lynx', '-dump', url], stdout=output_stream) p.communicate() In this case, no quoting of the "url" argument is required. Finally, you can also look at higher level ways of doing whatever it is you're trying. See the urllib2 standard module (assuming python2 because of your print statement), or the requests module (http://docs.python-requests.org/en/v1.1.0/) which provide facilities to access different kinds of urls with varying degrees of automation. -- regards, kushal From bessenkphilip at gmail.com Thu Apr 4 23:51:09 2013 From: bessenkphilip at gmail.com (bessenkphilip) Date: Fri, 05 Apr 2013 03:21:09 +0530 Subject: [Tutor] Doubt in for loop In-Reply-To: <515CEB1B.30004@davea.name> References: <515CD75E.3030306@gmail.com> <515CDD25.8050208@pearwood.info> <515CEB1B.30004@davea.name> Message-ID: <515DF5CD.9020209@gmail.com> On 04/04/2013 08:23 AM, Dave Angel wrote: > On 04/03/2013 09:53 PM, Steven D'Aprano wrote: >> On 04/04/13 12:29, bessenkphilip wrote: >>> Hi all, >>> >>> I'm having a doubt in the below program's 2n'd "for" loop. >>> >>>>>> for n in range(2, 10): >>> ... for x in range(2, n): >>> ... if n % x == 0: >>> ... print n, 'equals', x, '*', n/x >>> ... break >>> ... else: >>> ... # loop fell through without finding a factor >>> ... print n, 'is a prime number' >>> ... >>> 2 is a prime number >>> 3 is a prime number >>> 4 equals 2 * 2 >>> 5 is a prime number >>> 6 equals 2 * 3 >>> 7 is a prime number >>> 8 equals 2 * 4 >>> 9 equals 3 * 3 >>> >>> My doubt is that "will 'x' be always of value 2, if so why that for >>> loop "for x in range(2, n):" >>> i don't know how the first output , as If 2%2==0:(this satisfies the >>> if loop as x =2) , so how the else part came to output i.e 2 is a >>> prime number. >> >> I'm sorry, I don't understand your question. >> >> x is *not* always of value 2. You can see with the last line, >> >> 9 equals 3 * 3 >> >> x has value 3. >> >> >> The outer loop just checks 2, 3, 4, ... 9 to see whether they are prime. >> The inner loop actually does the checking: >> >> >> for x in range(2, n): >> if n % x == 0: >> print n, 'equals', x, '*', n/x >> break >> >> >> This tests whether n is divisible by 2, 3, 4, 5, 6, ... up to n-1. If n >> is divisible by any of those numbers, then n cannot be prime. >> >> For example, with n = 9, the inner loop does this: >> >> x = 2 >> Test if 2 is a factor: does 9/2 have remainder zero? No. >> x = 3 >> Test if 3 is a factor: does 9/3 have remainder zero? Yes. >> So 9 is not prime, and 9 = 3 * (9/3) = 3 * 3 >> >> >> If we test it with n = 35, the inner loop would do this: >> >> x = 2 >> Test if 2 is a factor: does 35/2 have remainder zero? No. >> x = 3 >> Test if 3 is a factor: does 35/3 have remainder zero? No. >> x = 4 >> Test if 4 is a factor: does 35/4 have remainder zero? No. >> x = 5 >> Test if 5 is a factor: does 35/5 have remainder zero? Yes. >> So 35 is not prime, and 35 = 5 * (35/5) = 5 * 7 >> >> >> >> Notice that this does more work than necessary! Can you see what work it >> does that is unnecessary? >> >> (Hint: what even numbers are prime?) >> >> >> >> > > I don't understand the questions either, but I can point out one thing > that might be puzzling the OP: > > When n is 2, the inner loop does nothing, it just skips to the else > clause. The reason is that range(2,2) is a null iterator. range(i,j) > produces values from i to j-1, or to put it another way values for which > i <= n < j > > If i and j are identical, there's nothing to match it. > > Thank you very much Steven for explaining this. Yes,Dave, i was having doubt how n=2 came to else part, cleared that too, thank you . From breamoreboy at yahoo.co.uk Fri Apr 5 10:48:37 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 05 Apr 2013 09:48:37 +0100 Subject: [Tutor] Proper uses of classes In-Reply-To: <20130404170145.327670@gmx.com> References: <20130404170145.327670@gmx.com> Message-ID: On 04/04/2013 18:01, frank ernest wrote: > Sorry about the indentation guys my mail service atomatically removed it > when I pasted the text (I tried to fix it by hand but it was hard to > tell if I was sucessful.) > I was tring to create a list object (self) and change it using the list > methods and some additional ones I will define in my class. > I wanted to create some varibles which I pass to most if not all of my > methods. Two of my variables are to be passed to the class apon creation > of the object and then they in turn are to be passed to all or most of > the methods I create (a, b in this case.) If I make a, b nonlocal I get > the message that they are already nonlocal. > I will need for debuging purposes to print my object in random places in > my class. > If I did this: > >> self.a = a > > What would that create (I'm thinking local variable?)? If the line is in a class method you'd create a (using Python speak) name 'a' for every instance of your class. > > class alist(): > def __init__(self, b, a): > self.mylist = list() > self.mylist.append(b) > self.a = a + b > def appendit(self): > > #I need to get a in hear without passing > > #it in; it must come from the init method. > self.mylist.append(self.a) > > #(I hope I've updated the code well, I can't test it from this computer.) > > PS: This is not the real code that I'm Emailing: I thought I'd be better off with some simpler code that produces the same errors. > As I see it all you gain from the appendit method is the ability to delay adding 'a' to mylist until you've done some other processing. Is this what you're trying to achieve, if not can you give us more detail? That way we can help you code up your requirements. -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From davea at davea.name Fri Apr 5 11:42:46 2013 From: davea at davea.name (Dave Angel) Date: Fri, 05 Apr 2013 05:42:46 -0400 Subject: [Tutor] Proper uses of classes In-Reply-To: <20130404170145.327670@gmx.com> References: <20130404170145.327670@gmx.com> Message-ID: <515E9C96.4040308@davea.name> On 04/04/2013 01:01 PM, frank ernest wrote: > Sorry about the indentation guys my mail service atomatically removed it when I pasted the text (I tried to fix it by hand but it was hard to tell if I was sucessful.) > I was tring to create a list object (self) and change it using the list methods and some additional ones I will define in my class. > I wanted to create some varibles which I pass to most if not all of my methods. Two of my variables are to be passed to the class apon creation of the object and then they in turn are to be passed to all or most of the methods I create (a, b in this case.) If I make a, b nonlocal I get the message that they are already nonlocal. > I will need for debuging purposes to print my object in random places in my class. > If I did this: >> self.a = aWhat would that create (I'm thinking local variable?)? No. a is a local variable, since it was passed as an argument. self.a is an attribute of the alist instance. > > class alist(): def __init__(self, b, a): self.mylist = list() self.mylist.append(b) self.a = a + b def appendit(self): #I need to get a in hear without passing #it in; it must come from the init method. self.mylist.append(self.a) #(I hope I've updated the code well, I can't test it from this computer.)PS: This is not the real code that I'm Emailing: I thought I'd be better off with some simpler code that produces the same errors. > > Your mail service is just broken, at least for use here. This is a text forum, and your mail has an empty text body. So each of our mail readers has to try to reconstruct the text from html nonsense. You can see the result above of what Thunderbird does. The following is what I think you posted. class alist(): def __init__(self, b, a): self.mylist = list() self.mylist.append(b) self.a = a + b def appendit(self): #I need to get a in hear without passing #it in; it must come from the init method. self.mylist.append(self.a) #(I hope I've updated the code well, I can't test it from this computer.) There are lots of terminology problems which will stop you from understanding what's going on. "I wanted to create some varibles which I pass to most if not all of my methods" "Variables" passed to methods are called arguments, or parameters, and that's NOT what you're trying to do. You're trying to have the __init__() method "remember" those values. When you write "self.a =" you are creating an "instance attribute" which is visible to all methods on that instance. Other methods can access that instance attribute by referring to it as self.a Not by "global" not by "nonlocal". Those are very different. A local variable is also different, as is a class attribute. You need to study up on each of these terms, and see what the differences are in terms of lifetime, visibility, duplication, etc. More on that later. Now, the appendit() method is nonsensical, but perhaps it was just a sample. Each time it's called, it'll append the same value a to the list. Perhaps you'd be more comfortable if you wrote a __str__() method. That way, when you try to print an instance, it'll do what you say, rather than some default. Typically, it should do something with each attribute that was initialized by __init__(). (untested) def __str__(self): res = "mylist attribute is" + str(self.mylist) + "\n" res += "a is " + str(a) + "\n" return res Now you can exercise your class, and print out the results as often as you like: (untested) obj1 = alist(3, 47) # creates an instance of alist print(obj1) # prints it obj2 = alist(12, 9) # creates a second instance of alist, with its own self.mylist and self.a, different from those in obj1 print(obj2) obj1.append() #will take the particular list in obj1, and append the saved self.a value print(obj1) obj2.append() obj2.append() print(obj) Now, a brief, informal summary of all the different kinds of "variables." A global variable is defined at the outer scope of a module, and should mostly be constants, for sound engineering reasons. The global keyword, used only inside a function, declares that a particular variable that looks like it ought to be local, in fact is global. The keyword applies only to that particular function. A local variable is defined and used within a function (or method), and vanishes entirely when the function returns. The formal parameters of the function are locals as well. A class attribute belongs to the class, and there's only one of them, regardless of how many instances that class has. An instance attribute exists separately in each instance of a class. It should (my preference) be initialized in the __init__() method so that every instance has the same attributes, even if it's just self.att = None A nonlocal variable is probably beyond what you need to know at the present, but it's one that's either global, or in some other function. When you say xxxx.yyyy the meaning of that depends entirely on what xxxx is defined as. If xxxx is a class, then yyyy is an attribute of that class. If xxxx is an instance, then yyyy might be an instance attribute (usually) or a class attribute (if no instance attribute by that name). If xxxx is a module, then yyyy is a global in that other module. The name self is a convention, but a very useful one there's no advantage in breaking. Most methods take self as their first argument, and it refers to the object that method is called with. In the specific case of __init__() method, that object is newly created. In nearly all other cases, it's the object specified to the left of the method name, like obj1.appendit() There are a few other tricks that might matter, but this should get you going. Play with all these concepts, and become attuned to it. Only then should you try to do things like inherit from list. -- DaveA From mousumi251 at gmail.com Fri Apr 5 12:47:54 2013 From: mousumi251 at gmail.com (Mousumi Basu) Date: Fri, 5 Apr 2013 16:17:54 +0530 Subject: [Tutor] Socket Programming Message-ID: I want to perform bind function for socket programming between two computers of ip addresses- 172.18.2.11 and 172.18.2.95 using the following command(on the computer having IP address 172.18.2.95): s=socket.socket(socket.AF_INIT,socket.SCK_DGRM)) s.bind(('172.18.2.11',8032)) But error is occurring showing "bind not done" The ping operation of command prompt is showing that the computers are connected. Please help me. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ausnajm at yahoo.com.au Fri Apr 5 14:05:40 2013 From: ausnajm at yahoo.com.au (Najam Us Saqib) Date: Fri, 5 Apr 2013 05:05:40 -0700 (PDT) Subject: [Tutor] basic question Message-ID: <1365163540.19153.YahooMailNeo@web161804.mail.bf1.yahoo.com> Hi, My name is Najam, I am very new to Python Programming. Would you please help me with the following question? The question/problem is, Write a Car salesman program where the user enters the base price of a car. The program should add a bunch of extra fees such as tax, license, dealer prep, and destination charge.Make tax and license a percent of the base price. The other fees should be set values. Display the actual price of the car once all the extras are applied. I am not sure whether I have entered the right code for "Make tax and license a percent of the base price." or not. My program is; price = float(raw_input("Enter the base price of the car $ ")) tax = float(raw_input("Enter the tax $ ")) licence = float(raw_input("Enter the licence fees $ ")) dealer_prep = float(raw_input("Enter the dealer prep fees $ ")) des_charge = float(raw_input("Enter the destination charge $ ")) percent = (tax * 0.01 + licence * 0.01) / price ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? # ????? print "\nA percent of the base price is: $ " , percent total = price + tax + licence + dealer_prep + des_charge print "\nThe actual price of the car is: $ " , total raw_input("\nPress Enter key to Exit, thank you.") Thank you. Najam. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Fri Apr 5 14:22:48 2013 From: davea at davea.name (Dave Angel) Date: Fri, 05 Apr 2013 08:22:48 -0400 Subject: [Tutor] basic question In-Reply-To: <1365163540.19153.YahooMailNeo@web161804.mail.bf1.yahoo.com> References: <1365163540.19153.YahooMailNeo@web161804.mail.bf1.yahoo.com> Message-ID: <515EC218.8080800@davea.name> On 04/05/2013 08:05 AM, Najam Us Saqib wrote: > Hi, > > My name is Najam, I am very new to Python Programming. Welcome. > Would you please help me with the following question? > > The question/problem is, > > Write a Car salesman program where the user enters the base price of a car. The program should add a bunch of extra fees such as tax, license, dealer prep, and destination charge.Make tax and license a percent of the base price. The other fees should be set values. Display the actual price of the car once all the extras are applied. > Is this exactly the way the assignment reads, or did you paraphrase it? > I am not sure whether I have entered the right code for "Make tax and license a percent of the base price." or not. > > My program is; > > price = float(raw_input("Enter the base price of the car $ ")) > > tax = float(raw_input("Enter the tax $ ")) > licence = float(raw_input("Enter the licence fees $ ")) > dealer_prep = float(raw_input("Enter the dealer prep fees $ ")) > des_charge = float(raw_input("Enter the destination charge $ ")) > > percent = (tax * 0.01 + licence * 0.01) / price # ????? > > print "\nA percent of the base price is: $ " , percent > > total = price + tax + licence + dealer_prep + des_charge > > print "\nThe actual price of the car is: $ " , total > > raw_input("\nPress Enter key to Exit, thank you.") > > The way I expect the assignment was intended is that the user should enter (with raw_input) the tax and license as percentages, and you convert them to dollars, rather than the other way around. -- DaveA From woody544 at gmail.com Fri Apr 5 14:34:53 2013 From: woody544 at gmail.com (Woody 544) Date: Fri, 5 Apr 2013 08:34:53 -0400 Subject: [Tutor] basic question In-Reply-To: References: <1365163540.19153.YahooMailNeo@web161804.mail.bf1.yahoo.com> Message-ID: On 4/5/13, Woody 544 wrote: > Dear Najam > > The tax and license amounts should not need to be entered, as I would > think the only variable is the base price, with tax and license > calculated as their rate times the base price. For example, if the > sales tax rate for the area is 6% for example: > > tax = price * 0.06 > > Since the other fees are fixed, there is no need for raw input from > the user on those either and the rates can be hard coded in. If the > tax rate = 6% and the license rate = 1% then: > > total = price + (price*.06) + (price * .01) + dealer_prep + des_charge > > Thus the only input from the user would be to enter the base price. > Of course, if the intent is for more than just one dealership with > varied rates and fees, it may make sense for the other values to be > entered by a user. > > MJ > > On 4/5/13, Najam Us Saqib wrote: >> Hi, >> >> My name is Najam, I am very new to Python Programming. Would you please >> help >> me with the following question? >> >> The question/problem is, >> >> Write a Car salesman program where the user enters the base price of a >> car. >> The program should add a bunch of extra fees such as tax, license, dealer >> prep, and destination charge.Make tax and license a percent of the base >> price. The other fees should be set values. Display the actual price of >> the >> car once all the extras are applied. >> >> I am not sure whether I have entered the right code for "Make tax and >> license a percent of the base price." or not. >> >> My program is; >> >> price = float(raw_input("Enter the base price of the car $ ")) >> >> tax = float(raw_input("Enter the tax $ ")) >> licence = float(raw_input("Enter the licence fees $ ")) >> dealer_prep = float(raw_input("Enter the dealer prep fees $ ")) >> des_charge = float(raw_input("Enter the destination charge $ ")) >> >> percent = (tax * 0.01 + licence * 0.01) / price >> # ????? >> >> print "\nA percent of the base price is: $ " , percent >> >> total = price + tax + licence + dealer_prep + des_charge >> >> print "\nThe actual price of the car is: $ " , total >> >> raw_input("\nPress Enter key to Exit, thank you.") >> >> >> >> Thank you. >> Najam. >> > From steve at pearwood.info Fri Apr 5 15:28:12 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 06 Apr 2013 00:28:12 +1100 Subject: [Tutor] Socket Programming In-Reply-To: References: Message-ID: <515ED16C.6070207@pearwood.info> On 05/04/13 21:47, Mousumi Basu wrote: > I want to perform bind function for socket programming between two > computers of ip addresses- 172.18.2.11 and 172.18.2.95 using the following > command(on the computer having IP address 172.18.2.95): > > s=socket.socket(socket.AF_INIT,socket.SCK_DGRM)) I get THREE errors with that line: * SyntaxError due to an extra closing parenthesis; * after fixing that problem, I get an AttributeError: 'module' object has no attribute 'AF_INIT' * after guessing what you mean instead of AF_INIT, I get another AttributeError: 'module' object has no attribute 'SCK_DGRM' Could you show us the code you are actually using, and save us from having to guess? > s.bind(('172.18.2.11',8032)) > > But error is occurring showing "bind not done" Please copy and paste the complete traceback, starting with the line: Traceback (most recent call last) and going all the way to the end of the error message. -- Steven From cfuller084 at thinkingplanet.net Fri Apr 5 18:29:46 2013 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 5 Apr 2013 11:29:46 -0500 Subject: [Tutor] Socket Programming In-Reply-To: References: Message-ID: <201304051129.47021.cfuller084@thinkingplanet.net> Have you checked out the socket HOWTO? http://docs.python.org/2/howto/sockets.html Cheers On Friday, April 05, 2013, Mousumi Basu wrote: > I want to perform bind function for socket programming between two > computers of ip addresses- 172.18.2.11 and 172.18.2.95 using the following > command(on the computer having IP address 172.18.2.95): > > s=socket.socket(socket.AF_INIT,socket.SCK_DGRM)) > s.bind(('172.18.2.11',8032)) > > But error is occurring showing "bind not done" > > The ping operation of command prompt is showing that the computers are > connected. > > Please help me. From sayanchatterjee at gmail.com Fri Apr 5 21:06:55 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Sat, 6 Apr 2013 00:36:55 +0530 Subject: [Tutor] TypeError: can't multiply sequence by non-int of type 'float' In-Reply-To: <20130404164239.fe2fdc5db4da7503ff9a1de8@gmail.com> References: <20130404164239.fe2fdc5db4da7503ff9a1de8@gmail.com> Message-ID: Thanks all...I realized my mistake!!...:) On 4 April 2013 20:12, Andreas Perstinger wrote: > Sayan Chatterjee wrote: > > >I know this error occurs when one tries to multiply a string with a > >fraction i.e float. In my case , I can't figure out how can a numpy > >floating point array be a string. > > The problem is not that the numpy array is a string but that you append > the array to a python list: > > > pv_za=[] > > pv_za.append(-K*np.sin(K*pv_za_temp)) > > pv_za_temp = [] > > pv_za_temp.append(np.array(pv_za)) > > Both "pv_za" and "pv_za_temp" are python lists to which you append a > numpy array. But since you delete both lists in each iteration I assume > you want to just assign a new numpy array to both names: > > pv_za = -K * np.sin(K * pv_za_temp) > pv_za_temp = pv_za # "pv_za" is already a numpy array > > Bye, Andreas > _______________________________________________ > 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 alan.gauld at btinternet.com Sat Apr 6 20:22:28 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 06 Apr 2013 19:22:28 +0100 Subject: [Tutor] Socket Programming In-Reply-To: References: Message-ID: On 05/04/13 11:47, Mousumi Basu wrote: > > s=socket.socket(socket.AF_INIT,socket.SCK_DGRM)) There is a double )) at the end of the line. That should give a different error so I assume this is not cut 'n paste code, but just in case I thought I'd point it out... > s.bind(('172.18.2.11',8032)) Because I can't see anything wrong here. > But error is occurring showing "bind not done" Can you send the full error text via cut 'n paste please? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ysoliman at uncc.edu Sun Apr 7 00:00:01 2013 From: ysoliman at uncc.edu (Soliman, Yasmin) Date: Sat, 6 Apr 2013 22:00:01 +0000 Subject: [Tutor] loop questions Message-ID: <211A029E048A2245A6E00BA02FEFF88A673AFF4B@BL2PRD0310MB373.namprd03.prod.outlook.com> I have two questions on these simple programs: 1st why does this loop keep repeating after I enter 'Quit'? import calendar m = raw_input(?Enter a year: ?) while m != ?Quit?: if calendar.isleap(int(m)): print ?%d is a leap year? % (int(m)) else: print ?%d is not a leap year? % (int(m)) 2nd How can I make this program not crash when a user enters a non integer? m = raw_input(?Enter an integer: ?) while not m.isdigit(): m = raw_input(?Enter an integer: ?) num = int(m) From msirenef at lightbird.net Sun Apr 7 00:23:05 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Sat, 06 Apr 2013 18:23:05 -0400 Subject: [Tutor] loop questions In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A673AFF4B@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A673AFF4B@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: <5160A049.5040205@lightbird.net> On 04/06/2013 06:00 PM, Soliman, Yasmin wrote: > I have two questions on these simple programs: > > 1st why does this loop keep repeating after I enter 'Quit'? > > import calendar > m = raw_input(?Enter a year: ?) > while m != ?Quit?: > if calendar.isleap(int(m)): > print ?%d is a leap year? % (int(m)) > else: > print ?%d is not a leap year? % (int(m)) > > > 2nd How can I make this program not crash when a user enters a non integer? > > m = raw_input(?Enter an integer: ?) > while not m.isdigit(): > m = raw_input(?Enter an integer: ?) > num = int(m) > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > In pseudocode, you need to do something like this: - loop forever inp = user input if inp is Quit: break try to convert inp to int if success: print if inp is leap year or not else: print error I have written a small function that handles a more general case of asking user for a certain kind of input (e.g. number, text, yes/no, etc) and keeps asking it until the answer in right format is given. Here it is: 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) # 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/ True friends stab you in the front. Oscar Wilde From breamoreboy at yahoo.co.uk Sun Apr 7 00:40:11 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 06 Apr 2013 23:40:11 +0100 Subject: [Tutor] loop questions In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A673AFF4B@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A673AFF4B@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: On 06/04/2013 23:00, Soliman, Yasmin wrote: > I have two questions on these simple programs: > > 1st why does this loop keep repeating after I enter 'Quit'? > > import calendar > m = raw_input(?Enter a year: ?) > while m != ?Quit?: > if calendar.isleap(int(m)): > print ?%d is a leap year? % (int(m)) > else: > print ?%d is not a leap year? % (int(m)) > Already answered by Mitya Sirenef. > > 2nd How can I make this program not crash when a user enters a non integer? The program doesn't crash, it raises an exception. > > m = raw_input(?Enter an integer: ?) > while not m.isdigit(): > m = raw_input(?Enter an integer: ?) > num = int(m) try: num = int(m) except ValueError: doSomething I'll leave you to restructure the loop. -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From ysoliman at uncc.edu Sun Apr 7 01:10:29 2013 From: ysoliman at uncc.edu (Soliman, Yasmin) Date: Sat, 6 Apr 2013 23:10:29 +0000 Subject: [Tutor] (no subject) Message-ID: <211A029E048A2245A6E00BA02FEFF88A673AFF67@BL2PRD0310MB373.namprd03.prod.outlook.com> How can I fix this loop so that it multiplies the two intergers and if user types in 'quit' for either number it stops? if not it keeps going. def multiply_integers(int1,int2): print int1*int2 int1=float(input('Please enter 1st integer: ')) int2=float(input('Please enter 2nd integer: ')) while True: multiply_integers= int("int1, int2") print int1*int2 if multiply_integers == 'Quit': print '\nThank you for using this program! Bye.' break else: print 'Not quitting' -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Apr 7 01:49:52 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 07 Apr 2013 09:49:52 +1000 Subject: [Tutor] loop questions In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A673AFF4B@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A673AFF4B@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: <5160B4A0.2060809@pearwood.info> On 07/04/13 08:00, Soliman, Yasmin wrote: > I have two questions on these simple programs: > > 1st why does this loop keep repeating after I enter 'Quit'? The code you give below is not valid Python code. Please copy and paste *actual* the code you use, do not retype it from memory. I know that it is not valid code because it uses fancy quotes ? ? which do not work in Python, instead of ordinary quotes (actually inch marks) " " > import calendar > m = raw_input(?Enter a year: ?) > while m != ?Quit?: > if calendar.isleap(int(m)): > print ?%d is a leap year? % (int(m)) > else: > print ?%d is not a leap year? % (int(m)) Fixing the above error, it is *not correct* that the loop repeats after entering "Quit". If you enter Quit, the loop will not run at all, not even once. If you enter something else, *anything* else include "quit" or "QUIT" or "Quit " (notice the space at the end), then it will loop forever. The problem is that your code only asks for a year *once*. The raw_input is outside of the loop, so it only happens once. To get the opportunity to enter a year, or quit, more than once, it needs to be inside the loop. Also, you should be more forgiving of user input. Instead of checking whether the user enters exactly CAPITAL Q lower u i t you should accept anything that looks like "quit". Use m.strip() to remove any accidental spaces at the beginning or end of the word, and m.lower() to convert to lowercase, then compare against "quit". (remember that strings are *immutable*, and re-assign the result of the method calls to m) > 2nd How can I make this program not crash when a user enters a non integer? > > m = raw_input(?Enter an integer: ?) > while not m.isdigit(): > m = raw_input(?Enter an integer: ?) > num = int(m) There are two ways. You can either catch the exception that happens, or avoid calling int. Here's the first way: # This will work with negative numbers too. response = raw_input("Enter an integer: ") try: num = int(response) except ValueError: print "%r is not an integer, please try again" % response Here's the second way: # This will not work with negative numbers. response = raw_input("Enter an integer: ") response = response.strip() # get rid of any leading or trailing spaces if response.isdigit(): num = int(response) else: print "%r is not an integer, please try again" % response If you want these to repeat multiple times, you need to put them inside a loop. -- Steven From steve at pearwood.info Sun Apr 7 02:02:44 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 07 Apr 2013 10:02:44 +1000 Subject: [Tutor] (no subject) In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A673AFF67@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A673AFF67@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: <5160B7A4.2060406@pearwood.info> On 07/04/13 09:10, Soliman, Yasmin wrote: > How can I fix this loop so that it multiplies the two intergers and if user types in 'quit' for either number it stops? if not it keeps going. How would you solve this problem in real life? Right down the steps you would do, as if you were explaining it to a child, or an idiot. Remember that computers are dumber than any child, so make the steps as simple as you can. * Ask the user for a value * if the first value is "Quit", then stop * Ask the user for a second value * If the second value is "Quit", then stop * Convert the first value to an int (instead of a string) * Convert the second value to an int (instead of a string) * Multiply the two ints Now put that into Python code. Get it working. If you have *specific* questions, please ask, but this question is so broad and general that you're basically asking us to do everything. Once it works, then put it inside a loop. The secret to programming is to break tasks up into smaller tasks, smaller and simpler, until they are so small and simple that even a computer can do them. Then put the pieces together, in the right order. P.S. Please use a sensible subject line. -- Steven From breamoreboy at yahoo.co.uk Sun Apr 7 02:57:23 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 07 Apr 2013 01:57:23 +0100 Subject: [Tutor] (no subject) In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A673AFF67@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A673AFF67@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: On 07/04/2013 00:10, Soliman, Yasmin wrote: To quote John McEnroe "You cannot be serious". Thankfully Steven D'Aprano has already given you a roadmap to follow. I'll point out a few things that should assist. > How can I fix this loop so that it multiplies the two intergers and if > user types in 'quit' for either number it stops? if not it keeps going. > > def multiply_integers(int1,int2): > print int1*int2 multiply_integers will return None, the Python default. > > int1=float(input('Please enter 1st integer: ')) > int2=float(input('Please enter 2nd integer: ')) Are you trying to get integers from the input by calling float? Or could that be interest? Or what? The print statement later on tells me you're using Python 2.x. Therefore you should be using raw_input above and *NOT* input, the latter is highly dangerous. > > > while True: > multiply_integers= int("int1, int2") Having defined a function you now try to reassign its name, obviously not what you want. But that won't work as the call to int will fail as you're passing a single string "int1, int2" to it. > print int1*int2 Why print this here when your function multiply_integers already does exactly that? > > if multiply_integers == 'Quit': You now try to compare your function to a string. Or should multiply_integers be an int here? > print '\nThank you for using this program! Bye.' > break > else: > print 'Not quitting' > -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From ausnajm at yahoo.com.au Sun Apr 7 05:23:57 2013 From: ausnajm at yahoo.com.au (Najam Us Saqib) Date: Sat, 6 Apr 2013 20:23:57 -0700 (PDT) Subject: [Tutor] While loop Message-ID: <1365305037.70564.YahooMailNeo@web161805.mail.bf1.yahoo.com> Hi, Would you please help me by explaining that why " 5 " is skipped and not printed in the following program? Thank you. Najam. count = 0 while True: ? ? count += 1 ? ? # end loop if count is greater than 10 ? ? if count > 10: ? ? ? ? break # means "break out of the loop" ? ? # skip 5 ? ? if count == 5: ? ? ? ? continue # means "Jump back to the top of the looop" ? ? print count raw_input("\n\nPress the enter key to exit.") Output: 1 2 3 4 6 7 8 9 10 Press the enter key to exit. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Sun Apr 7 06:09:42 2013 From: davea at davea.name (Dave Angel) Date: Sun, 07 Apr 2013 00:09:42 -0400 Subject: [Tutor] While loop In-Reply-To: <1365305037.70564.YahooMailNeo@web161805.mail.bf1.yahoo.com> References: <1365305037.70564.YahooMailNeo@web161805.mail.bf1.yahoo.com> Message-ID: <5160F186.5070701@davea.name> On 04/06/2013 11:23 PM, Najam Us Saqib wrote: > Hi, > > Would you please help me by explaining that why " 5 " is skipped and not printed in the following program? > Seems to me the comments say it pretty well. The continue statement causes execution to continue at the while statement, which has the effect of skipping the print. Like Monopoly: go directly to jail, do not pass go. > Thank you. > Najam. > > count = 0 > while True: > count += 1 > # end loop if count is greater than 10 > if count > 10: > break # means "break out of the loop" > # skip 5 > if count == 5: > continue # means "Jump back to the top of the looop" > print count > > raw_input("\n\nPress the enter key to exit.") > > Output: > > 1 > 2 > 3 > 4 > 6 > 7 > 8 > 9 > 10 > > > Press the enter key to exit. Incidentally, this looks like a transliteration of something written for some other language. An experienced Python programmer would never write it this way. I'd use something like (untested): for count in xrange(11): if count != 5: print count On the other hand, a course --teaching a C programmer to use Python-- might well use this as an early example, showing you later how much elegantly it can be done. -- DaveA From davea at davea.name Sun Apr 7 06:10:09 2013 From: davea at davea.name (Dave Angel) Date: Sun, 07 Apr 2013 00:10:09 -0400 Subject: [Tutor] While loop In-Reply-To: <1365305037.70564.YahooMailNeo@web161805.mail.bf1.yahoo.com> References: <1365305037.70564.YahooMailNeo@web161805.mail.bf1.yahoo.com> Message-ID: <5160F1A1.9060702@davea.name> On 04/06/2013 11:23 PM, Najam Us Saqib wrote: > Hi, > > Would you please help me by explaining that why " 5 " is skipped and not printed in the following program? > Seems to me the comments say it pretty well. The continue statement causes execution to continue at the while statement, which has the effect of skipping the print. Like Monopoly: go directly to jail, do not pass go. > Thank you. > Najam. > > count = 0 > while True: > count += 1 > # end loop if count is greater than 10 > if count > 10: > break # means "break out of the loop" > # skip 5 > if count == 5: > continue # means "Jump back to the top of the looop" > print count > > raw_input("\n\nPress the enter key to exit.") > > Output: > > 1 > 2 > 3 > 4 > 6 > 7 > 8 > 9 > 10 > > > Press the enter key to exit. Incidentally, this looks like a transliteration of something written for some other language. An experienced Python programmer would never write it this way. I'd use something like (untested): for count in xrange(11): if count != 5: print count On the other hand, a course --teaching a C programmer to use Python-- might well use this as an early example, showing you later how much elegantly it can be done. -- DaveA From sayanchatterjee at gmail.com Sun Apr 7 07:12:35 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Sun, 7 Apr 2013 10:42:35 +0530 Subject: [Tutor] While loop In-Reply-To: <5160F1A1.9060702@davea.name> References: <1365305037.70564.YahooMailNeo@web161805.mail.bf1.yahoo.com> <5160F1A1.9060702@davea.name> Message-ID: # skip 5 if count == 5: continue # means "Jump back to the top of the looop" It is the reason. You yourself have mentioned it right inside the code! On 7 April 2013 09:40, Dave Angel wrote: > On 04/06/2013 11:23 PM, Najam Us Saqib wrote: > >> Hi, >> >> Would you please help me by explaining that why " 5 " is skipped and not >> printed in the following program? >> >> > Seems to me the comments say it pretty well. The continue statement > causes execution to continue at the while statement, which has the effect > of skipping the print. Like Monopoly: go directly to jail, do not pass go. > > > Thank you. >> Najam. >> >> count = 0 >> while True: >> count += 1 >> # end loop if count is greater than 10 >> if count > 10: >> break # means "break out of the loop" >> # skip 5 >> if count == 5: >> continue # means "Jump back to the top of the looop" >> print count >> >> raw_input("\n\nPress the enter key to exit.") >> >> Output: >> >> 1 >> 2 >> 3 >> 4 >> 6 >> 7 >> 8 >> 9 >> 10 >> >> >> Press the enter key to exit. >> > > Incidentally, this looks like a transliteration of something written for > some other language. An experienced Python programmer would never write it > this way. > > I'd use something like (untested): > > for count in xrange(11): > if count != 5: > print count > > On the other hand, a course --teaching a C programmer to use Python-- > might well use this as an early example, showing you later how much > elegantly it can be done. > > > -- > DaveA > ______________________________**_________________ > 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 alan.gauld at btinternet.com Sun Apr 7 10:24:10 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 07 Apr 2013 09:24:10 +0100 Subject: [Tutor] loop questions In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A673AFF4B@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A673AFF4B@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: On 06/04/13 23:00, Soliman, Yasmin wrote: > I have two questions on these simple programs: > > 1st why does this loop keep repeating after I enter 'Quit'? > > import calendar > m = raw_input(?Enter a year: ?) > while m != ?Quit?: > if calendar.isleap(int(m)): > print ?%d is a leap year? % (int(m)) > else: > print ?%d is not a leap year? % (int(m)) > I don't understand why it even starts repeating since the only user input is before the loop. However you need to enter exactly "Quit" and not QUIT or quit or any other combination... It usually better to force the user input to upper or lower case, eg: while m.lower() != "quit": > 2nd How can I make this program not crash when a user enters a non integer? > > m = raw_input(?Enter an integer: ?) > while not m.isdigit(): > m = raw_input(?Enter an integer: ?) > num = int(m) Moving the last line out of the loop will help. But there are other things to check in addition to isdigit(). That's why Python tends towards exception handling rather than pre-validation. eg. while True: try: m = int(raw_input(....)) except ValueError,TypeError: continue HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From chigga101 at gmail.com Sun Apr 7 17:07:52 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sun, 7 Apr 2013 16:07:52 +0100 Subject: [Tutor] urllib.urlretrieve ? Message-ID: Im following a tutorial on what i believe is using Python 2 and i'm a bit confused. I use Python 3 on windows vista. I believe urlretrieve() is a python 2 function that isnt in 3, but why is the tutorial using urllib instead of urllib2? Also when i run the program on Python 3, it says: AttributeError: 'module' object has no attribute 'urlretrieve' so Python 3 doesnt recognize this function, i want to ask if there is an equivalent function to 'urlretrieve' in Python 3? the program uses this function to download a file as so: urllib.urlretrieve(self._url, self._filename, reporthook) the 3rd argument is a function that is called to track progress of the current download status. i dont really need help with the program, i understand its code, but i need to know if this function has one similar in Python 3? or do you have any examples of how i could add its functionality to Python 3. From eryksun at gmail.com Sun Apr 7 17:16:22 2013 From: eryksun at gmail.com (eryksun) Date: Sun, 7 Apr 2013 11:16:22 -0400 Subject: [Tutor] urllib.urlretrieve ? In-Reply-To: References: Message-ID: On Sun, Apr 7, 2013 at 11:07 AM, Matthew Ngaha wrote: > so Python 3 doesnt recognize this function, i want to ask if there is > an equivalent function to 'urlretrieve' in Python 3? The documentation is indexed: http://docs.python.org/3/genindex-U.html From alan.gauld at btinternet.com Sun Apr 7 17:31:14 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 07 Apr 2013 16:31:14 +0100 Subject: [Tutor] urllib.urlretrieve ? In-Reply-To: References: Message-ID: On 07/04/13 16:07, Matthew Ngaha wrote: > an equivalent function to 'urlretrieve' in Python 3? the program uses > this function to download a file as so: > > urllib.urlretrieve(self._url, self._filename, reporthook) > Looking in the V3 documents on the Python web site it says: ============== The following functions and classes are ported from the Python 2 module urllib (as opposed to urllib2). They might become deprecated at some point in the future. urllib.request.urlretrieve(url, filename=None, reporthook=None, data=None) Copy a network object denoted by a URL to a local file... =============== Look in the module docs for urlib.request. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From chigga101 at gmail.com Sun Apr 7 17:32:04 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sun, 7 Apr 2013 16:32:04 +0100 Subject: [Tutor] urllib.urlretrieve ? In-Reply-To: References: Message-ID: the whole program depends on the urlretrieve 3rd argument, the function to be called.. is there no options to include a callback? def _download(self): def reporthook(pos, block, total): if self.size != total: self._size = total self.on_size.emit() self.progress = float(pos*block)/float(total) urllib.urlretrieve(self._url, self._filename, reporthook) ##3rd arg calls inner function self.running = False From chigga101 at gmail.com Sun Apr 7 18:20:50 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sun, 7 Apr 2013 17:20:50 +0100 Subject: [Tutor] urllib.urlretrieve ? In-Reply-To: References: Message-ID: > Look in the module docs for urlib.request. > Hi. Ive never used the urllib before unless it was typing in something from an unrelated tutorial. I've also never done anything related to web programming. I'm looking at the urllib.request page and i really don't understand what i'm looking at. I'm confused as to what i should be looking for. From joel.goldstick at gmail.com Sun Apr 7 18:23:37 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 7 Apr 2013 12:23:37 -0400 Subject: [Tutor] urllib.urlretrieve ? In-Reply-To: References: Message-ID: On Sun, Apr 7, 2013 at 11:32 AM, Matthew Ngaha wrote: > the whole program depends on the urlretrieve 3rd argument, the > function to be called.. is there no options to include a callback? > > def _download(self): > > def reporthook(pos, block, total): > if self.size != total: > self._size = total > self.on_size.emit() > self.progress = float(pos*block)/float(total) > > urllib.urlretrieve(self._url, self._filename, reporthook) > ##3rd arg calls inner function > self.running = False > You might want to look at requests module: http://docs.python-requests.org/en/latest/ Many people think it is easier to use than the native python support. > _______________________________________________ > 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 chigga101 at gmail.com Sun Apr 7 18:58:33 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sun, 7 Apr 2013 17:58:33 +0100 Subject: [Tutor] urllib.urlretrieve ? In-Reply-To: References: Message-ID: > > You might want to look at requests module: > http://docs.python-requests.org/en/latest/ > Many people think it is easier to use than the native python support. > are all of these modules related to web programming like clients and (HTTP)servers? I've come across urllib a lot of times but only followed along, maybe its best i just learn about HTTP and its concepts etc so i can understand the request module better then come back to my problem.. Thanks From alan.gauld at btinternet.com Sun Apr 7 20:10:06 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 07 Apr 2013 19:10:06 +0100 Subject: [Tutor] urllib.urlretrieve ? In-Reply-To: References: Message-ID: On 07/04/13 17:20, Matthew Ngaha wrote: >> Look in the module docs for urlib.request. >> > > Hi. Ive never used the urllib before In Python 3 urllib combines (the best) features of urllib and urllib2 from Python 2. > web programming. I'm looking at the urllib.request page and i really > don't understand what i'm looking at. I'm confused as to what i should > be looking for. You were asking about urllib.urlretrieve. It's documented on that page. Now, beyond that, what else are you confused about? The more specific the question the more specific the answer. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From chigga101 at gmail.com Sun Apr 7 20:49:58 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sun, 7 Apr 2013 19:49:58 +0100 Subject: [Tutor] urllib.urlretrieve ? In-Reply-To: References: Message-ID: yeah, sadly urlretrieve doesnt exist on my version of python. i just need a function to put in the same line that replaces this one with the same arguments in order to see the results of my tutorial. urllib.urlretrieve(self._url, self._filename, reporthook) On Sun, Apr 7, 2013 at 7:10 PM, Alan Gauld wrote: > On 07/04/13 17:20, Matthew Ngaha wrote: >>> >>> Look in the module docs for urlib.request. >>> >> >> Hi. Ive never used the urllib before > > > In Python 3 urllib combines (the best) features of > urllib and urllib2 from Python 2. > > >> web programming. I'm looking at the urllib.request page and i really >> don't understand what i'm looking at. I'm confused as to what i should >> be looking for. > > > You were asking about urllib.urlretrieve. > It's documented on that page. > > Now, beyond that, what else are you confused about? > The more specific the question the more specific the answer. > > > -- > 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 From breamoreboy at yahoo.co.uk Sun Apr 7 21:09:23 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 07 Apr 2013 20:09:23 +0100 Subject: [Tutor] urllib.urlretrieve ? In-Reply-To: References: Message-ID: On 07/04/2013 19:49, Matthew Ngaha wrote: Please don't top post. > yeah, sadly urlretrieve doesnt exist on my version of python. i just > need a function to put in the same line that replaces this one with > the same arguments in order to see the results of my tutorial. > > urllib.urlretrieve(self._url, self._filename, reporthook) > > On Sun, Apr 7, 2013 at 7:10 PM, Alan Gauld wrote: >> On 07/04/13 17:20, Matthew Ngaha wrote: >>>> >>>> Look in the module docs for urlib.request. >>>> >>> >>> Hi. Ive never used the urllib before >> >> In Python 3 urllib combines (the best) features of >> urllib and urllib2 from Python 2. >> >>> web programming. I'm looking at the urllib.request page and i really >>> don't understand what i'm looking at. I'm confused as to what i should >>> be looking for. >> >> You were asking about urllib.urlretrieve. >> It's documented on that page. >> >> Now, beyond that, what else are you confused about? >> The more specific the question the more specific the answer. >> >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> See either http://docs.python.org/2/library/urllib.html#urllib.urlretrieve or http://docs.python.org/3/library/urllib.request.html#urllib.request.urlretrieve -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From chigga101 at gmail.com Sun Apr 7 21:59:53 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sun, 7 Apr 2013 20:59:53 +0100 Subject: [Tutor] urllib.urlretrieve ? In-Reply-To: References: Message-ID: >org/2/library/urllib.html#urllib.urlretrieve > or > http://docs.python.org/3/library/urllib.request.html#urllib.request.urlretrieve sorry about the top posting gmail has changed the way their messages are done, it gave me a blank field i didnt realize i was writing above the message. i must have missed it but your 2nd link was exactly what i needed. ive got the program to run without the module error. However i'm out of luck as i now get this error: urllib.error.HTTPError: HTTP Error 404: Not Found i guess the tutorial is very old that the site doesnt exist anymore:( Thanks for the help From bodsda at googlemail.com Sun Apr 7 23:14:51 2013 From: bodsda at googlemail.com (Bod Soutar) Date: Sun, 7 Apr 2013 22:14:51 +0100 Subject: [Tutor] urllib.urlretrieve ? In-Reply-To: References: Message-ID: On 7 April 2013 20:59, Matthew Ngaha wrote: >>org/2/library/urllib.html#urllib.urlretrieve >> or >> http://docs.python.org/3/library/urllib.request.html#urllib.request.urlretrieve > sorry about the top posting gmail has changed the way their messages > are done, it gave me a blank field i didnt realize i was writing above > the message. > > i must have missed it but your 2nd link was exactly what i needed. ive > got the program to run without the module error. However i'm out of > luck as i now get this error: > > urllib.error.HTTPError: HTTP Error 404: Not Found > > i guess the tutorial is very old that the site doesnt exist anymore:( > Thanks for the help Unless you're looking for something specific from the URL that the tutorial uses, then you could use any address Bodsda From chigga101 at gmail.com Mon Apr 8 00:09:51 2013 From: chigga101 at gmail.com (Matthew Ngaha) Date: Sun, 7 Apr 2013 23:09:51 +0100 Subject: [Tutor] urllib.urlretrieve ? In-Reply-To: References: Message-ID: > Unless you're looking for something specific from the URL that the > tutorial uses, then you could use any address > > Bodsda thanks i did that and to my suprise an extra file showed up in my folder, of the page i just visited:) thanks From alan.gauld at btinternet.com Mon Apr 8 00:13:13 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 07 Apr 2013 23:13:13 +0100 Subject: [Tutor] urllib.urlretrieve ? In-Reply-To: References: Message-ID: On 07/04/13 19:49, Matthew Ngaha wrote: > yeah, sadly urlretrieve doesnt exist on my version of python. I just told you where to find it on Python 3. It's just been moved that's all. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mousumi251 at gmail.com Mon Apr 8 09:06:19 2013 From: mousumi251 at gmail.com (Mousumi Basu) Date: Mon, 8 Apr 2013 12:36:19 +0530 Subject: [Tutor] Socket Programming Message-ID: I want to perform binding between two computers having ip addresses 172.18.2.11 and 172.18.2.95.So i wrote the following code(on the computer having IP address 172.18.2.95):- import socket import sys s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) try: s=s.bind(('172.18.2.11',2213)) print 'socket bind is complete' except socket.error,msg: print 'bind failed' sys.exit() The output is :- bind failed but when i am writting;- s=s.bind(('localhost',2213)) the output is;- socket bind is complete Can you please tell me where i am making the error? (The computers are connected as the ping operation is executing properly in command prompt) -------------- next part -------------- An HTML attachment was scrubbed... URL: From timomlists at gmail.com Mon Apr 8 11:19:41 2013 From: timomlists at gmail.com (Timo) Date: Mon, 08 Apr 2013 11:19:41 +0200 Subject: [Tutor] Socket Programming In-Reply-To: References: Message-ID: <51628BAD.7030909@gmail.com> Op 08-04-13 09:06, Mousumi Basu schreef: > I want to perform binding between two computers having ip addresses > 172.18.2.11 and 172.18.2.95.So i wrote the > following code(on the computer having IP address 172.18.2.95):- > > > import socket > import sys > s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) > try: > s=s.bind(('172.18.2.11',2213)) > print 'socket bind is complete' > except socket.error,msg: > print 'bind failed' > sys.exit() You are hiding the error message here. Just print msg and see why it fails. Timo > > > The output is :- > bind failed > > > but when i am writting;- > > s=s.bind(('localhost',2213)) > > the output is;- > socket bind is complete > > > > Can you please tell me where i am making the error? > (The computers are connected as the ping operation is executing > properly in command prompt) > > > > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From sibannac.ms at gmail.com Mon Apr 8 12:21:57 2013 From: sibannac.ms at gmail.com (Max Smith) Date: Mon, 8 Apr 2013 12:21:57 +0200 Subject: [Tutor] if statement problems(noob question) Message-ID: Hi, everyone whom might read this, im Max and i am really new to coding, been going at it for about two weeks using codeacademy and the book "think python". when i decided to experiment a little with if statements i ran into the following problem: def plus(x,y): if x and y == int or float: print "The answer is: " + str(x+y) else: print "not a number" plus(2,2) plus("one","two") concatenates one and two insted of printing "not a number" i have tried to simplify by not cheacking for float values an i have also tried. def plus(x,y): if x and y == int or float: print "The answer is: " + str(x+y) elif x or y != int or float: print "not a number" Am i perhaps missing something with the logic gates? Any help is greatly appreciated ! -------------- next part -------------- An HTML attachment was scrubbed... URL: From woody544 at gmail.com Mon Apr 8 12:37:41 2013 From: woody544 at gmail.com (Woody 544) Date: Mon, 8 Apr 2013 06:37:41 -0400 Subject: [Tutor] if statement problems(noob question) In-Reply-To: References: Message-ID: Max, You've made the arguments a string (so never a number) in: print "The answer is: " + str(x+y) MJ On Apr 8, 2013 6:23 AM, "Max Smith" wrote: > Hi, everyone whom might read this, im Max and i am really new to coding, > been going at it for about two weeks using codeacademy and the book "think > python". > when i decided to experiment a little with if statements i ran into the > following problem: > > def plus(x,y): > if x and y == int or float: > print "The answer is: " + str(x+y) > > else: > print "not a number" > > > plus(2,2) > plus("one","two") > > concatenates one and two insted of printing "not a number" > > i have tried to simplify by not cheacking for float values an i have also > tried. > > def plus(x,y): > if x and y == int or float: > print "The answer is: " + str(x+y) > > elif x or y != int or float: > print "not a number" > > Am i perhaps missing something with the logic gates? > > Any help is greatly appreciated ! > > _______________________________________________ > 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 Mon Apr 8 12:45:59 2013 From: davea at davea.name (Dave Angel) Date: Mon, 08 Apr 2013 06:45:59 -0400 Subject: [Tutor] if statement problems(noob question) In-Reply-To: References: Message-ID: <51629FE7.2030809@davea.name> On 04/08/2013 06:21 AM, Max Smith wrote: > Hi, everyone whom might read this, im Max and i am really new to coding, > been going at it for about two weeks using codeacademy and the book "think > python". > when i decided to experiment a little with if statements i ran into the > following problem: > > def plus(x,y): > if x and y == int or float: What is it you expect this to do? Have you tried a similar, simpler expression to get acquainted? x = 2 if x == int: will always fail, since the integer 2 is not equal to the type int. In Python 2.x, when you compare objects of different types, you generally get unequal. (Exception, if you define your own classes, you can define how they compare to others) In Python 3, you'd get an exception. The way you should test an object to see if it's an instance of a class is to use isinstance() http://docs.python.org/2/library/functions.html#isinstance isinstance(x, int) And if you need to test more than one type or class, use a tuple of the types: isinstance(x, (int, float)) Now you can combine more than one such test: if isinstance(x, (int, float)) and isinstance(y, (int, float)): -- DaveA From davea at davea.name Mon Apr 8 12:49:22 2013 From: davea at davea.name (Dave Angel) Date: Mon, 08 Apr 2013 06:49:22 -0400 Subject: [Tutor] if statement problems(noob question) In-Reply-To: References: Message-ID: <5162A0B2.7040707@davea.name> On 04/08/2013 06:37 AM, Woody 544 wrote: > Max, > > You've made the arguments a string (so never a number) in: > > print "The answer is: " + str(x+y) > > MJ That has nothing to do with the issue. The str() function call is unnecessary, but harmless. If the two values x and y are ints or floats, they will get added in the obvious way long before being converted to str(). If they are already strings, they'll be concatenated long before str() does a null conversion on the resultant string. The problem, as I stated in my own response, is that the if statement does nothing useful for checking of types. -- DaveA From steve at pearwood.info Mon Apr 8 13:55:17 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 08 Apr 2013 21:55:17 +1000 Subject: [Tutor] if statement problems(noob question) In-Reply-To: <51629FE7.2030809@davea.name> References: <51629FE7.2030809@davea.name> Message-ID: <5162B025.20709@pearwood.info> On 08/04/13 20:45, Dave Angel wrote: > > will always fail, since the integer 2 is not equal to the type int. In Python 2.x, when you compare objects of different types, you generally get unequal. (Exception, if you define your own classes, you can define how they compare to others) In Python 3, you'd get an exception. Not so. Equality testing is always allowed. In Python 3: py> 25 == "hello world" False exactly the same as in Python 2. It's only ordering comparisons, < <= >= > that raise an error with incompatible types: py> 25 <= "hello world" Traceback (most recent call last): File "", line 1, in TypeError: unorderable types: int() <= str() -- Steven From steve at pearwood.info Mon Apr 8 14:18:06 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 08 Apr 2013 22:18:06 +1000 Subject: [Tutor] if statement problems(noob question) In-Reply-To: References: Message-ID: <5162B57E.1050409@pearwood.info> On 08/04/13 20:21, Max Smith wrote: > Hi, everyone whom might read this, im Max and i am really new to coding, > been going at it for about two weeks using codeacademy and the book "think > python". > when i decided to experiment a little with if statements i ran into the > following problem: > > def plus(x,y): > if x and y == int or float: > print "The answer is: " + str(x+y) > else: > print "not a number" Your problem here is that you've let Python's friendly syntax fool you into thinking you can program in English. Python's good, but it's not that good! In English, I might say to you: "If x and y are ints, or floats, then do this ..." which you've translated into Python as: if x and y == int or float: ... But that's not what it means to Python. What Python does is quite different. Translating the above: if x is a truthy value, and y equals the function "int", or the function "float" is a truthy value, then ... What do I mean by "is a truthy value"? Python has a rule that *every* value, numbers, strings, lists, etc, everything, can be considered "true-like" or "false-like". The rules are: - values which are considered "empty" or "nothing" in some sense are treated as false-like: zero numbers: 0, 0.0 empty string: '' empty containers (lists, dicts, tuples) None False are all "false-like" or "falsey" values. - values which are considered non-empty, or "something", are treated as true-like: every number except zero, e.g. 0.0001, 42, -17.4 every non-empty string, e.g. "hello world" every non-empty container, e.g. [1, 2, 3] True functions modules etc. are all "true-like" or "truthy" values. So let's go back to your code: if x and y == int or float: ... 1) First, Python checks whether x is a truthy value. In the examples you give, it is, so the if-clause starts to look like this: if True and y == int or float: ... 2) Next, Python checks whether y equals the int function. In this case, it does not, so the if-clause looks like this: if True and False or float: ... and Python can simplify "True and False" to just False: if False or float: ... 3) Next, Python checks whether the float function is a truthy value. Since functions are "something" rather than "nothing", it is considered truthy, and the if-clause looks like this: if False or True: ... which Python simplifies to: if True: ... and so the if-clause *always* evaluates as True. So what do you have to write instead? Firstly, you can't check the type of a value with equals. You use the isinstance function instead. To check if x is an int: if isinstance(x, int): ... To check if x is an int, or a float, make the second argument a tuple of types: if isinstance(x, (int, float)): ... To check is x *and* y are ints, or floats, you have to check each one separately: number = (int, float) # tuple of two types if isinstance(x, number) and isinstance(y, number): ... Try that, and see how your code works. -- Steven From steve at pearwood.info Mon Apr 8 14:26:28 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 08 Apr 2013 22:26:28 +1000 Subject: [Tutor] Socket Programming In-Reply-To: References: Message-ID: <5162B774.7040201@pearwood.info> On 08/04/13 17:06, Mousumi Basu wrote: > I want to perform binding between two computers having ip addresses > 172.18.2.11 and 172.18.2.95.So i wrote the following code(on the computer > having IP address 172.18.2.95):- > > > import socket > import sys > s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) > try: > s=s.bind(('172.18.2.11',2213)) > print 'socket bind is complete' > except socket.error,msg: > print 'bind failed' > sys.exit() Why are you throwing away the useful information Python gives you to debug the problem? That's like trying to find your lost keys by deliberately putting on a blindfold. Never, never, never catch an exception only to print a useless message that tells you nothing. "Bind failed"? Why did it fail? Who knows! You threw that information away. You might as well have said "An error occurred". Instead, use this code: import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s = s.bind(('172.18.2.11', 2213)) print 'socket bind is complete' If an error occurs, Python will automatically print a full traceback showing you exactly: * what went wrong * where it went wrong * what line of code caused the problem * what type of problem it was instead of just a useless "an error occurred" message. Once you have a proper traceback, and you can see the actual error message, then and only then can we begin to solve the problem. -- Steven From davea at davea.name Mon Apr 8 14:27:31 2013 From: davea at davea.name (Dave Angel) Date: Mon, 08 Apr 2013 08:27:31 -0400 Subject: [Tutor] if statement problems(noob question) In-Reply-To: <5162B025.20709@pearwood.info> References: <51629FE7.2030809@davea.name> <5162B025.20709@pearwood.info> Message-ID: <5162B7B3.4050909@davea.name> On 04/08/2013 07:55 AM, Steven D'Aprano wrote: > On 08/04/13 20:45, Dave Angel wrote: >> >> will always fail, since the integer 2 is not equal to the type int. >> In Python 2.x, when you compare objects of different types, you >> generally get unequal. (Exception, if you define your own classes, >> you can define how they compare to others) In Python 3, you'd get an >> exception. > > > Not so. Equality testing is always allowed. > Right. Thanks for the correction. I should know better by now. I knew I should have left that part off, since the OP is using version 2 anyway. -- DaveA From s.shall at virginmedia.com Mon Apr 8 14:40:17 2013 From: s.shall at virginmedia.com (Sydney Shall) Date: Mon, 08 Apr 2013 13:40:17 +0100 Subject: [Tutor] How to extract a float from an instancemethod call Message-ID: <5162BAB1.8010700@virginmedia.com> Hi, I am learning Python. I use MAC OSX 10.6.8 Python 2.7.3 I have been given a project to write a program involving random walks. I have drafted a program which has passed all the static tests, but on testing my program i get the following error message: Traceback (most recent call last): File "/Users/Sydney/Documents/6.00x Files/Problem Sets/ProblemSet7/ps7 copy.py", line 303, in testRobotMovement(StandardRobot, RectangularRoom) File "ps7_verify_movement.py", line 12, in testRobotMovement File "/Users/Sydney/Documents/6.00x Files/Problem Sets/ProblemSet7/ps7 copy.py", line 285, in updatePositionAndClean while self.room.isPositionInRoom(self.position) == False: File "/Users/Sydney/Documents/6.00x Files/Problem Sets/ProblemSet7/ps7 copy.py", line 163, in isPositionInRoom return self.room[(x,y)] in self.room KeyError: (>, >) >>> The program text referred to is the following, I give the whole module, which is part of a larger program. def isPositionInRoom(self, pos): """ Return True if pos is inside the room. pos: a Position object. returns: True if pos is in the room, False otherwise. """ x = pos.getX y = pos.getY return self.room[(x,y)] in self.room The module that made the call is; def updatePositionAndClean(self): """ Simulate the raise passage of a single time-step. Move the robot to a new position and mark the tile it is on as having been cleaned. """ steps = 0 self.position = self.room.getRandomPosition() print self.position self.x = self.position.getX self.y = self.position.getY print self.room self.room.cleanTileAtPosition((self.x, self.y)) self.direction = self.getRobotDirection() print 'Initial direction in degrees is ' , self.direction self.position = self.position.getNewPosition(self.direction, self.speed) steps += 1 while self.room.isPositionInRoom(self.position) == False: self.direction = Robot.getRobotDirection() self.position = Position.getNewPosition(self.direction, self.speed) steps += 1 self.x = self.position.getX self.y = self.position.getY print 'Current position is x,y ', self.x, self.y print 'Current direction is ' , self.direction + 'Degrees.' self.room.cleanTileAtPosition((self.x, self.y)) print self.room.isTileCleaned((self.x, self.y)) I do not understand how one extracts a number from an instance method that should return a number. I need to convert this number a float to an int to avoid the key error. But I do not know how to extract the float. This conclusion I derive from this earlier error message; Traceback (most recent call last): File "/Users/Sydney/Documents/6.00x Files/Problem Sets/ProblemSet7/ps7 copy.py", line 303, in testRobotMovement(StandardRobot, RectangularRoom) File "ps7_verify_movement.py", line 12, in testRobotMovement File "/Users/Sydney/Documents/6.00x Files/Problem Sets/ProblemSet7/ps7 copy.py", line 285, in updatePositionAndClean while self.room.isPositionInRoom(self.position) == False: File "/Users/Sydney/Documents/6.00x Files/Problem Sets/ProblemSet7/ps7 copy.py", line 163, in isPositionInRoom return self.room[(int(x), int(y))] in self.room TypeError: int() argument must be a string or a number, not 'instancemethod' >>> ================================ RESTART ================================ I would be grateful for any guidance. -- Sydney Shall From davea at davea.name Mon Apr 8 14:52:21 2013 From: davea at davea.name (Dave Angel) Date: Mon, 08 Apr 2013 08:52:21 -0400 Subject: [Tutor] How to extract a float from an instancemethod call In-Reply-To: <5162BAB1.8010700@virginmedia.com> References: <5162BAB1.8010700@virginmedia.com> Message-ID: <5162BD85.7070207@davea.name> On 04/08/2013 08:40 AM, Sydney Shall wrote: > Hi, > I am learning Python. > > I use MAC OSX 10.6.8 > Python 2.7.3 > > I have been given a project to write a program involving random walks. > I have drafted a program which has passed all the static tests, but on > testing my program i get the following error message: > > > Traceback (most recent call last): > File "/Users/Sydney/Documents/6.00x Files/Problem > Sets/ProblemSet7/ps7 copy.py", line 303, in > testRobotMovement(StandardRobot, RectangularRoom) > File "ps7_verify_movement.py", line 12, in testRobotMovement > File "/Users/Sydney/Documents/6.00x Files/Problem > Sets/ProblemSet7/ps7 copy.py", line 285, in updatePositionAndClean > while self.room.isPositionInRoom(self.position) == False: > File "/Users/Sydney/Documents/6.00x Files/Problem > Sets/ProblemSet7/ps7 copy.py", line 163, in isPositionInRoom > return self.room[(x,y)] in self.room > KeyError: ( 0x4699490>>, 0x4699490>>) > >>> > > The program text referred to is the following, I give the whole module, > which is part of a larger program. > def isPositionInRoom(self, pos): > """ > Return True if pos is inside the room. > > pos: a Position object. > returns: True if pos is in the room, False otherwise. > """ > x = pos.getX > y = pos.getY You never show the code for Position.getX and Position.getY, but I'd expect they're methods that take no arguments. in that case, you need parens in order to call them. x = pos.getX() y = pos.getY() > return self.room[(x,y)] in self.room > a simple print of x and y could have revealed this as well. -- DaveA From kushal.kumaran+python at gmail.com Mon Apr 8 15:37:58 2013 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Mon, 08 Apr 2013 19:07:58 +0530 Subject: [Tutor] Socket Programming In-Reply-To: References: Message-ID: <5162c83b.e5f1420a.13d6.ffff81bf@mx.google.com> Mousumi Basu writes: > I want to perform binding between two computers having ip addresses > 172.18.2.11 and 172.18.2.95.So i wrote the following code(on the computer > having IP address 172.18.2.95):- > > > import socket > import sys > s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) > try: > s=s.bind(('172.18.2.11',2213)) The bind method does not do what you think it does. To bind to an IP address, the address must be assigned to one of the interfaces on the host where the code is running. So your bind call will not work on 172.18.2.95. It will only work on 172.18.2.11. To make a connection to a different host, you call the connect method. Since you are using SOCK_DGRAM, an explicit connect call is not required. You can just call the sendto method on the socket. On the other end, the socket will need the bind method to be called. It can then call recvfrom to receive data. You should read an introductory sockets programming text if you intend to use the python socket module. This page: http://beej.us/guide/bgnet/output/html/multipage/index.html which showed up in my web search, seems simple. You will have to translate C code to python, but the basic concepts will apply. > print 'socket bind is complete' > except socket.error,msg: > print 'bind failed' > sys.exit() > > > The output is :- > bind failed > > > but when i am writting;- > > s=s.bind(('localhost',2213)) > > the output is;- > socket bind is complete > > > > Can you please tell me where i am making the error? > (The computers are connected as the ping operation is executing properly in > command prompt) -- regards, kushal From Steve.Flynn at capita.co.uk Mon Apr 8 14:48:17 2013 From: Steve.Flynn at capita.co.uk (Flynn, Stephen (L & P - IT)) Date: Mon, 8 Apr 2013 13:48:17 +0100 Subject: [Tutor] How to extract a float from an instancemethod call In-Reply-To: <5162BAB1.8010700@virginmedia.com> References: <5162BAB1.8010700@virginmedia.com> Message-ID: Aha - another EdX 6.00 Python course student. > Traceback (most recent call last): > File "/Users/Sydney/Documents/6.00x Files/Problem > Sets/ProblemSet7/ps7 copy.py", line 303, in > testRobotMovement(StandardRobot, RectangularRoom) > File "ps7_verify_movement.py", line 12, in testRobotMovement > File "/Users/Sydney/Documents/6.00x Files/Problem > Sets/ProblemSet7/ps7 copy.py", line 285, in updatePositionAndClean > while self.room.isPositionInRoom(self.position) == False: > File "/Users/Sydney/Documents/6.00x Files/Problem > Sets/ProblemSet7/ps7 copy.py", line 163, in isPositionInRoom > return self.room[(x,y)] in self.room > KeyError: ( 0x4699490>>, 0x4699490>>) > >>> > > The program text referred to is the following, I give the whole module, > which is part of a larger program. > def isPositionInRoom(self, pos): > """ > Return True if pos is inside the room. > > pos: a Position object. > returns: True if pos is in the room, False otherwise. > """ > x = pos.getX > y = pos.getY > return self.room[(x,y)] in self.room You extract X and Y from the Position object using it's accessor methods. All you then need to do is check to ensure that both X and Y are >= zero and that both of them, when converted to an into, are less than room. width and room. height. This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. From alan.gauld at btinternet.com Mon Apr 8 11:02:04 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 08 Apr 2013 10:02:04 +0100 Subject: [Tutor] Socket Programming In-Reply-To: References: Message-ID: On 08/04/13 08:06, Mousumi Basu wrote: > import socket > import sys > s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) > try: > s=s.bind(('172.18.2.11',2213)) > print 'socket bind is complete' > except socket.error,msg: > print 'bind failed' > sys.exit() Your first error is that when developing you don't want to hide the error messages so add a raise statement to the except block so you get the full traceback with all of its helpful details. > but when i am writting;- > > s=s.bind(('localhost',2213)) > > the output is;- > socket bind is complete Which suggests that the 172... IP address you are using above is not recognised... or maybe has a firewall around it, or some other restrictions on access. > Can you please tell me where i am making the error? > (The computers are connected as the ping operation is executing properly > in command prompt) It is most likely a network configuration issue but only you can fix that since we can't see how the network is set up. Rather than using ping try using telnet to reach the IP address and port and see what response you get. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From losermeloser at yahoo.com Mon Apr 8 18:24:32 2013 From: losermeloser at yahoo.com (Lolo Lolo) Date: Mon, 8 Apr 2013 09:24:32 -0700 (PDT) Subject: [Tutor] Socket Programming In-Reply-To: <5162c83b.e5f1420a.13d6.ffff81bf@mx.google.com> References: <5162c83b.e5f1420a.13d6.ffff81bf@mx.google.com> Message-ID: <1365438272.94498.YahooMailNeo@web121105.mail.ne1.yahoo.com> on socket programming. if as a client or server, the information being sent has a buffer size on 2048, will this retrieve all data below 2KB? or can it be exceeded with say 2100? or does 2100 fall under 3KB? -------------- next part -------------- An HTML attachment was scrubbed... URL: From donald.dietrich at live.com Mon Apr 8 20:58:54 2013 From: donald.dietrich at live.com (Donald Dietrich) Date: Mon, 8 Apr 2013 18:58:54 +0000 Subject: [Tutor] =?utf-8?q?Reading_Program?= Message-ID: I am just new to python programing, but would like some help developing a program for ?flow reading? What I would like the program to do is use any .txt file like micorsoft word .txt file and flow the words across the screen one at time until the file is come to the end. I would also like to control the rate (time) of flow. Do you think you can help me. Sincerely, Donald Dietrich Sent from Windows Mail -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Apr 8 21:46:29 2013 From: bgailer at gmail.com (bob gailer) Date: Mon, 08 Apr 2013 15:46:29 -0400 Subject: [Tutor] Reading Program In-Reply-To: References: Message-ID: <51631E95.1060505@gmail.com> On 4/8/2013 2:58 PM, Donald Dietrich wrote: > I am just new to python programing welcome. what other programming experience do you have? What version of python? and what OS? > would like some help developing a program for "flow reading" What I > would like the program to do is use any .txt file like micorsoft word > .txt file and flow the words across the screen one at time until the > file is come to the end. I would also like to control the rate (time) > of flow. Do you have any experience developing GUI applications? Do you have any experience with reading files? I would start simple, and add pieces one at a time. Pseudo code: open the file grab a line split it (by default this will give you a list of "words" - meaning text strings that are separated from one another by whitespace) write a word to the console (terminal) sleep for a short time repeat for each word in the list repeat for each line in the file. Then take a look at the various GUI packages that have a Python version. tkinter comes with the Python distribution. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From brianjamesarb at gmail.com Mon Apr 8 22:38:24 2013 From: brianjamesarb at gmail.com (brian arb) Date: Mon, 8 Apr 2013 16:38:24 -0400 Subject: [Tutor] FYI: An Introduction to Interactive Programming in Python Message-ID: An Introduction to Interactive Programming in PythonJoe Warren, Scott Rixner, Stephen Wong and John Greiner This course is designed to be a fun introduction to the basics of programming in Python. Our main focus will be on building simple interactive games such as Pong, Blackjack and Asteroids. https://www.coursera.org/course/interactivepython -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Tue Apr 9 01:58:42 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 09 Apr 2013 09:58:42 +1000 Subject: [Tutor] FYI: An Introduction to Interactive Programming in Python In-Reply-To: References: Message-ID: <516359B2.2040300@pearwood.info> On 09/04/13 06:38, brian arb wrote: > An Introduction to Interactive Programming in PythonJoe Warren, Scott > Rixner, Stephen Wong and John Greiner > > This course is designed to be a fun introduction to the basics of > programming in Python. Our main focus will be on building simple > interactive games such as Pong, Blackjack and Asteroids. > > https://www.coursera.org/course/interactivepython Thanks for the link Brian. As an aside, I wonder, apart from Conway's Game of Life, which isn't actually a game at all, what's a non-interactive game? -- Steven From dfjennings at gmail.com Tue Apr 9 02:29:42 2013 From: dfjennings at gmail.com (Don Jennings) Date: Mon, 8 Apr 2013 20:29:42 -0400 Subject: [Tutor] FYI: An Introduction to Interactive Programming in Python In-Reply-To: <516359B2.2040300@pearwood.info> References: <516359B2.2040300@pearwood.info> Message-ID: On Apr 8, 2013, at 7:58 PM, Steven D'Aprano wrote: > On 09/04/13 06:38, brian arb wrote: >> An Introduction to Interactive Programming in PythonJoe Warren, Scott >> Rixner, Stephen Wong and John Greiner >> >> This course is designed to be a fun introduction to the basics of >> programming in Python. Our main focus will be on building simple >> interactive games such as Pong, Blackjack and Asteroids. >> >> https://www.coursera.org/course/interactivepython > > Thanks for the link Brian. > > As an aside, I wonder, apart from Conway's Game of Life, which isn't > actually a game at all, what's a non-interactive game? Watching someone else play Pong? ;>) Take care, Don From davea at davea.name Tue Apr 9 03:54:37 2013 From: davea at davea.name (Dave Angel) Date: Mon, 08 Apr 2013 21:54:37 -0400 Subject: [Tutor] FYI: An Introduction to Interactive Programming in Python In-Reply-To: <516359B2.2040300@pearwood.info> References: <516359B2.2040300@pearwood.info> Message-ID: <516374DD.3060704@davea.name> On 04/08/2013 07:58 PM, Steven D'Aprano wrote: > On 09/04/13 06:38, brian arb wrote: >> An Introduction to Interactive Programming in PythonJoe Warren, Scott >> Rixner, Stephen Wong and John Greiner >> >> This course is designed to be a fun introduction to the basics of >> programming in Python. Our main focus will be on building simple >> interactive games such as Pong, Blackjack and Asteroids. >> >> https://www.coursera.org/course/interactivepython > > Thanks for the link Brian. > > As an aside, I wonder, apart from Conway's Game of Life, which isn't > actually a game at all, what's a non-interactive game? > > Perhaps a game where the interaction is not real-time, like Adventure and other early RPG's. -- DaveA From LConrad at Go2France.com Tue Apr 9 05:20:24 2013 From: LConrad at Go2France.com (Len Conrad) Date: Mon, 08 Apr 2013 21:20:24 -0600 Subject: [Tutor] FYI: An Introduction to Interactive Programming in Python In-Reply-To: <516374DD.3060704@davea.name> References: <516359B2.2040300@pearwood.info> <516374DD.3060704@davea.name> Message-ID: <201304090521923.SM01804@W500.Go2France.com> wrong teaching language! :) Computer scientists develop video game that teaches how to program in Java http://phys.org/news/2013-04-scientists-video-game-java.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From kartiksundarajan at gmail.com Tue Apr 9 08:18:48 2013 From: kartiksundarajan at gmail.com (kartik sundarajan) Date: Tue, 9 Apr 2013 11:48:48 +0530 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: My guess is you are using Python version >2.6 where "set" is a built-in. You can fix this by doing the following. 1) Remove "from sets import Set" 2) And replace "alphabet = list(Set(stList))" with "alphabet = list(set(stList))" This should work straight away. P.S Its "Python" not phyton Cheers Kartik On Sun, Mar 24, 2013 at 12:20 PM, michelle_low wrote: > ** > > 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)) > > _______________________________________________ > 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 Apr 9 09:50:52 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 09 Apr 2013 08:50:52 +0100 Subject: [Tutor] FYI: An Introduction to Interactive Programming in Python In-Reply-To: <201304090521923.SM01804@W500.Go2France.com> References: <516359B2.2040300@pearwood.info> <516374DD.3060704@davea.name> <201304090521923.SM01804@W500.Go2France.com> Message-ID: On 09/04/13 04:20, Len Conrad wrote: > Computer scientists develop video game that teaches how to program in > Java* > > http://phys.org/news/2013-04-scientists-video-game-java.html As an engineer I used to be embarrassed that people called it software engineering. Now they are calling this computer *science*.... oh dear... ======================== CodeSpells was influenced by research that Esper and Foster conducted on how successful programmers learn their trade. They surveyed 30 computer scientists and identified five characteristics that are key to learn programming outside a classroom setting: activities must be structured by the person who is trying to learn; learning must be creative and exploratory; programming is empowering; learners have difficulty stopping once they start; and learners spend countless hours on the activity. ======================= Since when did 30 become a representative sample size? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From breamoreboy at yahoo.co.uk Tue Apr 9 10:48:32 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 09 Apr 2013 09:48:32 +0100 Subject: [Tutor] FYI: An Introduction to Interactive Programming in Python In-Reply-To: <201304090521923.SM01804@W500.Go2France.com> References: <516359B2.2040300@pearwood.info> <516374DD.3060704@davea.name> <201304090521923.SM01804@W500.Go2France.com> Message-ID: On 09/04/2013 04:20, Len Conrad wrote: > > *wrong teaching language! :) > > Computer scientists develop video game that teaches how to program in > Java* > > http://phys.org/news/2013-04-scientists-video-game-java.html > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Please tone down your language. Using four letter words starting with 'j' on a Python mailing list is a bit offputting first thing in the morning :) -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From daedae11 at 126.com Tue Apr 9 10:20:42 2013 From: daedae11 at 126.com (daedae11) Date: Tue, 9 Apr 2013 16:20:42 +0800 (CST) Subject: [Tutor] How to make a python script run on startup Message-ID: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com> On Windows, how to make a python script run on startup? -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Tue Apr 9 11:29:56 2013 From: davea at davea.name (Dave Angel) Date: Tue, 09 Apr 2013 05:29:56 -0400 Subject: [Tutor] How to make a python script run on startup In-Reply-To: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com> References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com> Message-ID: <5163DF94.1070107@davea.name> On 04/09/2013 04:20 AM, daedae11 wrote: > On Windows, how to make a python script run on startup? > > Windows has a system scheduler, which you can add entries to, specifying what time(s) a particular entry is to run. One of the choices is system startup. -- DaveA From rhettnaxel at gmail.com Tue Apr 9 11:54:50 2013 From: rhettnaxel at gmail.com (Alexander Mark) Date: Tue, 9 Apr 2013 05:54:50 -0400 Subject: [Tutor] How to make a python script run on startup In-Reply-To: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com> References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com> Message-ID: <092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com> There is a startup folder, usually on the start menu, you can add the script to. --ame On Apr 9, 2013, at 4:20, daedae11 wrote: > On Windows, how to make a python script run on startup? > > > _______________________________________________ > 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 sayanchatterjee at gmail.com Tue Apr 9 13:14:55 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Tue, 9 Apr 2013 16:44:55 +0530 Subject: [Tutor] How to make a python script run on startup In-Reply-To: <092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com> References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com> <092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com> Message-ID: Anything executable inside the start-up folder will run on start up! On 9 April 2013 15:24, Alexander Mark wrote: > There is a startup folder, usually on the start menu, you can add the > script to. > > --ame > > On Apr 9, 2013, at 4:20, daedae11 wrote: > > On Windows, how to make a python script run on startup? > > > _______________________________________________ > 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 > > -- -------------------------------------------------------------------------- *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 eryksun at gmail.com Tue Apr 9 13:21:32 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 9 Apr 2013 07:21:32 -0400 Subject: [Tutor] How to make a python script run on startup In-Reply-To: <092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com> References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com> <092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com> Message-ID: On Tue, Apr 9, 2013 at 5:54 AM, Alexander Mark wrote: > There is a startup folder, usually on the start menu, you can add the script > to. current user: "%USERPROFILE%\Start Menu\Programs\Startup" all users: "%ALLUSERSPROFILE%\Start Menu\Programs\Startup" Updating the latter will probably require elevation, which you do via ShellExecute with the "runas" verb, using either pywin32 or ctypes. If you don't want a console use the .pyw extension. From ausnajm at yahoo.com.au Tue Apr 9 13:50:45 2013 From: ausnajm at yahoo.com.au (Najam Us Saqib) Date: Tue, 9 Apr 2013 04:50:45 -0700 (PDT) Subject: [Tutor] Flip a coin Message-ID: <1365508245.81711.YahooMailNeo@web161802.mail.bf1.yahoo.com> Hi, This program is killing me, I have been working on it for last 3 hours, I have tried my best but can't make it work, please help me out.? The Problem: Create a program that flips a coin 100 times and than tells you the number of tails and heads. My code: # Flip a coin import random flip_coin = 100 head = "" tail = "" n_head = 0 n_tail = 0 the_num = (raw_input("Press enter key to flip the coin!")) #raw_input("Please Flip the Coin") while flip_coin != 100: ? ? flip_coin = random.randrange(100) +1? ? ? if flip_coin <= 50: ? ? ? ? ? ? ? ?print "head" ? ?? ? ? else:? ? ? ?print "tail" ? ?? ? ? the_num = (raw_input("Press Enter to flip the coin")) ? ? n_head += 1 ? ? n_tail += 1 ? ?? ? ?? print "The total numbers of heads are" ,n_head print "The total numbers of tails are" ,n_tail raw_input("\n\nPress the enter key to exit, thank you") Thank you very much, looking forward to hear from you. Regards, Najam. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sayanchatterjee at gmail.com Tue Apr 9 14:14:59 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Tue, 9 Apr 2013 17:44:59 +0530 Subject: [Tutor] Flip a coin In-Reply-To: <1365508245.81711.YahooMailNeo@web161802.mail.bf1.yahoo.com> References: <1365508245.81711.YahooMailNeo@web161802.mail.bf1.yahoo.com> Message-ID: flip_coin = 100 and then after a while while flip_coin != 100: It is contradicting.So the while loop is never executed. Just put flip_coin = 0 and remove head = "" tail = "" They are not necessary. It should work. Cheers, Sayan On 9 April 2013 17:20, Najam Us Saqib wrote: > Hi, > > This program is killing me, I have been working on it for last 3 hours, I > have tried my best but can't make it work, please help me out. > > The Problem: > > Create a program that flips a coin 100 times and than tells you the number > of tails and heads. > > My code: > > # Flip a coin > > import random > > flip_coin = 100 > head = "" > tail = "" > n_head = 0 > n_tail = 0 > the_num = (raw_input("Press enter key to flip the coin!")) > > > #raw_input("Please Flip the Coin") > > while flip_coin != 100: > flip_coin = random.randrange(100) +1 > if flip_coin <= 50: > > print "head" > > else: > print "tail" > > the_num = (raw_input("Press Enter to flip the coin")) > n_head += 1 > n_tail += 1 > > > > print "The total numbers of heads are" ,n_head > print "The total numbers of tails are" ,n_tail > > raw_input("\n\nPress the enter key to exit, thank you") > > Thank you very much, looking forward to hear from you. > > Regards, > Najam. > > > > _______________________________________________ > 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 steve at pearwood.info Tue Apr 9 14:18:17 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 09 Apr 2013 22:18:17 +1000 Subject: [Tutor] Flip a coin In-Reply-To: <1365508245.81711.YahooMailNeo@web161802.mail.bf1.yahoo.com> References: <1365508245.81711.YahooMailNeo@web161802.mail.bf1.yahoo.com> Message-ID: <51640709.4030202@pearwood.info> On 09/04/13 21:50, Najam Us Saqib wrote: > Hi, > > This program is killing me, I have been working on it for last 3 hours, I have tried my best but can't make it work, please help me out. Would you like to tell us what it is doing wrong, or should we guess? My guess is below: > flip_coin = 100 Here you set flip_coin to 100. > while flip_coin != 100: Here you test whether flip_coin is not equal to 100. Since it is 100, the while loop is skipped, and nothing you write inside the while loop is executed at all. If you want to run something 100 times, use a for loop: for i in range(100): do_something() -- Steven From steve at pearwood.info Tue Apr 9 14:47:50 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 09 Apr 2013 22:47:50 +1000 Subject: [Tutor] FYI: An Introduction to Interactive Programming in Python In-Reply-To: References: <516359B2.2040300@pearwood.info> <516374DD.3060704@davea.name> <201304090521923.SM01804@W500.Go2France.com> Message-ID: <51640DF6.4060503@pearwood.info> On 09/04/13 17:50, Alan Gauld wrote: > On 09/04/13 04:20, Len Conrad wrote: > >> Computer scientists develop video game that teaches how to program in >> Java* >> >> http://phys.org/news/2013-04-scientists-video-game-java.html > > As an engineer I used to be embarrassed that people called it software engineering. Now they are calling this computer *science*.... oh dear... Computer science is a science, or to be technical, a branch of mathematics. It has about as much to do with the every day practice of writing programs as science does to the every day practice of building televisions -- that is to say, depending on how you look at it, either *not at all* or *completely*. But in this case, it's less computer science and more pedagogy, which is the science and art of teaching. > ======================== > CodeSpells was influenced by research that Esper and Foster conducted on how successful programmers learn their trade. They surveyed 30 computer scientists and identified five characteristics that are key to learn programming outside a classroom setting: activities must be structured by the person who is trying to learn; learning must be creative and exploratory; programming is empowering; learners have difficulty stopping once they start; and learners spend countless hours on the activity. > ======================= > > Since when did 30 become a representative sample size? If they are randomly selected, 30 is likely plenty for a representative sample size. In surveys, a sample size of 30 gives you a margin of error of about 15%, which isn't too bad. (To drop that margin of error to 10% means increasing the sample size to about 65, and to 5%, you need about 250 people.) In this case, I would be suspicious of the results, not because 30 is too small a sample, but because: 1) it is likely to be a biased selection 2) both computer scientists and educators are prone to fashions, and Java is one such fashion. -- Steven From kevgathuku at gmail.com Tue Apr 9 15:48:45 2013 From: kevgathuku at gmail.com (Kevin Ndung'u) Date: Tue, 9 Apr 2013 16:48:45 +0300 Subject: [Tutor] How to make a python script run on startup In-Reply-To: References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com> <092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com> Message-ID: anybody know how to do this on linux? On 4/9/13, eryksun wrote: > On Tue, Apr 9, 2013 at 5:54 AM, Alexander Mark > wrote: >> There is a startup folder, usually on the start menu, you can add the >> script >> to. > > current user: > "%USERPROFILE%\Start Menu\Programs\Startup" > > all users: > "%ALLUSERSPROFILE%\Start Menu\Programs\Startup" > > Updating the latter will probably require elevation, which you do via > ShellExecute with the "runas" verb, using either pywin32 or ctypes. If > you don't want a console use the .pyw extension. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From sayanchatterjee at gmail.com Tue Apr 9 16:12:05 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Tue, 9 Apr 2013 19:42:05 +0530 Subject: [Tutor] How to make a python script run on startup In-Reply-To: References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com> <092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com> Message-ID: Hope this link helps.:) http://stackoverflow.com/questions/8339555/how-to-run-a-script-at-the-start-up-of-ubuntu On 9 April 2013 19:18, Kevin Ndung'u wrote: > anybody know how to do this on linux? > > On 4/9/13, eryksun wrote: > > On Tue, Apr 9, 2013 at 5:54 AM, Alexander Mark > > wrote: > >> There is a startup folder, usually on the start menu, you can add the > >> script > >> to. > > > > current user: > > "%USERPROFILE%\Start Menu\Programs\Startup" > > > > all users: > > "%ALLUSERSPROFILE%\Start Menu\Programs\Startup" > > > > Updating the latter will probably require elevation, which you do via > > ShellExecute with the "runas" verb, using either pywin32 or ctypes. If > > you don't want a console use the .pyw extension. > > _______________________________________________ > > 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 > -- -------------------------------------------------------------------------- *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 msirenef at lightbird.net Tue Apr 9 16:30:20 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Tue, 09 Apr 2013 10:30:20 -0400 Subject: [Tutor] Flip a coin In-Reply-To: <1365508245.81711.YahooMailNeo@web161802.mail.bf1.yahoo.com> References: <1365508245.81711.YahooMailNeo@web161802.mail.bf1.yahoo.com> Message-ID: <516425FC.8050105@lightbird.net> On 04/09/2013 07:50 AM, Najam Us Saqib wrote: > Hi, > > This program is killing me, I have been working on it for last 3 hours, I have tried my best but can't make it work, please help me out. > > The Problem: > > Create a program that flips a coin 100 times and than tells you the number of tails and heads. > > My code: > > # Flip a coin > > import random > > flip_coin = 100 > head = "" > tail = "" > n_head = 0 > n_tail = 0 > the_num = (raw_input("Press enter key to flip the coin!")) > > > #raw_input("Please Flip the Coin") > > while flip_coin != 100: > flip_coin = random.randrange(100) +1 > if flip_coin <= 50: > > print "head" > > else: > print "tail" > > the_num = (raw_input("Press Enter to flip the coin")) > n_head += 1 > n_tail += 1 > > > > print "The total numbers of heads are" ,n_head > print "The total numbers of tails are" ,n_tail > > raw_input("\n\nPress the enter key to exit, thank you") > > Thank you very much, looking forward to hear from you. > > Regards, > Najam. > You shouldn't start with writing code when you're not clear on how it needs to work -- instead, start with pseudo code. In the same way, if you can lift 200lbs you can start with 100lbs and then work your way up. The pseudo code is a lot simpler to write than code: # assume 0 is heads and 1 is tails num_heads = num_tails = 0 - repeat 100 times: get input from user if input == quit: break loop flip = random integer out of 0 and 1 if flip: print tails num_tails += 1 else: print heads num_heads += 1 print num_heads, num_tails print Exiting... To find out how to pick a random integer, see: http://docs.python.org/2/library/random.html -m -- Lark's Tongue Guide to Python: http://lightbird.net/larks/ From eryksun at gmail.com Tue Apr 9 16:38:36 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 9 Apr 2013 10:38:36 -0400 Subject: [Tutor] How to make a python script run on startup In-Reply-To: <7c3c0ce4.1900b.13deecaf89f.Coremail.daedae11@126.com> References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com> <092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com> <7c3c0ce4.1900b.13deecaf89f.Coremail.daedae11@126.com> Message-ID: On Tue, Apr 9, 2013 at 8:35 AM, daedae11 wrote: > I refer the msdn for ShellExecute, there isn't a "runas" verb, only "edit", > "find", "open", "print", "properties". Adding a file to the all users startup folder probably doesn't even require elevation. Maybe even a regular user can do it, given the default ProgramData NTFS permissions. I don't remember what the defaults are. Background: NT 6 (Vista) added User Account Control (UAC), which adds the "run as administrator" option. This launches a process with an elevated access token. ShellExecute allows the same with the "runas" verb. You can verify whether it exists on your system for the exefile filetype (e.g. python.exe): C:\>reg query hkcr\exefile\shell\runas\command HKEY_CLASSES_ROOT\exefile\shell\runas\command (Default) REG_SZ "%1" %* IsolatedCommand REG_SZ "%1" %* On a related note, the old "runas.exe" console command lets you launch a process with the credentials of an administrator account. However, it can't 'elevate' the process. From eryksun at gmail.com Tue Apr 9 16:55:31 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 9 Apr 2013 10:55:31 -0400 Subject: [Tutor] How to make a python script run on startup In-Reply-To: References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com> <092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com> Message-ID: On Tue, Apr 9, 2013 at 9:48 AM, Kevin Ndung'u wrote: > > anybody know how to do this on linux? For a desktop environment that implements freedesktop.org standards (X Desktop Group), such as GNOME, KDE and Xfce, you can add .desktop files per user to "$HOME/.config/autostart". System wide it's "$XDG_CONFIG_DIRS/autostart". http://standards.freedesktop.org/autostart-spec/latest/ar01s02.html From brianjamesarb at gmail.com Tue Apr 9 17:32:03 2013 From: brianjamesarb at gmail.com (brian arb) Date: Tue, 9 Apr 2013 11:32:03 -0400 Subject: [Tutor] FYI: An Introduction to Interactive Programming in Python In-Reply-To: <516359B2.2040300@pearwood.info> References: <516359B2.2040300@pearwood.info> Message-ID: One game wrote along time ago when I was first learning Python and App Engine is http://cdacabeecdebcabab.appspot.com/ It's kind of a non-interactive Sudoku puzzle, the only really interaction is to click "solve this" or "display next puzzle" then to watch the python code written attempt to solve the puzzle you click on the button "next iteration" until you reach a solution or the code fails to resolve any more of the cells. On Mon, Apr 8, 2013 at 7:58 PM, Steven D'Aprano wrote: > On 09/04/13 06:38, brian arb wrote: > >> An Introduction to Interactive Programming in PythonJoe Warren, Scott >> >> Rixner, Stephen Wong and John Greiner >> >> This course is designed to be a fun introduction to the basics of >> programming in Python. Our main focus will be on building simple >> interactive games such as Pong, Blackjack and Asteroids. >> >> https://www.coursera.org/**course/interactivepython >> > > Thanks for the link Brian. > > As an aside, I wonder, apart from Conway's Game of Life, which isn't > actually a game at all, what's a non-interactive game? > > > > -- > Steven > ______________________________**_________________ > 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 Apr 9 18:29:03 2013 From: davea at davea.name (Dave Angel) Date: Tue, 09 Apr 2013 12:29:03 -0400 Subject: [Tutor] Flip a coin In-Reply-To: <1365508245.81711.YahooMailNeo@web161802.mail.bf1.yahoo.com> References: <1365508245.81711.YahooMailNeo@web161802.mail.bf1.yahoo.com> Message-ID: <516441CF.6070101@davea.name> On 04/09/2013 07:50 AM, Najam Us Saqib wrote: > Hi, > > This program is killing me, I have been working on it for last 3 hours, I have tried my best but can't make it work, please help me out. > > The Problem: > > Create a program that flips a coin 100 times and than tells you the number of tails and heads. > Nowhere does that say to ask the user for input, or even to wait for user input. So start with Miya's pseudo-code, remove the input stuff, and try to turn that into code. Keep it very simple till it works, then consider whether any fancy-ing-up is useful. -- DaveA From davea at davea.name Tue Apr 9 18:35:17 2013 From: davea at davea.name (Dave Angel) Date: Tue, 09 Apr 2013 12:35:17 -0400 Subject: [Tutor] How to make a python script run on startup In-Reply-To: <092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com> References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com> <092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com> Message-ID: <51644345.5020603@davea.name> On 04/09/2013 05:54 AM, Alexander Mark wrote: > On Apr 9, 2013, at 4:20, daedae11 wrote: > >> On Windows, how to make a python script run on startup? >> >> >> _ (Top-posted comment moved AFTER the question) > There is a startup folder, usually on the start menu, you can add the script to. > But does anything in the startup folder run BEFORE any user logs in? It's been a long time since I had to run Windows, but I didn't think so. -- DaveA From davea at davea.name Tue Apr 9 19:04:33 2013 From: davea at davea.name (Dave Angel) Date: Tue, 09 Apr 2013 13:04:33 -0400 Subject: [Tutor] How to make a python script run on startup In-Reply-To: <2957c1e7.178e3.13dee722c12.Coremail.daedae11@126.com> References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com> <5163DF94.1070107@davea.name> <2957c1e7.178e3.13dee722c12.Coremail.daedae11@126.com> Message-ID: <51644A21.80108@davea.name> On 04/09/2013 06:58 AM, daedae11 wrote: (Please don't top-post. And don't forget to include the list in your cc. I'm forwarding it for you) > Which module to should I use to add entries to that system scheduler? > > The system scheduler is an interactive (gui) program that comes with the OS. No idea what module would mean in this context. And I haven't run Windows in a long time, except for occasionally helping others. Every version of Windows does its best to move things around and confuse any administrative user. For XP, try: http://support.microsoft.com/kb/308569 and notice there's a distinction between "When my computer starts" and "When a user logs on" -- DaveA From wolfrage8765 at gmail.com Tue Apr 9 21:22:13 2013 From: wolfrage8765 at gmail.com (Jordan) Date: Tue, 09 Apr 2013 21:22:13 +0200 Subject: [Tutor] Impossible Else as Exception Message-ID: <51646A65.5080708@gmail.com> I want to know what exception should be raised if there is a bug in my code that allows an else statement to be triggered, because the else condition in my code should be impossible, unless there is an error in my code. What exception should I raise so that if my code is wrong it will raise an exception which will give me a trace back? Which would be most Pythonic? Example: if condition is 1: do something with 1 elif condition is 2: do something with 2 else: # Impossible unless the code above is flawed. Raise Exception From dyoo at hashcollision.org Tue Apr 9 21:26:37 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 9 Apr 2013 13:26:37 -0600 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: Side note: I would strongly suggest using the biopython libraries for the basic parsing. FASTA parsing has been done and replicated so many times that it's almost a hazing ritual for the practicing bioinformatician. The biopython folks have written a parser, so perhaps you can reuse it. http://biopython.org/wiki/Main_Page http://biopython.org/DIST/docs/tutorial/Tutorial.html#htoc11 About reading from either standard input or as command line arguments, see the 'fileinput' library: http://docs.python.org/3/library/fileinput.html It automatically handles reading either from sys.stdin, or by opening up the name of the file passed as a command line argument. From eryksun at gmail.com Tue Apr 9 21:41:15 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 9 Apr 2013 15:41:15 -0400 Subject: [Tutor] How to make a python script run on startup In-Reply-To: <51644345.5020603@davea.name> References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com> <092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com> <51644345.5020603@davea.name> Message-ID: On Tue, Apr 9, 2013 at 12:35 PM, Dave Angel wrote: > But does anything in the startup folder run BEFORE any user logs in? It's > been a long time since I had to run Windows, but I didn't think so. The contents of the startup folders are executed in the current session after logon. The same applies to run keys such as "HKLM\Software\Microsoft\Windows\CurrentVersion\Run". I wasn't taking "startup" to mean literally before any user has logged on. But yes, if that's the requirement, you can use the Task Scheduler service to start a program as a batch process in session 0 (or instead create your own service). Just as an FYI, in the "Home" versions of Windows the task scheduler can't store logon credentials, so to run at startup you have to use LOCALSERVICE or SYSTEM. To automate creating a task use the "schtasks" command. For example, to create a task named "Python" that runs python.exe at startup under the LOCALSERVICE account, execute the following from an elevated shell: schtasks /Create /TN Python /RU LOCALSERVICE /SC ONSTART /TR C:\Python33\python.exe This will run as a non-interactive service in session 0. There won't be a visible GUI or console window to interact with in your desktop session. From alan.gauld at btinternet.com Tue Apr 9 22:04:16 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 09 Apr 2013 21:04:16 +0100 Subject: [Tutor] FYI: An Introduction to Interactive Programming in Python In-Reply-To: <51640DF6.4060503@pearwood.info> References: <516359B2.2040300@pearwood.info> <516374DD.3060704@davea.name> <201304090521923.SM01804@W500.Go2France.com> <51640DF6.4060503@pearwood.info> Message-ID: On 09/04/13 13:47, Steven D'Aprano wrote: >> Since when did 30 become a representative sample size? > > If they are randomly selected, 30 is likely plenty for a representative > sample size. In surveys, a sample size of 30 gives you a margin of error > of about 15%, which isn't too bad. Hmm, if I'd gone to my manager (and especially the finance director) with a project proposal based on assumptions with a 15% margin they'd have thrown me out. And if I told them I'd developed 5 key assumptions based on that same proposal I'd probably have been fired! I'd be looking for something like 300+ samples for a project like this to claim that my 5 key principles were valid. And its not like there is a shortage of computer scientists to ask (although admittedly harder to find ones with no formal computer training)! > 1) it is likely to be a biased selection My suspicion is they just asked around their local department! But maybe I'm just overly suspicious... > 2) both computer scientists and educators are prone to fashions, and > Java is one such fashion. I don't care about the language since their 5 principles of learning are language independent. It was the idea that you could define 5 key principles needed to learn to program from a sample size of 30... If they came to me to peer review that I'd have been telling them to go back and do a bigger survey! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Tue Apr 9 22:07:27 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 09 Apr 2013 21:07:27 +0100 Subject: [Tutor] How to make a python script run on startup In-Reply-To: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com> References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com> Message-ID: On 09/04/13 09:20, daedae11 wrote: > On Windows, how to make a python script run on startup? The same way you make anything run on startup there is nothing magical about Python code. You can schedule it, add it to the registry or put it in the users startup folder if you want it at login rather than system start... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From breamoreboy at yahoo.co.uk Tue Apr 9 22:38:45 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 09 Apr 2013 21:38:45 +0100 Subject: [Tutor] Impossible Else as Exception In-Reply-To: <51646A65.5080708@gmail.com> References: <51646A65.5080708@gmail.com> Message-ID: On 09/04/2013 20:22, Jordan wrote: > I want to know what exception should be raised if there is a bug in my > code that allows an else statement to be triggered, because the else > condition in my code should be impossible, unless there is an error in > my code. What exception should I raise so that if my code is wrong it > will raise an exception which will give me a trace back? Which would be > most Pythonic? > > Example: > > if condition is 1: > do something with 1 > elif condition is 2: > do something with 2 > else: # Impossible unless the code above is flawed. > Raise Exception > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > The RuntimeError builtin see http://docs.python.org/3/library/exceptions.html#RuntimeError. -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From ramit.prasad at jpmorgan.com Tue Apr 9 22:58:49 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 9 Apr 2013 20:58:49 +0000 Subject: [Tutor] FYI: An Introduction to Interactive Programming in Python In-Reply-To: References: <516359B2.2040300@pearwood.info> <516374DD.3060704@davea.name> <201304090521923.SM01804@W500.Go2France.com> <51640DF6.4060503@pearwood.info> Message-ID: <5B80DD153D7D744689F57F4FB69AF474182BC593@SCACMX008.exchad.jpmchase.net> Alan Gauld wrote: > > On 09/04/13 13:47, Steven D'Aprano wrote: > > >> Since when did 30 become a representative sample size? > > > > If they are randomly selected, 30 is likely plenty for a representative > > sample size. In surveys, a sample size of 30 gives you a margin of error > > of about 15%, which isn't too bad. > > Hmm, if I'd gone to my manager (and especially the finance director) > with a project proposal based on assumptions with a 15% margin they'd > have thrown me out. And if I told them I'd developed 5 key assumptions > based on that same proposal I'd probably have been fired! I'd be looking > for something like 300+ samples for a project like this to claim that my > 5 key principles were valid. And its not like there is a shortage of > computer scientists to ask (although admittedly harder to find ones with > no formal computer training)! Well, 15% error margin is from statistics and provable, but the layman usually hears "30 people" and thinks "that's far too small". I certainly did it too. :) Error margins are one of those surprising things like the Birthday Problem (at least to me). Seems like it should not be true but it is. http://en.wikipedia.org/wiki/Birthday_problem Honestly, with surveys the method of the survey itself makes a difference. This includes things like question wording, question order, and even survey format (free form, multiple choice, etc). Much like scientific studies, I am more interested in *how* it was done than in some summarized (frequently sensationalized) "findings". In my opinion, a flawed methodology is more frequently a problem than a small sample size. > > > 1) it is likely to be a biased selection > > My suspicion is they just asked around their local department! > But maybe I'm just overly suspicious... Overly suspicious or concerned based on experience? :) ~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 silideba at gmail.com Tue Apr 9 23:23:21 2013 From: silideba at gmail.com (Debashish Saha) Date: Wed, 10 Apr 2013 02:53:21 +0530 Subject: [Tutor] Retrieving data from a text file Message-ID: In the following you can see data from a ephemeris.txt file. Now I want to retrieve several columns(say, for example the column starting with 00:00, 27.69 and 44.1) and name the array as x,y,z. What do I have to I tried this x, y, z = numpy.loadtxt("ephemeris.txt", unpack=True) And got this error "ValueError: could not convert string to float: Date__(UT)__HR:MN" Could you also help me in converting that HR:MN into minute only? Date__(UT)__HR:MN R.A.__(a-apparent)__DEC\ **********************************************\ 2013-Jan-01 00:00 * 14 31 27.69 -12 29 44.1\ 2013-Jan-01 00:01 * 14 31 27.71 -12 29 44.1\ 2013-Jan-01 00:02 * 14 31 27.72 -12 29 44.2\ 2013-Jan-01 00:03 * 14 31 27.73 -12 29 44.2\ 2013-Jan-01 00:04 * 14 31 27.75 -12 29 44.3\ 2013-Jan-01 00:05 * 14 31 27.76 -12 29 44.3\ 2013-Jan-01 00:06 * 14 31 27.77 -12 29 44.4\ 2013-Jan-01 00:07 * 14 31 27.78 -12 29 44.4\ 2013-Jan-01 00:08 * 14 31 27.80 -12 29 44.4\ 2013-Jan-01 00:09 * 14 31 27.81 -12 29 44.5\p -------------- next part -------------- An HTML attachment was scrubbed... URL: From bfishbein79 at gmail.com Tue Apr 9 23:31:23 2013 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Tue, 9 Apr 2013 16:31:23 -0500 Subject: [Tutor] building a website with python Message-ID: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com> Hello. I learned Python this past year (with help from many of you) and wrote many programs for my small business. Now I want to build a website. I acquired the domain name through godaddy.com (bookchicken.com) but have not found hosting yet. I learned html, css, and javascript via codeacademy.org, but have never built a website. I would like to build it with Python, and was wondering if you could give me some pointers about what I need to learn first: Django is the thing to use? And do I need specific hosting to use python or are all hosts basically the same. Thanks, Ben From ramit.prasad at jpmorgan.com Tue Apr 9 23:54:28 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 9 Apr 2013 21:54:28 +0000 Subject: [Tutor] building a website with python In-Reply-To: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com> References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com> Message-ID: <5B80DD153D7D744689F57F4FB69AF474182BD269@SCACMX008.exchad.jpmchase.net> Benjamin Fishbein wrote: > > Hello. I learned Python this past year (with help from many of you) and wrote many programs for my > small business. Now I want to build a website. I acquired the domain name through godaddy.com > (bookchicken.com) but have not found hosting yet. > I learned html, css, and javascript via codeacademy.org, but have never built a website. > I would like to build it with Python, and was wondering if you could give me some pointers about what > I need to learn first: Django is the thing to use? And do I need specific hosting to use python or are > all hosts basically the same. > Thanks, > Ben http://wiki.python.org/moin/WebFrameworks Lots of Python frameworks to choose from, though Django is the most famous/popular. There are lighter frameworks too, depending on what you need. Your hosting solution to support Python, and I do not believe all hosts support Python. You should double check with whatever host you choose. ~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 marc.tompkins at gmail.com Wed Apr 10 00:03:59 2013 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 9 Apr 2013 15:03:59 -0700 Subject: [Tutor] building a website with python In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474182BD269@SCACMX008.exchad.jpmchase.net> References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com> <5B80DD153D7D744689F57F4FB69AF474182BD269@SCACMX008.exchad.jpmchase.net> Message-ID: On Tue, Apr 9, 2013 at 2:54 PM, Prasad, Ramit wrote: > Your hosting solution (needs) to support Python, and I do not believe all > hosts support Python. You > should double check with whatever host you choose. > Almost all commercial web hosts offer limited Python support (running as an Apache module), but this is NOT sufficient to run the larger Python web frameworks, such as Django. What you need to check for is support for "long-running processes"; as of the last time I checked, GoDaddy, 1and1, and most of the budget hosts don't offer that - so no Django -------------- next part -------------- An HTML attachment was scrubbed... URL: From wprins at gmail.com Wed Apr 10 00:06:21 2013 From: wprins at gmail.com (Walter Prins) Date: Tue, 9 Apr 2013 23:06:21 +0100 Subject: [Tutor] building a website with python In-Reply-To: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com> References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com> Message-ID: Hello Benjamin, On 9 April 2013 22:31, Benjamin Fishbein wrote: > Hello. I learned Python this past year (with help from many of you) and > wrote many programs for my small business. Now I want to build a website. I > acquired the domain name through godaddy.com (bookchicken.com) but have > not found hosting yet. > I learned html, css, and javascript via codeacademy.org, but have never > built a website. > I would like to build it with Python, and was wondering if you could give > me some pointers about what I need to learn first: Django is the thing to > use? And do I need specific hosting to use python or are all hosts > basically the same. > Django is good but arguably big and a bit intimidating if you're starting out. There are many alternatives, from so called "micro" frameworks like "bottle" (which is implemented in a single Python file) to CherryPy to Flask. Personally, I'd suggest having a look at Web2Py. It's not quite as heavy as Django but very capable nonetheless. It also deploys easily, including to Google App Engine and elsewhere, and includes a very capable Admin interface that also includes a basic IDE, thus allowing you to tweak the site right from within the site should you have the need. Here's a nice little presentation about Web2Py: http://www.slideshare.net/blackthorne/web2pyweb-development-like-a-boss ... and a tutorial to get you going: http://killer-web-development.com/section/1/0 Not all web hosts are the same -- you need to ensure you have Python available with the host you use. There are dedicated Python hosts out there. (PythonAnywhere comes to mind.) As a slightly different possibility, you might consider running your own virtual host in the cloud. You would need to learn a bit about administering a server box, but this route does give you the ultimate control over your website and environment. Here's a link to Rackspace with which I've had good experiences thus far for your review: http://www.rackspace.com/cloud/servers/ Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Wed Apr 10 00:12:11 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Tue, 9 Apr 2013 23:12:11 +0100 Subject: [Tutor] Impossible Else as Exception In-Reply-To: <51646A65.5080708@gmail.com> References: <51646A65.5080708@gmail.com> Message-ID: On 9 April 2013 20:22, Jordan wrote: > I want to know what exception should be raised if there is a bug in my code > that allows an else statement to be triggered, because the else condition in > my code should be impossible, unless there is an error in my code. What > exception should I raise so that if my code is wrong it will raise an > exception which will give me a trace back? Which would be most Pythonic? > > Example: > > if condition is 1: > do something with 1 > elif condition is 2: > do something with 2 > else: # Impossible unless the code above is flawed. > Raise Exception AssertionError is raised when an assert statement fails. Since this situation is essentially an implicit assert it would make sense to use that. Oscar From eire1130 at gmail.com Wed Apr 10 00:58:39 2013 From: eire1130 at gmail.com (James Reynolds) Date: Tue, 9 Apr 2013 18:58:39 -0400 Subject: [Tutor] building a website with python In-Reply-To: References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com> Message-ID: As far as hosts, I use digital ocean. It's a cloud based thing like EC2, but it's cheap (5/10/20 and up). You will of course have to configure everything yourself, but that's not such a bad thing. It will give you good experience configuring a linux box as well and learning about deployment. Since I'm a django developer, I'm going to suggest you learn that of course. But, there are others out there. However, with Django you get the Django eco system, which is large and very helpful. For example, you can use fabric for easy deployment, south for database migrations, celery for task management and so and so forth. Even simple websites could find some use in south and fabric. On Tue, Apr 9, 2013 at 6:06 PM, Walter Prins wrote: > Hello Benjamin, > > On 9 April 2013 22:31, Benjamin Fishbein wrote: > >> Hello. I learned Python this past year (with help from many of you) and >> wrote many programs for my small business. Now I want to build a website. I >> acquired the domain name through godaddy.com (bookchicken.com) but have >> not found hosting yet. >> I learned html, css, and javascript via codeacademy.org, but have never >> built a website. >> I would like to build it with Python, and was wondering if you could give >> me some pointers about what I need to learn first: Django is the thing to >> use? And do I need specific hosting to use python or are all hosts >> basically the same. >> > > Django is good but arguably big and a bit intimidating if you're starting > out. There are many alternatives, from so called "micro" frameworks like > "bottle" (which is implemented in a single Python file) to CherryPy to > Flask. Personally, I'd suggest having a look at Web2Py. It's not quite as > heavy as Django but very capable nonetheless. It also deploys easily, > including to Google App Engine and elsewhere, and includes a very capable > Admin interface that also includes a basic IDE, thus allowing you to tweak > the site right from within the site should you have the need. Here's a nice > little presentation about Web2Py: > http://www.slideshare.net/blackthorne/web2pyweb-development-like-a-boss > ... and a tutorial to get you going: > http://killer-web-development.com/section/1/0 > > Not all web hosts are the same -- you need to ensure you have Python > available with the host you use. There are dedicated Python hosts out > there. (PythonAnywhere comes to mind.) As a slightly different > possibility, you might consider running your own virtual host in the cloud. > You would need to learn a bit about administering a server box, but this > route does give you the ultimate control over your website and environment. > Here's a link to Rackspace with which I've had good experiences thus far > for your review: > http://www.rackspace.com/cloud/servers/ > > Walter > > _______________________________________________ > 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 Wed Apr 10 01:14:12 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Apr 2013 00:14:12 +0100 Subject: [Tutor] Impossible Else as Exception In-Reply-To: <51646A65.5080708@gmail.com> References: <51646A65.5080708@gmail.com> Message-ID: On 09/04/13 20:22, Jordan wrote: > I want to know what exception should be raised if there is a bug in my > code that allows an else statement to be triggered, because the else > condition in my code should be impossible, class BuggyCodeError(StandardError): pass Maybe? Seriously, exceptions are not intended for handling buggy code. You should be removing the bugs using assertions and tests. The exception to raise is whatever is appropriate to how you got into that else and that depends on the nature of the conditions. One option might be a ValueError or maybe an IOError. I'm not sure I agree with the suggestion to use AssertionError because that implies it came from an assertion. I'd rather define a bespoke error class than use that. > if condition is 1: > do something with 1 > elif condition is 2: > do something with 2 > else: # Impossible unless the code above is flawed. > Raise Exception If its really impossible for the condition to be anything other than 1 or 2 then an elif should not be needed. If it is possible to get another value think about what causes could exist to get the other value ( even if it is a code error!!) and describe the cause(s). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Wed Apr 10 01:52:40 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 10 Apr 2013 09:52:40 +1000 Subject: [Tutor] Impossible Else as Exception In-Reply-To: <51646A65.5080708@gmail.com> References: <51646A65.5080708@gmail.com> Message-ID: <5164A9C8.6060405@pearwood.info> On 10/04/13 05:22, Jordan wrote: > I want to know what exception should be raised if there is a bug in my code that allows an else statement to be triggered, because the else condition in my code should be impossible, unless there is an error in my code. What exception should I raise so that if my code is wrong it will raise an exception which will give me a trace back? Which would be most Pythonic? > > Example: > > if condition is 1: > do something with 1 > elif condition is 2: > do something with 2 > else: # Impossible unless the code above is flawed. > Raise Exception The above isn't a great example, because the sample code *is* flawed. The short reason why it is flawed is this: You use identity tests (using `is`) instead of equality tests (using `==`) which makes the above code fragile and dependent on the exact version and implementation of Python being used. There are two rules for when to use `is`: 1) Only use `is` when comparing to None; 2) (For everything else) If you have to ask if you should use `is`, the answer is No. As given, your question cannot be answered simply. It depends on the circumstances. Here are the two most common cases: 1) You're testing data you receive from a user, the caller, or another part of the program. You know what the data should be, but you can't be sure that it will be. Here's a toy example: def func(n): """Do something useful. Argument n must be 1 or 2.""" if n == 1: do_this() elif n == 2: do_that() else: # Y U No Listen? I told you that n must be 1 or 2! ... So what should I put in place of the dots? The answer depends on the exact tests being performed, but the two most common cases are: ValueError, if the argument has the wrong value; TypeError, if the argument has the wrong type. In this case, I would go with ValueError: else: raise ValueError('n must be 1 or 2, not %r' % n) 1) You're testing the *internal logic* of your code. In this case, you're sure of what the data will be, but out of some tiny lingering doubt that maybe *you* have made a mistake, you want to check just to be sure. Here is a toy example: def spam(n): """Returns 'spam' n times. Guarantees to return spam.""" if n <= 0: n = 1 return ' '.join(['spam']*n) def breakfast(hunger=3): s = "toast and %s and eggs" % spam(hunger) if "spam" in s: # This should always be true. return s else: # This can never happen! raise RuntimeError('no spam in breakfast? yuck!') So RuntimeError is a good choice for this. But if you are *sure* that the error condition can *never* happen, but not *absolutely sure* and you still want to check just in case you're mistaken, then an even better way to write it is: def breakfast(hunger=3): s = "toast and %s and eggs" % spam(hunger) assert "spam" in s, 'no spam in breakfast? yuck!' return s -- Steven From steve at pearwood.info Wed Apr 10 01:56:53 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 10 Apr 2013 09:56:53 +1000 Subject: [Tutor] FYI: An Introduction to Interactive Programming in Python In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474182BC593@SCACMX008.exchad.jpmchase.net> References: <516359B2.2040300@pearwood.info> <516374DD.3060704@davea.name> <201304090521923.SM01804@W500.Go2France.com> <51640DF6.4060503@pearwood.info> <5B80DD153D7D744689F57F4FB69AF474182BC593@SCACMX008.exchad.jpmchase.net> Message-ID: <5164AAC5.9020404@pearwood.info> On 10/04/13 06:58, Prasad, Ramit wrote: > Much like scientific studies, I am more interested in *how* it > was done than in some summarized (frequently sensationalized) > "findings". In my opinion, a flawed methodology is more > frequently a problem than a small sample size. +1000 on that. -- Steven From steve at pearwood.info Wed Apr 10 02:15:35 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 10 Apr 2013 10:15:35 +1000 Subject: [Tutor] FYI: An Introduction to Interactive Programming in Python In-Reply-To: References: <516359B2.2040300@pearwood.info> <516374DD.3060704@davea.name> <201304090521923.SM01804@W500.Go2France.com> <51640DF6.4060503@pearwood.info> Message-ID: <5164AF27.3050506@pearwood.info> On 10/04/13 06:04, Alan Gauld wrote: > On 09/04/13 13:47, Steven D'Aprano wrote: > >>> Since when did 30 become a representative sample size? >> >> If they are randomly selected, 30 is likely plenty for a representative >> sample size. In surveys, a sample size of 30 gives you a margin of error >> of about 15%, which isn't too bad. > > Hmm, if I'd gone to my manager (and especially the finance director) with a project proposal based on assumptions with a 15% margin they'd have thrown me out. The 15% figure comes from surveys where people are asked to rate something on some scale, say from 1 to 7. If your sample of 30 gives an average rating of 5, then a 15% margin of error corresponds to plus or minus 1: the true average is likely to be 4, 5 or 6. Given that the question being asking is fundamentally subjective, and you have no idea whether Fred's rating of 5 and Wilma's rating of 5 mean the same thing, I think that plus or minus 1 is pretty much as good as you can reasonably expect. Additional samples just adds spurious precision that looks good but doesn't *mean* anything. But what do I know? :) > My suspicion is they just asked around their local department! > But maybe I'm just overly suspicious... Nah, I reckon you've hit the nail right on the head. -- Steven From dyoo at hashcollision.org Wed Apr 10 02:17:41 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Tue, 9 Apr 2013 18:17:41 -0600 Subject: [Tutor] Impossible Else as Exception In-Reply-To: <5164A9C8.6060405@pearwood.info> References: <51646A65.5080708@gmail.com> <5164A9C8.6060405@pearwood.info> Message-ID: >> if condition is 1: >> do something with 1 >> elif condition is 2: >> do something with 2 >> else: # Impossible unless the code above is flawed. >> Raise Exception > > > > The above isn't a great example, because the sample code *is* flawed. > The short reason why it is flawed is this: > > You use identity tests (using `is`) instead of equality tests (using > `==`) which makes the above code fragile and dependent on the exact > version and implementation of Python being used. I don't think we can say this. The code above is not literal. Otherwise, we should be technically obligated to raise the exact same objection to "do something with 2". Going back to the original question: perhaps an assertion here would be sufficient. Something like: assert False, "Impossible situation" would document that the case analysis above should be technically exhaustive, and that reaching the assertion should be treated as an internal error. From steve at pearwood.info Wed Apr 10 02:17:55 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 10 Apr 2013 10:17:55 +1000 Subject: [Tutor] building a website with python In-Reply-To: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com> References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com> Message-ID: <5164AFB3.6090200@pearwood.info> On 10/04/13 07:31, Benjamin Fishbein wrote: > Hello. I learned Python this past year (with help from many of you) and wrote many programs for my small business. Now I want to build a website. I acquired the domain name through godaddy.com (bookchicken.com) but have not found hosting yet. > I learned html, css, and javascript via codeacademy.org, but have never built a website. > I would like to build it with Python, and was wondering if you could give me some pointers about what I need to learn first: Django is the thing to use? And do I need specific hosting to use python or are all hosts basically the same. Django is an excellent product but pretty heavyweight. Consider CherryPy for a lighter experience with a more gentle learning curve. http://www.cherrypy.org/ -- Steven From alan.gauld at btinternet.com Wed Apr 10 02:29:57 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 10 Apr 2013 01:29:57 +0100 (BST) Subject: [Tutor] Chapter 3 Projects In-Reply-To: <1365552412.1498.YahooMailNeo@web141006.mail.bf1.yahoo.com> References: <1364168328.77990.YahooMailNeo@web141005.mail.bf1.yahoo.com> <1365552412.1498.YahooMailNeo@web141006.mail.bf1.yahoo.com> Message-ID: <1365553797.57250.YahooMailNeo@web186001.mail.ir2.yahoo.com> Forwarded to group. Please use ReplyAll when responding to tutor posts. >________________________________ > From: Mariel Jane Sanchez >To: Alan Gauld >Sent: Wednesday, 10 April 2013, 1:06 >Subject: Re: [Tutor] Chapter 3 Projects > > > >Thank you so much, I finally figured out the 2nd project. I still have problems with 1 and 3 so I'll try to be more clear.? > >It would help if you posted your code. It shouldn't be long?and its much easier to see where you are getting confused if we can see the code! Chapter 3 Booklet PDF is attached > >Chapter 3? >Project 1 on page 90 on the PDF >"1. Write a program that gets a score from the player and rates it on the following: >- Given a score between 0-999, the program should display the message, 'Nothing to brag about." >- Given a score between 1000-9999, the program should display the message, 'Good score.' >- Given a score over 9999, the program should display the message, 'Very impressive!" >- If the score is a negative number, the program should display the message, 'That is not a legal score!'" > >I'd do it like this score = raw_input('score? ') if score < 0: print 'That is not a legal score' elif score > 9999: print 'Very impressive' elif 9999 >= score >= 1000: print 'Good score.' elif # student to complete... > >I tried using range as another tutor suggested which would make sense since it's dealing with ranges but I still get the same result as before. Can you explain how to do this step by step, if you don't mind? > >You can use range by substituting the elif lines above with: elif score in range(1000,10000): print 'Good score.' Project 3 (Guess My Number code on page 35) >"Modify the Guess My Number program from the chapter so that the player has only five guesses. If the player runs out of guesses, the program should end the game and display an appropriately chastising message" >For my case, I somehow, accidentally programmed it to have only 5 tries and also put a message that says " You ran out of tries," which I think is a good progress. However, on the last try; when I put my guess, hit enter and got the guess wrong, the message loops.? > >I ?showed you the structure for this last time. Without seeing your code I have no idea what?you did wrong. When you first started on Python, how did you do this project so there's no loop at the end? > >I did not do those projects because I did not do the course that?you are doing.? I did not in fact do any courses, I just read the official documents and made? up my own projects. So I can't tell you how I did it. I can only comment on how I might? do it now. ? Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Wed Apr 10 02:43:59 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 9 Apr 2013 20:43:59 -0400 Subject: [Tutor] Impossible Else as Exception In-Reply-To: References: <51646A65.5080708@gmail.com> <5164A9C8.6060405@pearwood.info> Message-ID: On Tue, Apr 9, 2013 at 8:17 PM, Danny Yoo wrote: > > Going back to the original question: perhaps an assertion here would > be sufficient. Something like: > > assert False, "Impossible situation" Like "if __debug__" statements, assert statements are skipped by the compiler if optimization is enabled. If you want an AssertionError here even for optimized code, then explicitly raise AssertionError('Impossible situation'). From dfjennings at gmail.com Wed Apr 10 04:03:27 2013 From: dfjennings at gmail.com (Don Jennings) Date: Tue, 9 Apr 2013 22:03:27 -0400 Subject: [Tutor] building a website with python In-Reply-To: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com> References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com> Message-ID: On Apr 9, 2013, at 5:31 PM, Benjamin Fishbein wrote: > Hello. I learned Python this past year (with help from many of you) and wrote many programs for my small business. Now I want to build a website. I acquired the domain name through godaddy.com (bookchicken.com) but have not found hosting yet. > I learned html, css, and javascript via codeacademy.org, but have never built a website. > I would like to build it with Python, So, are you really just wanting to use python to build a static site? If so, you can run a python web framework on your local machine and then deploy the static files to any decent host you find. For example, there are instructions for setting up this scenario using flask, jinja2 and markdown[1]. If you have experience with ReStructuredText (here's a comparison of the two markups [2]), it's fairly easy to use docutils to produce the html files. > and was wondering if you could give me some pointers about what I need to learn first: Django is the thing to use? And do I need specific hosting to use python or are all hosts basically the same. If you do want python web apps, I've had pleasant results from webfaction.com (though I don't do anything terribly difficult :>). You've gotten some good feedback, but I suspect you will get better information if you provide more information about your goals for the site. Take care, Don [1] https://nicolas.perriault.net/code/2012/dead-easy-yet-powerful-static-website-generator-with-flask/ [2] http://www.unexpected-vortices.com/doc-notes/markdown-and-rest-compared.html From doanviettrung at gmail.com Wed Apr 10 04:29:55 2013 From: doanviettrung at gmail.com (DoanVietTrungAtGmail) Date: Wed, 10 Apr 2013 12:29:55 +1000 Subject: [Tutor] Set Reply-To field to Tutor@python.org In-Reply-To: References: <510721b3.4553420a.4681.fffff522@mx.google.com> <1359474293.64460.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: FWIW, I'd like to reverse my answer, and now I agree with Oscar's 29 Jan suggestion to make "Reply-to-tutor-list" the default. Lately, several times a tutor had to forward to the list an email meant for the list but sent to him only, by mistake. On the other hand, the wrote-to-1-person-but-mistakenly-sent-to-list scenario that I had in mind is rarer, therefore Oscar's suggestion is better than my previous reply. Trung On Wed, Jan 30, 2013 at 6:33 AM, Nick W wrote: > My personal opinion (with whatever limited weight that has on this list > since I've only answered a few questions - and probably half of them I've > accidentally only sent to the op)/how I read it is that RFC 2822 actually > allows lists to set reply-to header; by my view the list software is > forwarding to everyone else and therefor counts as the most recent > sender/author. I admit that that is a somewhat different conclusion to > others that I've read as to the meaning of 2822, but that seems logical to > me and also my personal preference is for having the reply-to header be set > to the list address. > Nick > > > On Tue, Jan 29, 2013 at 7:44 AM, Albert-Jan Roskam wrote: > >> >> >> > >> > To summarize existing opinions on this matter: >> > >> > http://marc.merlins.org/netrants/listreplyto.html >> > >> > You might want to familiarize yourself with existing literature on the >> > matter before starting a new flame war. >> >> Hmmm... False alarm? >> >> Page blocked >> >> The page you've been trying to access was blocked. >> Reason: Access Denied! The requested URL is a Spyware site. >> Transaction ID is 5107F01CFF920603D57F. >> _______________________________________________ >> 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 amitsaha.in at gmail.com Wed Apr 10 04:38:40 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Wed, 10 Apr 2013 12:38:40 +1000 Subject: [Tutor] building a website with python In-Reply-To: References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com> Message-ID: On Wed, Apr 10, 2013 at 12:03 PM, Don Jennings wrote: > > On Apr 9, 2013, at 5:31 PM, Benjamin Fishbein wrote: > >> Hello. I learned Python this past year (with help from many of you) and wrote many programs for my small business. Now I want to build a website. I acquired the domain name through godaddy.com (bookchicken.com) but have not found hosting yet. >> I learned html, css, and javascript via codeacademy.org, but have never built a website. >> I would like to build it with Python, > > So, are you really just wanting to use python to build a static site? If so, you can run a python web framework on your local machine and then deploy the static files to any decent host you find. For example, there are instructions for setting up this scenario using flask, jinja2 and markdown[1]. If you have experience with ReStructuredText (here's a comparison of the two markups [2]), it's fairly easy to use docutils to produce the html files. Good suggestion. I wrote this article showing how you can do that using Sphinx. Please take a look [1]. The advantage of using something like Sphinx is that it gives you static HTML, which you can simply copy and paste. As you will see in the article, it is also very easy to upload your HTML to GitHub pages. [1] http://amitsaha.github.io/site/notes/articles/sphinx/static_html.html Hope it is a solution which suits you. Also, getting familiar with Sphinx may also help you in your future Python projects - since it is *the* de-facto standard for documenting Python projects. Best, Amit. -- http://amitsaha.github.com/ From amitsaha.in at gmail.com Wed Apr 10 04:47:09 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Wed, 10 Apr 2013 12:47:09 +1000 Subject: [Tutor] building a website with python In-Reply-To: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com> References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com> Message-ID: On Wed, Apr 10, 2013 at 7:31 AM, Benjamin Fishbein wrote: > Hello. I learned Python this past year (with help from many of you) and wrote many programs for my small business. Now I want to build a website. I acquired the domain name through godaddy.com (bookchicken.com) but have not found hosting yet. > I learned html, css, and javascript via codeacademy.org, but have never built a website. > I would like to build it with Python, and was wondering if you could give me some pointers about what I need to learn first: Django is the thing to use? And do I need specific hosting to use python or are all hosts basically the same. Django is great, but like others have suggested, so called "micro" frameworks may be a good start. I personally would suggest Flask [1]. The documentation is extensive and excellent. [1] http://flask.pocoo.org/docs/ -Amit. -- http://amitsaha.github.com/ From amitsaha.in at gmail.com Wed Apr 10 04:50:34 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Wed, 10 Apr 2013 12:50:34 +1000 Subject: [Tutor] building a website with python In-Reply-To: References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com> Message-ID: On Wed, Apr 10, 2013 at 12:47 PM, Amit Saha wrote: > On Wed, Apr 10, 2013 at 7:31 AM, Benjamin Fishbein > wrote: >> Hello. I learned Python this past year (with help from many of you) and wrote many programs for my small business. Now I want to build a website. I acquired the domain name through godaddy.com (bookchicken.com) but have not found hosting yet. >> I learned html, css, and javascript via codeacademy.org, but have never built a website. >> I would like to build it with Python, and was wondering if you could give me some pointers about what I need to learn first: Django is the thing to use? And do I need specific hosting to use python or are all hosts basically the same. > > Django is great, but like others have suggested, so called "micro" > frameworks may be a good start. I personally would suggest Flask [1]. > The documentation is extensive and excellent. > > > [1] http://flask.pocoo.org/docs/ And, I will add Frozen-Flask (http://pythonhosted.org/Frozen-Flask/), which basically gives you a set of static files, which you can just dump on any host with no "special" features. I haven't tried it myself, though. -Amit. -- http://amitsaha.github.com/ From bfishbein79 at gmail.com Wed Apr 10 05:07:51 2013 From: bfishbein79 at gmail.com (Benjamin Fishbein) Date: Tue, 9 Apr 2013 22:07:51 -0500 Subject: [Tutor] building a website with python In-Reply-To: References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com> Message-ID: > > You've gotten some good feedback, but I suspect you will get better information if you provide more information about your goals for the site. > Thanks for your help, everyone. There are some specific things I want the site to do, and I'm not sure which would be the best developing tool or hosting for these. The python software I developed is for selling used books. It takes book ISBN numbers as input and returns the best prices being offered. It uses the selenium module...I'm not sure how that would translate into a website. There are many websites that offer similar book price comparisons, but mine is different...it's user-friendly. Any volunteer at a thrift shop or library can use it...just a series of simple directions and yes/no questions, taking the user all the way from scanning or typing in an ISBN to dropping the parcel off at the post office. (The local libraries I worked with more than doubled their used-book revenues.) I want to expand this nationwide, and bookchicken.com seems to be the way to do it. So much of the program is simple enough. But there's two parts of the program that I anticipate being important to what host, development tool I use: 1. ISBNs (the books the thrift shop/ library has) being sent to various websites and returning the data to my site to be analyzed by my program. 2. Maneuvering through the website of the company buying the books. I don't want to send the user off to a warehouse's site with a list of books to sell to them. They'll still be entering their address and name, but it'll be on my site, that I then send to the warehouse's page, get a packing slip and shipping label from the warehouse, and give these documents to the user to print out. I'm not sure if this changes anyone's ideas about which host/ developer I should use. Please let me know. Thanks, Ben From davea at davea.name Wed Apr 10 05:11:40 2013 From: davea at davea.name (Dave Angel) Date: Tue, 09 Apr 2013 23:11:40 -0400 Subject: [Tutor] Chapter 3 Projects In-Reply-To: <1365553797.57250.YahooMailNeo@web186001.mail.ir2.yahoo.com> References: <1364168328.77990.YahooMailNeo@web141005.mail.bf1.yahoo.com> <1365552412.1498.YahooMailNeo@web141006.mail.bf1.yahoo.com> <1365553797.57250.YahooMailNeo@web186001.mail.ir2.yahoo.com> Message-ID: <5164D86C.80107@davea.name> On 04/09/2013 08:29 PM, ALAN GAULD wrote: > Forwarded to group. Please use ReplyAll when responding to tutor posts. > > >> ________________________________ >> From: Mariel Jane Sanchez >> To: Alan Gauld >> Sent: Wednesday, 10 April 2013, 1:06 >> Subject: Re: [Tutor] Chapter 3 Projects >> >> >> >> Thank you so much, I finally figured out the 2nd project. I still have problems with 1 and 3 so I'll try to be more clear. >> >> It would help if you posted your code. It shouldn't be long and its much easier to see where you are getting confused if we can see the code! > Chapter 3 Booklet PDF is attached >> >> Chapter 3 >> Project 1 on page 90 on the PDF >> "1. Write a program that gets a score from the player and rates it on the following: >> - Given a score between 0-999, the program should display the message, 'Nothing to brag about." >> - Given a score between 1000-9999, the program should display the message, 'Good score.' >> - Given a score over 9999, the program should display the message, 'Very impressive!" >> - If the score is a negative number, the program should display the message, 'That is not a legal score!'" >> >> I'd do it like this > > score = raw_input('score? ') That would need to be: score = int(raw_input('score? ') > if score < 0: print 'That is not a legal score' > elif score > 9999: print 'Very impressive' > elif 9999 >= score >= 1000: print 'Good score.' > elif # student to complete... > > >> >> I tried using range as another tutor suggested which would make sense since it's dealing with ranges but I still get the same result as before. Can you explain how to do this step by step, if you don't mind? >> >> You can use range by substituting the elif lines above with: > > elif score in range(1000,10000): print 'Good score.' > > Project 3 (Guess My Number code on page 35) >> "Modify the Guess My Number program from the chapter so that the player has only five guesses. If the player runs out of guesses, the program should end the game and display an appropriately chastising message" >> For my case, I somehow, accidentally programmed it to have only 5 tries and also put a message that says " You ran out of tries," which I think is a good progress. However, on the last try; when I put my guess, hit enter and got the guess wrong, the message loops. >> >> I showed you the structure for this last time. > Without seeing your code I have no idea what you did wrong. > > > When you first started on Python, how did you do this project so there's no loop at the end? >> >> I did not do those projects because I did not do the course that you are doing. > I did not in fact do any courses, I just read the official documents and made > up my own projects. So I can't tell you how I did it. I can only comment on how I might > do it now. > > Alan Gauld > Author of the Learn To Program website > > 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 > -- DaveA From wolfrage8765 at gmail.com Wed Apr 10 08:18:28 2013 From: wolfrage8765 at gmail.com (Jordan) Date: Wed, 10 Apr 2013 08:18:28 +0200 Subject: [Tutor] Impossible Else as Exception In-Reply-To: References: <51646A65.5080708@gmail.com> <5164A9C8.6060405@pearwood.info> Message-ID: <51650434.5020906@gmail.com> Thank you all for the feedback and suggestions. I have never used an assertion, before so I will read up on the concept. But this last email about the optimizations makes me want to go with an AssertionError exception, since assert is skipped if the compiler is told to optimize. Alan you are right, the code should be better tested, but test driven development seems like it would take me forever to complete even small tasks, there is so much to be tested. I have limited time to program with my wife and kids, but do you think test driven development is still the way to go? On 04/10/2013 02:43 AM, eryksun wrote: > On Tue, Apr 9, 2013 at 8:17 PM, Danny Yoo wrote: >> Going back to the original question: perhaps an assertion here would >> be sufficient. Something like: >> >> assert False, "Impossible situation" > Like "if __debug__" statements, assert statements are skipped by the > compiler if optimization is enabled. If you want an AssertionError > here even for optimized code, then explicitly raise > AssertionError('Impossible situation'). > _______________________________________________ > 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 Wed Apr 10 10:10:16 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Apr 2013 09:10:16 +0100 Subject: [Tutor] Impossible Else as Exception In-Reply-To: <51650434.5020906@gmail.com> References: <51646A65.5080708@gmail.com> <5164A9C8.6060405@pearwood.info> <51650434.5020906@gmail.com> Message-ID: On 10/04/13 07:18, Jordan wrote: > Alan you are right, the code should be better tested, but test driven > development seems like it would take me forever to complete even small > tasks, there is so much to be tested. I have limited time to program > with my wife and kids, but do you think test driven development is still > the way to go? Do you want to spend your time writing tests that identify bugs immediately or spend your time debugging code after you've written it and every time you modify it? A lot depends on how often you will be going back to the code in the future. If this is a use once throw away project then TDD may be overkill. If you are likely to want to enhance it in the future TDD is an investment to save time. I confess I don't use TDD all of the time and even with TDD errors will still sneak through. But TDD improves your chances of finding them early considerably. It will usually take the same amount of total time, its just a question of how you use it. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Apr 10 10:14:13 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Apr 2013 09:14:13 +0100 Subject: [Tutor] Chapter 3 Projects In-Reply-To: <5164D86C.80107@davea.name> References: <1364168328.77990.YahooMailNeo@web141005.mail.bf1.yahoo.com> <1365552412.1498.YahooMailNeo@web141006.mail.bf1.yahoo.com> <1365553797.57250.YahooMailNeo@web186001.mail.ir2.yahoo.com> <5164D86C.80107@davea.name> Message-ID: On 10/04/13 04:11, Dave Angel wrote: >>> I'd do it like this >> >> score = raw_input('score? ') > > That would need to be: > score = int(raw_input('score? ') Oops, yes. Good catch. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From arijit.ukil at tcs.com Wed Apr 10 10:57:17 2013 From: arijit.ukil at tcs.com (Arijit Ukil) Date: Wed, 10 Apr 2013 14:27:17 +0530 Subject: [Tutor] running python from windows command prompt In-Reply-To: References: Message-ID: I like to run a python program "my_python.py" from windows command prompt. This program ( a function called testing) takes input as block data (say data = [1,2,3,4] and outputs processed single data. import math def avrg(data): return sum(data)/len(data) def testing (data): val = avrg(data) out = pow(val,2) return out Pls 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 davea at davea.name Wed Apr 10 13:52:30 2013 From: davea at davea.name (Dave Angel) Date: Wed, 10 Apr 2013 07:52:30 -0400 Subject: [Tutor] Impossible Else as Exception In-Reply-To: <51650434.5020906@gmail.com> References: <51646A65.5080708@gmail.com> <5164A9C8.6060405@pearwood.info> <51650434.5020906@gmail.com> Message-ID: <5165527E.8040003@davea.name> On 04/10/2013 02:18 AM, Jordan wrote: > Thank you all for the feedback and suggestions. I have never used an > assertion, before so I will read up on the concept. One comment about assertion. Even though an optimized run will ignore the assertion itself, it can save a (small) amount of time avoiding any other overhead "preparing" for the assertion. So I'd make your if/elif logic something like this: if condition == 1: do something with 1 else: #Note, condition must be 2, unless something above is flawed assert(condition==2, "Condition must be 1 or 2, something's wrong") do something with 2 One more comment I didn't notice anybody else point out. Many times, instead of hoping the code remains consistent, you can make it much more likely by changing types. For example, instead of naming the conditions 1 and 2, name then True and False. Now, the test becomes: if condition: do something with 1 else: do something with 2 This isn't as perfect an answer as with typed languages, because somebody can slip in some other type. -- DaveA From davea at davea.name Wed Apr 10 14:14:21 2013 From: davea at davea.name (Dave Angel) Date: Wed, 10 Apr 2013 08:14:21 -0400 Subject: [Tutor] running python from windows command prompt In-Reply-To: References: Message-ID: <5165579D.4090609@davea.name> (Please don't hijack a thread with an unrelated question. You're no doing yourself any favors, as any decent thread-viewer will hide your new subject line, and group the whole thread with its original title. That can cause your query to be ignored by many of the readers.) To start a new thread, send the email to tutor at pyhon.org. On 04/10/2013 04:57 AM, Arijit Ukil wrote: > I like to run a python program "my_python.py" from windows command > prompt. This program ( a function called testing) takes input as block > data (say data = [1,2,3,4] and outputs processed single data. > > import math > > def avrg(data): > return sum(data)/len(data) > > def testing (data): > val = avrg(data) > out = pow(val,2) > return out > This program is missing some top-level code, so nobody is calling testing(). As it stands, it does nothing visible to the user. You say the program should "take input" from the user, but there are at least 3 ways to do that. 1) The user could edit the source file, adding lines like: mydata = (1, 9,43,7) print ("results: %d" % testing(mydata) ) 2) The user could put the source data into a file, such as a csv file 3) The user could have the parameters on the command line, after the script name. python my_python.py 1 9 43 7 Each of 2 and 3 require you to add some logic to process the data file and/or commandline. Please specify the problem more completely, and show us what you tried, and somebody will probably be able to help you. Also specify the Python version, as it can make a difference. For example, avrg() function in Python 2.7 assumes either that its arguments include a float, or that you want only an integer result. In Python 3, it'll switch to float. -- DaveA From arijit.ukil at tcs.com Wed Apr 10 14:32:47 2013 From: arijit.ukil at tcs.com (Arijit Ukil) Date: Wed, 10 Apr 2013 18:02:47 +0530 Subject: [Tutor] Running python from windows command prompt Message-ID: I like to run a python program "my_python.py" from windows command prompt. This program ( a function called testing) takes input as block data (say data = [1,2,3,4] and outputs processed single data. import math def avrg(data): return sum(data)/len(data) def testing (data): val = avrg(data) out = pow(val,2) return out I am using python 2.6. My intention is to run from windows command prompt as python my_python.py 1 3 2 However I am getting error: No such file in the directory, Errno 21 Pls 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 amitsaha.in at gmail.com Wed Apr 10 14:37:06 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Wed, 10 Apr 2013 22:37:06 +1000 Subject: [Tutor] Running python from windows command prompt In-Reply-To: References: Message-ID: On Wed, Apr 10, 2013 at 10:32 PM, Arijit Ukil wrote: > I like to run a python program "my_python.py" from windows command prompt. > This program ( a function called testing) takes input as block data (say > data = [1,2,3,4] and outputs processed single data. > > import math > > def avrg(data): > return sum(data)/len(data) > > def testing (data): > val = avrg(data) > out = pow(val,2) > return out > > I am using python 2.6. My intention is to run from windows command prompt as Why not Python 2.7 or Python 3.3 ? > > python my_python.py 1 3 2 > > However I am getting error: No such file in the directory, Errno 21 Have you set the Windows Path variable correctly? Do you see IDLE in your programs menu? -Amit. -- http://amitsaha.github.com/ From amitsaha.in at gmail.com Wed Apr 10 14:43:18 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Wed, 10 Apr 2013 22:43:18 +1000 Subject: [Tutor] Running python from windows command prompt In-Reply-To: References: Message-ID: On Wed, Apr 10, 2013 at 10:32 PM, Arijit Ukil wrote: > I like to run a python program "my_python.py" from windows command prompt. > This program ( a function called testing) takes input as block data (say > data = [1,2,3,4] and outputs processed single data. > > import math > > def avrg(data): > return sum(data)/len(data) > > def testing (data): > val = avrg(data) > out = pow(val,2) > return out > > I am using python 2.6. My intention is to run from windows command prompt as > > python my_python.py 1 3 2 I am hoping this is not your complete program. What tutorial are you following? Can you please paste complete programs? -Amit. -- http://amitsaha.github.com/ From davea at davea.name Wed Apr 10 14:50:44 2013 From: davea at davea.name (Dave Angel) Date: Wed, 10 Apr 2013 08:50:44 -0400 Subject: [Tutor] Running python from windows command prompt In-Reply-To: References: Message-ID: <51656024.90803@davea.name> On 04/10/2013 08:32 AM, Arijit Ukil wrote: > I like to run a python program "my_python.py" from windows command > prompt. This program ( a function called testing) takes input as block > data (say data = [1,2,3,4] and outputs processed single data. > > import math > > def avrg(data): > return sum(data)/len(data) > > def testing (data): > val = avrg(data) > out = pow(val,2) > return out > > I am using python 2.6. My intention is to run from windows command > prompt as > > python my_python.py 1 3 2 > > However I am getting error: No such file in the directory, Errno 21 > > Pls help. > Interesting error message. So it really doesn't identify what file, nor in what directory it's looking? Windows will search the path for python, but it's up to you to specify the right directory for data files. Presumably that indicates that my_python.py is not in the current directory. Is it? If that's the problem, you can either change to the right directory (cd mysource) or you can give an explicit path on the command line python path\to\my_python.py 1 3 2 It's frequently useful to paste the relevant portion of the commandline into your message. Don't paraphrase. -- DaveA From woody544 at gmail.com Wed Apr 10 16:44:09 2013 From: woody544 at gmail.com (Woody 544) Date: Wed, 10 Apr 2013 10:44:09 -0400 Subject: [Tutor] File not found error, but it is in the folder! Message-ID: I have a script that worked before I moved it to another folder. I cannot understand why I am getting a 'No such file or directory' error, when the file is in the folder. Any clues would be much appreciated. Thanks! MJ Here is a copy and paste of the script up to the error, output/error and a check for the file: SCRIPT: import os, string, codecs os.chdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS') folder = 'W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses' files = os.listdir(folder) #os.walk(folder) fy13q1dict = {'country' : 'countryname', 'title':'titlename', 'travel':'traveldata', 'publications':'pubdata','conferences':'confdata','highlights':'higlightdata','upcoming':'upcomingdata'} countryname = () titlename = () for i in files: fy13q1dict = {'country' : 'countryname', 'title':'titlename'} fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1) data = str(fp.read()) data = data.replace('\xa0',' ') data = data.split() OUTPUT: >>> Traceback (most recent call last): File "W:\BEP\DOS reports\Q1 FY13\BEP_Tool4DOS\bep_dos_tool.py", line 22, in fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1) File "C:\Python27\lib\codecs.py", line 881, in open file = __builtin__.open(filename, mode, buffering) IOError: [Errno 2] No such file or directory: 'Algeria_688_RVF.txt' CHECK FOR FILE IN FOLDER: >>> os.listdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses') ['Algeria_688_RVF.txt', 'Egypt_31060_RVFEnvir From bgailer at gmail.com Wed Apr 10 16:31:26 2013 From: bgailer at gmail.com (bob gailer) Date: Wed, 10 Apr 2013 10:31:26 -0400 Subject: [Tutor] Reading Program In-Reply-To: References: Message-ID: <516577BE.6040702@gmail.com> On 4/8/2013 2:58 PM, Donald Dietrich wrote: > I am just new to python programing, but would like some help > developing a program for "flow reading" What I would like the program > to do is use any .txt file like micorsoft word .txt file and flow the > words across the screen one at time until the file is come to the end. > I would also like to control the rate (time) of flow. Do you think you > can help me. To Tutors: I had a phone chat with Donald yesterday. Summary: Win 8, IDLE, Python 3.1. Working his way thru Python for Absolute Beginner. He is seeking other books as well. To Donald: Here's the easiest way to create a text file: In IDLE: File -> New Window Enter 2 lines with 2 words on each line. File -> Save: File name: test1.txt Save as type: Text files (*.txt) Here's an interactive session showing some ideas: In the Python Shell (read a file) >>> txt = open("test1.txt") >>> print(txt.read()) you should see the file contents here In the Python Shell (parse the file into words) >>> txt = open("test1.txt") >>> print(txt.read().split()) you should see a list of the words in the file In the Python Shell (display the words with a time delay) >>> txt = open("test1.txt") >>> for word in txt.read().split(): print(word) time.sleep(.4) now press enter again and you should see the words appear with a 0.4 second delay. Hope this helps get you going. Feel free to come back with questions. -- Bob Gailer 919-636-4239 Chapel Hill NC -------------- next part -------------- An HTML attachment was scrubbed... URL: From bcloete at gmail.com Wed Apr 10 17:06:08 2013 From: bcloete at gmail.com (Bradley Cloete) Date: Wed, 10 Apr 2013 17:06:08 +0200 Subject: [Tutor] building a website with python In-Reply-To: References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com> Message-ID: On Wed, Apr 10, 2013 at 5:07 AM, Benjamin Fishbein wrote: > > > > You've gotten some good feedback, but I suspect you will get better > information if you provide more information about your goals for the site. > > > > Thanks for your help, everyone. There are some specific things I want the > site to do, and I'm not sure which would be the best developing tool or > hosting for these. > The python software I developed is for selling used books. > It takes book ISBN numbers as input and returns the best prices being > offered. > It uses the selenium module...I'm not sure how that would translate into a > website. > There are many websites that offer similar book price comparisons, but > mine is different...it's user-friendly. Any volunteer at a thrift shop or > library can use it...just a series of simple directions and yes/no > questions, taking the user all the way from scanning or typing in an ISBN > to dropping the parcel off at the post office. (The local libraries I > worked with more than doubled their used-book revenues.) I want to expand > this nationwide, and bookchicken.com seems to be the way to do it. > So much of the program is simple enough. But there's two parts of the > program that I anticipate being important to what host, development tool I > use: > 1. ISBNs (the books the thrift shop/ library has) being sent to various > websites and returning the data to my site to be analyzed by my program. > 2. Maneuvering through the website of the company buying the books. I > don't want to send the user off to a warehouse's site with a list of books > to sell to them. They'll still be entering their address and name, but > it'll be on my site, that I then send to the warehouse's page, get a > packing slip and shipping label from the warehouse, and give these > documents to the user to print out. > > I'm not sure if this changes anyone's ideas about which host/ developer I > should use. Please let me know. > Thanks, > Ben > > The Django website has a list of recommended hosts. https://code.djangoproject.com/wiki/DjangoFriendlyWebHosts also... http://djangohosting.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From torkamani at gmail.com Wed Apr 10 17:16:22 2013 From: torkamani at gmail.com (Ali Torkamani) Date: Wed, 10 Apr 2013 08:16:22 -0700 Subject: [Tutor] Phyton script for fasta file (seek help) In-Reply-To: References: <13d9b2944c8.-4757810490957638786.6251647252550083523@zoho.com> Message-ID: I have written the following function for reading fasta files, I hope this helps: Ali def ReadFasta(filename): dictFasta=dict() prevLine=''; try: f = open(filename, "r") for line in f: print line line=line.lower() line=line.strip() if len(line)==0: continue if (not(line[0]>='a' and line[0]<='z')) and line[0]!='>': continue if line[0]=='>': prevLine=line[1:] dictFasta[prevLine]='' else: dictFasta[prevLine]=dictFasta[prevLine]+line f.close() except IOError: print 'error opening %s'%(filename) pass return dictFasta -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Wed Apr 10 17:23:59 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 10 Apr 2013 16:23:59 +0100 Subject: [Tutor] File not found error, but it is in the folder! In-Reply-To: References: Message-ID: On 10/04/2013 15:44, Woody 544 wrote: > I have a script that worked before I moved it to another folder. I > cannot understand why I am getting a 'No such file or directory' > error, when the file is in the folder. > > Any clues would be much appreciated. Thanks! > > MJ > > Here is a copy and paste of the script up to the error, output/error > and a check for the file: > > SCRIPT: > import os, string, codecs > os.chdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS') > > folder = 'W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses' > files = os.listdir(folder) > > #os.walk(folder) > > fy13q1dict = {'country' : 'countryname', 'title':'titlename', > 'travel':'traveldata', > 'publications':'pubdata','conferences':'confdata','highlights':'higlightdata','upcoming':'upcomingdata'} > countryname = () > titlename = () > > for i in files: > fy13q1dict = {'country' : 'countryname', 'title':'titlename'} > fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1) > data = str(fp.read()) > data = data.replace('\xa0',' ') > data = data.split() > > OUTPUT: >>>> > > Traceback (most recent call last): > File "W:\BEP\DOS reports\Q1 FY13\BEP_Tool4DOS\bep_dos_tool.py", line > 22, in > fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1) > File "C:\Python27\lib\codecs.py", line 881, in open > file = __builtin__.open(filename, mode, buffering) > IOError: [Errno 2] No such file or directory: 'Algeria_688_RVF.txt' > > CHECK FOR FILE IN FOLDER: >>>> os.listdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses') > ['Algeria_688_RVF.txt', 'Egypt_31060_RVFEnvir > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Your os.chdir call doesn't have the FY13Q1_responses directory on the end. A slight aside, it's far easier to write Windows file paths with raw strings or even use forward slashes. -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From eryksun at gmail.com Wed Apr 10 17:29:02 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 10 Apr 2013 11:29:02 -0400 Subject: [Tutor] Running python from windows command prompt In-Reply-To: References: Message-ID: On Wed, Apr 10, 2013 at 8:32 AM, Arijit Ukil wrote: > > python my_python.py 1 3 2 Adding Python's installation directory to PATH is for starting the interpreter with specific options (-O, -vv, etc), running a module on Python's sys.path (-m), running a command (-c), or starting an interactive shell. Otherwise you can run the script directly: my_python.py 1 3 2 With pylauncher (py.exe) installed to %WINDIR% you don't even need the installation directory on PATH. See PEP 397. http://www.python.org/dev/peps/pep-0397 http://bitbucket.org/vinay.sajip/pylauncher I still add the scripts directory to PATH, which in your case might be "C:\Python26\Scripts". I recommend you do this if you want my_python.py to run as a command-line utility (of course you first have to copy my_python.py to the scripts directory). You can even avoid using the .py extension if you add .PY to the PATHEXT environment variable. Beyond the Windows details, your script needs to import sys and get the argument list, sys.argv[1:]. The arguments are strings, so you'll need to convert to float or int as required. Also, why do you import the math module? You're not using it. From dyoo at hashcollision.org Wed Apr 10 17:32:55 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 10 Apr 2013 09:32:55 -0600 Subject: [Tutor] Phyton script for fasta file (seek help) In-Reply-To: References: <13d9b2944c8.-4757810490957638786.6251647252550083523@zoho.com> Message-ID: Hi Ali, Again, I recommend not reinventing a FASTA parser unless you really need something custom here. In this particular case, the function ReadFasta here is slow on large inputs. The culprit is the set of lines: if line[0]=='>': prevLine=line[1:] dictFasta[prevLine]='' else: dictFasta[prevLine]=dictFasta[prevLine]+line which looks innocent on its own, but it is an O(n^2) string-appending algorithm if we walk across a very long sequence such as a chromosome. The folks who have written the Biopython FASTA parser have almost certainly already considered this pitfall. From sayanchatterjee at gmail.com Wed Apr 10 17:44:50 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Wed, 10 Apr 2013 21:14:50 +0530 Subject: [Tutor] Appending an extra column in a data file Message-ID: Dear All, I have some data files with numpy arrays stored in it in 2 columns. I want to add a third column with just floating point numbers(not numpy array) and plot them later with Matplotlib in 3d. How is it done? Could you please illuminate me? Bests, 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 walksloud at gmail.com Wed Apr 10 17:53:12 2013 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Wed, 10 Apr 2013 08:53:12 -0700 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: References: Message-ID: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> Hi Sayan, This question would be better suited to the matplotlib list. Also, a more precise description of your existing data, and what you hope it would look like would make it easier to help answer your question. Eg., from your description, it is not clear if your existing data is in a table, and in the table you have numpy arrays, or if you have one numpy array of rank 2 with data in it. Regards, Andre On Apr 10, 2013, at 8:44 AM, Sayan Chatterjee wrote: > Dear All, > > I have some data files with numpy arrays stored in it in 2 columns. I want to add a third column with just floating point numbers(not numpy array) and plot them later with Matplotlib in 3d. How is it done? Could you please illuminate me? > > Bests, > 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 > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From davea at davea.name Wed Apr 10 18:22:29 2013 From: davea at davea.name (Dave Angel) Date: Wed, 10 Apr 2013 12:22:29 -0400 Subject: [Tutor] File not found error, but it is in the folder! In-Reply-To: References: Message-ID: <516591C5.9020207@davea.name> On 04/10/2013 10:44 AM, Woody 544 wrote: > I have a script that worked before I moved it to another folder. I > cannot understand why I am getting a 'No such file or directory' > error, when the file is in the folder. > > Any clues would be much appreciated. Thanks! > > MJ > > Here is a copy and paste of the script up to the error, output/error > and a check for the file: > > SCRIPT: > import os, string, codecs > os.chdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS') > > folder = 'W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses' > files = os.listdir(folder) > > #os.walk(folder) > > fy13q1dict = {'country' : 'countryname', 'title':'titlename', > 'travel':'traveldata', > 'publications':'pubdata','conferences':'confdata','highlights':'higlightdata','upcoming':'upcomingdata'} > countryname = () > titlename = () > > for i in files: > fy13q1dict = {'country' : 'countryname', 'title':'titlename'} > fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1) > data = str(fp.read()) > data = data.replace('\xa0',' ') > data = data.split() > > OUTPUT: >>>> > > Traceback (most recent call last): > File "W:\BEP\DOS reports\Q1 FY13\BEP_Tool4DOS\bep_dos_tool.py", line > 22, in > fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1) > File "C:\Python27\lib\codecs.py", line 881, in open > file = __builtin__.open(filename, mode, buffering) > IOError: [Errno 2] No such file or directory: 'Algeria_688_RVF.txt' > > CHECK FOR FILE IN FOLDER: >>>> os.listdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses') > ['Algeria_688_RVF.txt', 'Egypt_31060_RVFEnvir As Mark points out, your problem is that you've used a different directory for os.chdir. I'd like to point out that I'm heavily biased against ever changing "current working directory" in a non-trivial application. The current directory is analogous to a global variable, and they should all be constant. Now, if you want to change it once, at program entry, then it's like a constant that gets iniialized once. But if you are going to use the chkdir, then all your code that deals with that directory should use relative paths. If you'd done os.listdir(".") you'd have seen the problem. My preference is to use absolute directories for every reference, in which case you'd use something like ...open(os.path.join(directory, i), ... With of course a better name than 'i', which is traditionally an integer. (since 1967, anyway) -- DaveA From sayanchatterjee at gmail.com Wed Apr 10 18:58:59 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Wed, 10 Apr 2013 22:28:59 +0530 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> Message-ID: Thank Andre for your prompt answer. I'll figure out the plotting issue once the dat files are made. So it's the primary concern. For an example I am attaching a dat file herewith. The two columns here are 2 numpy arrays.I want to add a third column, to be precise, I want to print a parameter value on the third column of the file. Sayan On 10 April 2013 21:23, Andre' Walker-Loud wrote: > Hi Sayan, > > This question would be better suited to the matplotlib list. > Also, a more precise description of your existing data, and what you hope > it would look like would make it easier to help answer your question. Eg., > from your description, it is not clear if your existing data is in a table, > and in the table you have numpy arrays, or if you have one numpy array of > rank 2 with data in it. > > > Regards, > > Andre > > > > On Apr 10, 2013, at 8:44 AM, Sayan Chatterjee wrote: > > > Dear All, > > > > I have some data files with numpy arrays stored in it in 2 columns. I > want to add a third column with just floating point numbers(not numpy > array) and plot them later with Matplotlib in 3d. How is it done? Could you > please illuminate me? > > > > Bests, > > 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 > > _______________________________________________ > > 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: file_0.02.dat Type: application/octet-stream Size: 18480 bytes Desc: not available URL: From walksloud at gmail.com Wed Apr 10 19:08:51 2013 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Wed, 10 Apr 2013 10:08:51 -0700 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> Message-ID: Hi Sayan, > Thank Andre for your prompt answer. No problem. > I'll figure out the plotting issue once the dat files are made. So it's the primary concern. > For an example I am attaching a dat file herewith. The two columns here are 2 numpy arrays.I want to add a third column, to be precise, I want to print a parameter value on the third column of the file. Let me try again. The reason the matplotlib list would be a better place is this is a general python list, and most people are not familiar with numpy. However, most people who use matplotlib are familiar with numpy. I am hoping you can describe precisely the structure of the data. Maybe show a little code on how it is created, or how you access it. I am not keen to open "random" files from the internet. As two examples of how I think your code might be packed 1/ ''' x = numpy.zeros([10]) # 1D numpy array of dimension 10 y = numpy.zeros([10]) # 1D numpy array of dimension 10 your_data = [] your_data.append(x) your_data.append(y) ''' so now your data is a table with two entries, and each entry is a numpy array. You have in mind adding a third entry to the table with just floats. 2/ ''' your_data = numpy.zeros([10,10]) # initialize a 2D numpy array with all zeros for i in range(your_data.shape[0]): for j in range(your_data.shape[1]): your_data[i,j] = data[i][j] # I am assuming the data is imported already and called data and is in a python list/table format ''' Now you want to make a new column or row for your data file, which contains floats. Well, all the entries inside the numpy array are already floats, so it is not clear to me why you want a new column that is not a numpy array. So it would be nice if you could precisely describe what you currently have and what you want. Hope this helps, Andre From alan.gauld at btinternet.com Wed Apr 10 19:26:29 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Apr 2013 18:26:29 +0100 Subject: [Tutor] Running python from windows command prompt In-Reply-To: References: Message-ID: On 10/04/13 13:32, Arijit Ukil wrote: > I like to run a python program "my_python.py" from windows command > prompt. This program ( a function called testing) takes input as block > data (say data = [1,2,3,4] and outputs processed single data. > Hopefully the code below is not your entire program. If it is it won't work. You define 2 functions but never call them. Also you don't print anything so there is no visible output. Finally this a code does not read the values from sys.argv. (See my tutorial topic 'Talking to the user') As for the error message, others have replied but basically you need to either change to the folder that your file exists in or specify the full path at the command prompt. > import math > > def avrg(data): > return sum(data)/len(data) > > def testing (data): > val = avrg(data) > out = pow(val,2) > return out HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sayanchatterjee at gmail.com Wed Apr 10 19:26:06 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Wed, 10 Apr 2013 22:56:06 +0530 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> Message-ID: Hi Andre, Well,this is the concerned snippet of the code: while *t < 1*: pp_za = pp_init + t*K*np.sin(K*pp_init) # Periodic Boundary Condition for i in range(0,999): if pp_za[i] < 0: pp_za[i] = 2 - abs(pp_za[i]) if pp_za[i] > 2: pp_za[i] = pp_za[i] % 2 pv_za = +K*np.sin(K*pp_init) fname = 'file_' + str(t) + '.dat' # Generating dataset for Phase Space diagram *np.savetxt(fname, np.array([pp_za,pv_za]).T, '%f')* t = t + 0.01 And the sample data generated is : 0.105728 0.098678 0.126865 0.118406 0.147998 0.138128 0.169126 0.157845 0.190247 0.177556 0.211362 0.197259 0.232469 0.216955 0.253567 0.236643 0.274657 0.256321 0.295737 0.275989 0.316806 0.295646 Precisely what I want is, I want to add the 't' (over which the while loop is run) in the 3 rd column. 't' is float and constant for each looping. If you know what a phase plot is(doesn't matter if you don't), I want to see the phase plot evolving with time. Thus the need of a time axis and hence plot with V(velocity-Yaxis), X ( Position -X axis) and t (Time-Z axis). I hope your first example might help.Though,I think,I need some tweaking to fit to my needs. Regards, Sayan On 10 April 2013 22:38, Andre' Walker-Loud wrote: > Hi Sayan, > > > Thank Andre for your prompt answer. > > No problem. > > > I'll figure out the plotting issue once the dat files are made. So it's > the primary concern. > > For an example I am attaching a dat file herewith. The two columns here > are 2 numpy arrays.I want to add a third column, to be precise, I want to > print a parameter value on the third column of the file. > > Let me try again. > The reason the matplotlib list would be a better place is this is a > general python list, and most people are not familiar with numpy. However, > most people who use matplotlib are familiar with numpy. > > I am hoping you can describe precisely the structure of the data. Maybe > show a little code on how it is created, or how you access it. I am not > keen to open "random" files from the internet. As two examples of how I > think your code might be packed > > 1/ > ''' > x = numpy.zeros([10]) # 1D numpy array of dimension 10 > y = numpy.zeros([10]) # 1D numpy array of dimension 10 > your_data = [] > your_data.append(x) > your_data.append(y) > ''' > > so now your data is a table with two entries, and each entry is a numpy > array. > You have in mind adding a third entry to the table with just floats. > > 2/ > ''' > your_data = numpy.zeros([10,10]) # initialize a 2D numpy array with all > zeros > for i in range(your_data.shape[0]): > for j in range(your_data.shape[1]): > your_data[i,j] = data[i][j] # I am assuming the data is imported > already and called data and is in a python list/table format > ''' > > Now you want to make a new column or row for your data file, which > contains floats. Well, all the entries inside the numpy array are already > floats, so it is not clear to me why you want a new column that is not a > numpy array. So it would be nice if you could precisely describe what you > currently have and what you want. > > > Hope this helps, > > Andre > > > -- -------------------------------------------------------------------------- *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 alan.gauld at btinternet.com Wed Apr 10 19:37:48 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 10 Apr 2013 18:37:48 +0100 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: References: Message-ID: On 10/04/13 16:44, Sayan Chatterjee wrote: > I have some data files with numpy arrays stored in it in 2 columns. I Can you define what that means? All files on a computer are data files in some sense. They exist as text files or binary files. If they are text files then the content of your arrays must be encoded somehow as strings. If they are binary files you must have dumped them to file somehow and adding floats is something you probably need to figure out yourself! How did you create these files? (Or how were they created buy somebody else?) > want to add a third column with just floating point numbers(not numpy > array) and plot them later with Matplotlib in 3d. How is it done? Could > you please illuminate me? The fact you use the term column suggests that maybe they are text files of some kind in which case you likely have the content of the numpy arrays but not their structure, in which case adding an extra column should be easy by following the pattern of how you created the files. Don't forget to modify the functions that read the data back to match. But with no idea of the exact nature of your "data files" we can't give very specific help. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From walksloud at gmail.com Wed Apr 10 19:47:08 2013 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Wed, 10 Apr 2013 10:47:08 -0700 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> Message-ID: Hi Sayan, > Well,this is the concerned snippet of the code: > > > while t < 1: > > > pp_za = pp_init + t*K*np.sin(K*pp_init) > > # Periodic Boundary Condition > > for i in range(0,999): > > if pp_za[i] < 0: > pp_za[i] = 2 - abs(pp_za[i]) > if pp_za[i] > 2: > pp_za[i] = pp_za[i] % 2 > > pv_za = +K*np.sin(K*pp_init) > > fname = 'file_' + str(t) + '.dat' > > # Generating dataset for Phase Space diagram > > np.savetxt(fname, np.array([pp_za,pv_za]).T, '%f') > > t = t + 0.01 To answer your question, to add "t" to the array, you can simply replace the current np.array command with either of the following np.array([pp_za,pv_za,t]) or np.array([t,pp_za,pv_za]) depending if you want "t" is the first element of the data or the last. Also, you are "transposing" the array with the ".T", so this will write the data in sequential lines, rather than a single line (row) with multiple entries. I just bring it up because it is not the "obvious" way to pack the data. Also, it looks like you are generating a separate file for each "t". Is this what you want? I assume you want a single data file that stores this info, not many data files. Andre > > And the sample data generated is : > > 0.105728 0.098678 > 0.126865 0.118406 > 0.147998 0.138128 > 0.169126 0.157845 > 0.190247 0.177556 > 0.211362 0.197259 > 0.232469 0.216955 > 0.253567 0.236643 > 0.274657 0.256321 > 0.295737 0.275989 > 0.316806 0.295646 > > Precisely what I want is, I want to add the 't' (over which the while loop is run) in the 3 rd column. 't' is float and constant for each looping. If you know what a phase plot is(doesn't matter if you don't), I want to see the phase plot evolving with time. Thus the need of a time axis and hence plot with V(velocity-Yaxis), X ( Position -X axis) and t (Time-Z axis). > > I hope your first example might help.Though,I think,I need some tweaking to fit to my needs. > > Regards, > Sayan > > > On 10 April 2013 22:38, Andre' Walker-Loud wrote: > Hi Sayan, > > > Thank Andre for your prompt answer. > > No problem. > > > I'll figure out the plotting issue once the dat files are made. So it's the primary concern. > > For an example I am attaching a dat file herewith. The two columns here are 2 numpy arrays.I want to add a third column, to be precise, I want to print a parameter value on the third column of the file. > > Let me try again. > The reason the matplotlib list would be a better place is this is a general python list, and most people are not familiar with numpy. However, most people who use matplotlib are familiar with numpy. > > I am hoping you can describe precisely the structure of the data. Maybe show a little code on how it is created, or how you access it. I am not keen to open "random" files from the internet. As two examples of how I think your code might be packed > > 1/ > ''' > x = numpy.zeros([10]) # 1D numpy array of dimension 10 > y = numpy.zeros([10]) # 1D numpy array of dimension 10 > your_data = [] > your_data.append(x) > your_data.append(y) > ''' > > so now your data is a table with two entries, and each entry is a numpy array. > You have in mind adding a third entry to the table with just floats. > > 2/ > ''' > your_data = numpy.zeros([10,10]) # initialize a 2D numpy array with all zeros > for i in range(your_data.shape[0]): > for j in range(your_data.shape[1]): > your_data[i,j] = data[i][j] # I am assuming the data is imported already and called data and is in a python list/table format > ''' > > Now you want to make a new column or row for your data file, which contains floats. Well, all the entries inside the numpy array are already floats, so it is not clear to me why you want a new column that is not a numpy array. So it would be nice if you could precisely describe what you currently have and what you want. > > > Hope this helps, > > Andre > > > > > > -- > > > -------------------------------------------------------------------------- > 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 From sayanchatterjee at gmail.com Wed Apr 10 19:46:46 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Wed, 10 Apr 2013 23:16:46 +0530 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: References: Message-ID: Hi Alan, Sorry for the ambiguity I have created. I have added the snippet of code just in the previous mail and also the sample data in the text file. Have you had a look on them? I am copy pasting it in this email: Hi Andre, Well,this is the concerned snippet of the code: while *t < 1*: pp_za = pp_init + t*K*np.sin(K*pp_init) # Periodic Boundary Condition for i in range(0,999): if pp_za[i] < 0: pp_za[i] = 2 - abs(pp_za[i]) if pp_za[i] > 2: pp_za[i] = pp_za[i] % 2 pv_za = +K*np.sin(K*pp_init) fname = 'file_' + str(t) + '.dat' # Generating dataset for Phase Space diagram *np.savetxt(fname, np.array([pp_za,pv_za]).T, '%f')* t = t + 0.01 And the sample data generated is : 0.105728 0.098678 0.126865 0.118406 0.147998 0.138128 0.169126 0.157845 0.190247 0.177556 0.211362 0.197259 0.232469 0.216955 0.253567 0.236643 0.274657 0.256321 0.295737 0.275989 0.316806 0.295646 Precisely what I want is, I want to add the 't' (over which the while loop is run) in the 3 rd column. 't' is float and constant for each looping. If you know what a phase plot is(doesn't matter if you don't), I want to see the phase plot evolving with time. Thus the need of a time axis and hence plot with V(velocity-Yaxis), X ( Position -X axis) and t (Time-Z axis). Regards, Sayan On 10 April 2013 23:07, Alan Gauld wrote: > On 10/04/13 16:44, Sayan Chatterjee wrote: > > I have some data files with numpy arrays stored in it in 2 columns. I >> > > Can you define what that means? > All files on a computer are data files in some sense. > They exist as text files or binary files. If they are text files then the > content of your arrays must be encoded somehow as strings. If they are > binary files you must have dumped them to file somehow and adding floats is > something you probably need to figure out yourself! > > How did you create these files? (Or how were they created buy somebody > else?) > > > want to add a third column with just floating point numbers(not numpy >> array) and plot them later with Matplotlib in 3d. How is it done? Could >> you please illuminate me? >> > > The fact you use the term column suggests that maybe they are text files > of some kind in which case you likely have the content of the numpy arrays > but not their structure, in which case adding an extra column should be > easy by following the pattern of how you created the files. Don't forget to > modify the functions that read the data back to match. > > But with no idea of the exact nature of your "data files" we can't give > very specific help. > > -- > 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: From dfjennings at gmail.com Wed Apr 10 19:50:02 2013 From: dfjennings at gmail.com (Don Jennings) Date: Wed, 10 Apr 2013 13:50:02 -0400 Subject: [Tutor] building a website with python In-Reply-To: References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com> Message-ID: On Apr 9, 2013, at 11:07 PM, Benjamin Fishbein wrote: >> >> You've gotten some good feedback, but I suspect you will get better information if you provide more information about your goals for the site. >> > > Thanks for your help, everyone. There are some specific things I want the site to do, and I'm not sure which would be the best developing tool or hosting for these. > The python software I developed is for selling used books. > It takes book ISBN numbers as input and returns the best prices being offered. > It uses the selenium module...I'm not sure how that would translate into a website. Checking the documentation [1], selenium will interact with a browser running remotely using the selenium-server. However, I don't imagine the latter option being viable if you plan to have any significant traffic. I would think a better plan is to forego the gui browser, perhaps re-writing the interaction with other sites using requests [2], a very nice way to work with HTTP. Do you need to interact with javascript on those pages? > There are many websites that offer similar book price comparisons, but mine is different...it's user-friendly. Any volunteer at a thrift shop or library can use it...just a series of simple directions and yes/no questions, taking the user all the way from scanning or typing in an ISBN to dropping the parcel off at the post office. (The local libraries I worked with more than doubled their used-book revenues.) I want to expand this nationwide, and bookchicken.com seems to be the way to do it. > So much of the program is simple enough. But there's two parts of the program that I anticipate being important to what host, development tool I use: > 1. ISBNs (the books the thrift shop/ library has) being sent to various websites and returning the data to my site to be analyzed by my program. > 2. Maneuvering through the website of the company buying the books. I don't want to send the user off to a warehouse's site with a list of books to sell to them. They'll still be entering their address and name, but it'll be on my site, that I then send to the warehouse's page, get a packing slip and shipping label from the warehouse, and give these documents to the user to print out. > > I'm not sure if this changes anyone's ideas about which host/ developer I should use. Please let me know. Obviously my recommendations for producing a static site missed the mark! I do think that one of the microframeworks folks have mentioned will get you up and running faster. Take care, Don [1] http://docs.seleniumhq.org/docs/03_webdriver.jsp [2] http://docs.python-requests.org/en/latest/user/quickstart/ From sayanchatterjee at gmail.com Wed Apr 10 19:54:12 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Wed, 10 Apr 2013 23:24:12 +0530 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> Message-ID: Yup it's exactly what I want! I want *many* data files,not one...to make an animation out of it. For a data file t is constant. the solution you have just mentioned i.e np.array([t,pp_za,pv_za]) is giving the following error: Traceback (most recent call last): File "ZA_Phase_Plot.py", line 38, in np.savetxt(fname, np.array([pp_za,pv_za,t]).T, '%f') File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 979, in savetxt fh.write(asbytes(format % tuple(row) + newline)) TypeError: float argument required, not numpy.ndarray What to do? :-| Sayan On 10 April 2013 23:17, Andre' Walker-Loud wrote: > Hi Sayan, > > > Well,this is the concerned snippet of the code: > > > > > > while t < 1: > > > > > > pp_za = pp_init + t*K*np.sin(K*pp_init) > > > > # Periodic Boundary Condition > > > > for i in range(0,999): > > > > if pp_za[i] < 0: > > pp_za[i] = 2 - abs(pp_za[i]) > > if pp_za[i] > 2: > > pp_za[i] = pp_za[i] % 2 > > > > pv_za = +K*np.sin(K*pp_init) > > > > fname = 'file_' + str(t) + '.dat' > > > > # Generating dataset for Phase Space diagram > > > > np.savetxt(fname, np.array([pp_za,pv_za]).T, '%f') > > > > t = t + 0.01 > > To answer your question, to add "t" to the array, you can simply replace > the current np.array command with either of the following > > np.array([pp_za,pv_za,t]) > > or > > np.array([t,pp_za,pv_za]) > > depending if you want "t" is the first element of the data or the last. > Also, you are "transposing" the array with the ".T", so this will write > the data in sequential lines, rather than a single line (row) with multiple > entries. I just bring it up because it is not the "obvious" way to pack > the data. > > Also, it looks like you are generating a separate file for each "t". > Is this what you want? > I assume you want a single data file that stores this info, not many data > files. > > > Andre > > > > > > > > > And the sample data generated is : > > > > 0.105728 0.098678 > > 0.126865 0.118406 > > 0.147998 0.138128 > > 0.169126 0.157845 > > 0.190247 0.177556 > > 0.211362 0.197259 > > 0.232469 0.216955 > > 0.253567 0.236643 > > 0.274657 0.256321 > > 0.295737 0.275989 > > 0.316806 0.295646 > > > > Precisely what I want is, I want to add the 't' (over which the while > loop is run) in the 3 rd column. 't' is float and constant for each > looping. If you know what a phase plot is(doesn't matter if you don't), I > want to see the phase plot evolving with time. Thus the need of a time axis > and hence plot with V(velocity-Yaxis), X ( Position -X axis) and t (Time-Z > axis). > > > > I hope your first example might help.Though,I think,I need some tweaking > to fit to my needs. > > > > Regards, > > Sayan > > > > > > On 10 April 2013 22:38, Andre' Walker-Loud wrote: > > Hi Sayan, > > > > > Thank Andre for your prompt answer. > > > > No problem. > > > > > I'll figure out the plotting issue once the dat files are made. So > it's the primary concern. > > > For an example I am attaching a dat file herewith. The two columns > here are 2 numpy arrays.I want to add a third column, to be precise, I want > to print a parameter value on the third column of the file. > > > > Let me try again. > > The reason the matplotlib list would be a better place is this is a > general python list, and most people are not familiar with numpy. However, > most people who use matplotlib are familiar with numpy. > > > > I am hoping you can describe precisely the structure of the data. Maybe > show a little code on how it is created, or how you access it. I am not > keen to open "random" files from the internet. As two examples of how I > think your code might be packed > > > > 1/ > > ''' > > x = numpy.zeros([10]) # 1D numpy array of dimension 10 > > y = numpy.zeros([10]) # 1D numpy array of dimension 10 > > your_data = [] > > your_data.append(x) > > your_data.append(y) > > ''' > > > > so now your data is a table with two entries, and each entry is a numpy > array. > > You have in mind adding a third entry to the table with just floats. > > > > 2/ > > ''' > > your_data = numpy.zeros([10,10]) # initialize a 2D numpy array with all > zeros > > for i in range(your_data.shape[0]): > > for j in range(your_data.shape[1]): > > your_data[i,j] = data[i][j] # I am assuming the data is imported > already and called data and is in a python list/table format > > ''' > > > > Now you want to make a new column or row for your data file, which > contains floats. Well, all the entries inside the numpy array are already > floats, so it is not clear to me why you want a new column that is not a > numpy array. So it would be nice if you could precisely describe what you > currently have and what you want. > > > > > > Hope this helps, > > > > Andre > > > > > > > > > > > > -- > > > > > > > -------------------------------------------------------------------------- > > 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 torkamani at gmail.com Wed Apr 10 19:56:12 2013 From: torkamani at gmail.com (Ali Torkamani) Date: Wed, 10 Apr 2013 10:56:12 -0700 Subject: [Tutor] Phyton script for fasta file (seek help) In-Reply-To: References: <13d9b2944c8.-4757810490957638786.6251647252550083523@zoho.com> Message-ID: On Wed, Apr 10, 2013 at 8:32 AM, Danny Yoo wrote: > Hi Ali, > > Again, I recommend not reinventing a FASTA parser unless you really > need something custom here. In this particular case, the function > ReadFasta here is slow on large inputs. The culprit is the set of > lines: > > if line[0]=='>': > prevLine=line[1:] > dictFasta[prevLine]='' > else: > Sure, I myself use biopythin as well, but just wanted to mention that it's not a big hassle, in particular if you need to load it just once. You have a very legitimate point about the order of execution of my suggested code. Ali -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Wed Apr 10 19:59:23 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 10 Apr 2013 13:59:23 -0400 Subject: [Tutor] File not found error, but it is in the folder! In-Reply-To: <516591C5.9020207@davea.name> References: <516591C5.9020207@davea.name> Message-ID: On Wed, Apr 10, 2013 at 12:22 PM, Dave Angel wrote: > My preference is to use absolute directories for every reference, in which > case you'd use something like > ...open(os.path.join(directory, i), ... +1 > With of course a better name than 'i', which is traditionally an integer. > (since 1967, anyway) At least 1958. I'm not familiar with pre-77 FORTRAN, but I found an old manual for FORTRAN II on UNIVAC systems, written by Knuth in 1962. It states that any variable name starting with the letters I through N is implicitly typed integer; otherwise it's implicitly a float. FORTRAN 77 introduced "IMPLICIT NONE" to disable this feature. From walksloud at gmail.com Wed Apr 10 20:06:46 2013 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Wed, 10 Apr 2013 11:06:46 -0700 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> Message-ID: Hi Sayan, > Yup it's exactly what I want! > > I want many data files,not one...to make an animation out of it. For a data file t is constant. You should not need many data files to make an animation. If you write your loops correctly, you can take a single data file with all the data. If you are using code you did not write, and just want to get it to work, I understand that, but would encourage you also to figure out how to do it all with single data file. Less files makes a files system and user happier. > the solution you have just mentioned i.e np.array([t,pp_za,pv_za]) is giving the following error: > > > Traceback (most recent call last): > File "ZA_Phase_Plot.py", line 38, in > np.savetxt(fname, np.array([pp_za,pv_za,t]).T, '%f') > File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 979, in savetxt > fh.write(asbytes(format % tuple(row) + newline)) > TypeError: float argument required, not numpy.ndarray > > What to do? :-| There are pieces of the code snipet you sent which are not defined, so it is not clear why you are getting this error. How long is the file "ZA_Phase_Plot.py"? At least you can send from line 0 to where you did before, so all the variables are defined. That should help. Andre From sayanchatterjee at gmail.com Wed Apr 10 20:22:03 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Wed, 10 Apr 2013 23:52:03 +0530 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> Message-ID: Hi Andre, Is it that? We can have different plots and hence animation from a single data file.Very good!...if you have some time in your disposal, it will be kind of you to illumine in this matter...may be some useful link will do. I have written this small code from scratch,there's no 'get it to work' business...:) Here is the total code...not attaching as you might have problem opening random files from internet....:) #!usr/bin/python import numpy as np import matplotlib.pyplot as plt import itertools as i import pylab K = 3.14 t = 0 # Allotment of particles pp_init = np.linspace(0,1.99799799,999) print pp_init # Velocity array while t < 1: pp_za = pp_init + t*K*np.sin(K*pp_init) # Periodic Boundary Condition for i in range(0,999): if pp_za[i] < 0: pp_za[i] = 2 - abs(pp_za[i]) if pp_za[i] > 2: pp_za[i] = pp_za[i] % 2 pv_za = +K*np.sin(K*pp_init) fname = 'file_' + str(t) + '.dat' # Generating dataset for Phase Space diagram np.savetxt(fname, np.array([pp_za,pv_za,t]), '%f') t = t + 0.01 # Plot using Matplotlib i = 0 while i < 1: fname = 'file_' + str(i) + '.dat' f=open(fname,"r") x,y = np.loadtxt(fname, unpack=True) #plt.plot(x,y,linewidth=2.0) plt.scatter(x,y) plt.ylim(-8,8) plt.xlim(0,2) plt.ylabel('Velocity') plt.xlabel('X') pylab.savefig(fname + '.png') plt.cla() f.close() i = i + 0.001 Regards, Sayan On 10 April 2013 23:36, Andre' Walker-Loud wrote: > Hi Sayan, > > > Yup it's exactly what I want! > > > > I want many data files,not one...to make an animation out of it. For a > data file t is constant. > > You should not need many data files to make an animation. If you write > your loops correctly, you can take a single data file with all the data. > If you are using code you did not write, and just want to get it to work, > I understand that, but would encourage you also to figure out how to do it > all with single data file. Less files makes a files system and user > happier. > > > the solution you have just mentioned i.e np.array([t,pp_za,pv_za]) is > giving the following error: > > > > > > Traceback (most recent call last): > > File "ZA_Phase_Plot.py", line 38, in > > np.savetxt(fname, np.array([pp_za,pv_za,t]).T, '%f') > > File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 979, > in savetxt > > fh.write(asbytes(format % tuple(row) + newline)) > > TypeError: float argument required, not numpy.ndarray > > > > What to do? :-| > > There are pieces of the code snipet you sent which are not defined, so it > is not clear why you are getting this error. How long is the file > "ZA_Phase_Plot.py"? At least you can send from line 0 to where you did > before, so all the variables are defined. That should help. > > Andre > > > > -- -------------------------------------------------------------------------- *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 oscar.j.benjamin at gmail.com Wed Apr 10 20:47:53 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 10 Apr 2013 19:47:53 +0100 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> Message-ID: On 10 April 2013 17:58, Sayan Chatterjee wrote: > Thank Andre for your prompt answer. > > I'll figure out the plotting issue once the dat files are made. So it's the > primary concern. > For an example I am attaching a dat file herewith. The two columns here are > 2 numpy arrays.I want to add a third column, to be precise, I want to print > a parameter value on the third column of the file. The file you attached is a space-delimited text file. If you want to add a third column with the value '1.0' on every row you can just do: with open('old.dat') as fin, open('new.dat', 'w') as fout: for line in fin: fout.write(line[:-1] + ' 1.0\n') Oscar From sayanchatterjee at gmail.com Wed Apr 10 20:48:05 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Thu, 11 Apr 2013 00:18:05 +0530 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> Message-ID: Hi Andre, I figured it out. Need not reply of np.savetxt for storing array simply f.wite() is doing fine. while i < 999: print i fo.write('{0:f} {1:f} {2:f}\n'.format(pp_za[i], pv_za[i],t)) i = i + 1 Eager to know that single file thing though! Sayan On 10 April 2013 23:52, Sayan Chatterjee wrote: > Hi Andre, > > Is it that? We can have different plots and hence animation from a single > data file.Very good!...if you have some time in your disposal, it will be > kind of you to illumine in this matter...may be some useful link will do. > > I have written this small code from scratch,there's no 'get it to work' > business...:) > > Here is the total code...not attaching as you might have problem opening > random files from internet....:) > > #!usr/bin/python > > import numpy as np > import matplotlib.pyplot as plt > import itertools as i > import pylab > > K = 3.14 > t = 0 > > # Allotment of particles > > pp_init = np.linspace(0,1.99799799,999) > > print pp_init > > # Velocity array > > while t < 1: > > > pp_za = pp_init + t*K*np.sin(K*pp_init) > > # Periodic Boundary Condition > > for i in range(0,999): > > if pp_za[i] < 0: > pp_za[i] = 2 - abs(pp_za[i]) > if pp_za[i] > 2: > pp_za[i] = pp_za[i] % 2 > > pv_za = +K*np.sin(K*pp_init) > > fname = 'file_' + str(t) + '.dat' > > # Generating dataset for Phase Space diagram > np.savetxt(fname, np.array([pp_za,pv_za,t]), '%f') > > t = t + 0.01 > > # Plot using Matplotlib > > i = 0 > > while i < 1: > fname = 'file_' + str(i) + '.dat' > f=open(fname,"r") > x,y = np.loadtxt(fname, unpack=True) > #plt.plot(x,y,linewidth=2.0) > plt.scatter(x,y) > plt.ylim(-8,8) > plt.xlim(0,2) > plt.ylabel('Velocity') > plt.xlabel('X') > pylab.savefig(fname + '.png') > plt.cla() > f.close() > i = i + 0.001 > > Regards, > Sayan > > > > > On 10 April 2013 23:36, Andre' Walker-Loud wrote: > >> Hi Sayan, >> >> > Yup it's exactly what I want! >> > >> > I want many data files,not one...to make an animation out of it. For a >> data file t is constant. >> >> You should not need many data files to make an animation. If you write >> your loops correctly, you can take a single data file with all the data. >> If you are using code you did not write, and just want to get it to work, >> I understand that, but would encourage you also to figure out how to do it >> all with single data file. Less files makes a files system and user >> happier. >> >> > the solution you have just mentioned i.e np.array([t,pp_za,pv_za]) is >> giving the following error: >> > >> > >> > Traceback (most recent call last): >> > File "ZA_Phase_Plot.py", line 38, in >> > np.savetxt(fname, np.array([pp_za,pv_za,t]).T, '%f') >> > File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 979, >> in savetxt >> > fh.write(asbytes(format % tuple(row) + newline)) >> > TypeError: float argument required, not numpy.ndarray >> > >> > What to do? :-| >> >> There are pieces of the code snipet you sent which are not defined, so it >> is not clear why you are getting this error. How long is the file >> "ZA_Phase_Plot.py"? At least you can send from line 0 to where you did >> before, so all the variables are defined. That should help. >> >> Andre >> >> >> >> > > > -- > > > -------------------------------------------------------------------------- > *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 sayanchatterjee at gmail.com Wed Apr 10 20:48:54 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Thu, 11 Apr 2013 00:18:54 +0530 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> Message-ID: Thanks Oscar figured it out...:) On 11 April 2013 00:17, Oscar Benjamin wrote: > On 10 April 2013 17:58, Sayan Chatterjee > wrote: > > Thank Andre for your prompt answer. > > > > I'll figure out the plotting issue once the dat files are made. So it's > the > > primary concern. > > For an example I am attaching a dat file herewith. The two columns here > are > > 2 numpy arrays.I want to add a third column, to be precise, I want to > print > > a parameter value on the third column of the file. > > The file you attached is a space-delimited text file. If you want to > add a third column with the value '1.0' on every row you can just do: > > with open('old.dat') as fin, open('new.dat', 'w') as fout: > for line in fin: > fout.write(line[:-1] + ' 1.0\n') > > > Oscar > -- -------------------------------------------------------------------------- *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 oscar.j.benjamin at gmail.com Wed Apr 10 21:04:55 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 10 Apr 2013 20:04:55 +0100 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> Message-ID: On 10 April 2013 19:48, Sayan Chatterjee wrote: > Hi Andre, > > I figured it out. Need not reply of np.savetxt for storing array simply > f.wite() is doing fine. > > while i < 999: > print i > fo.write('{0:f} {1:f} {2:f}\n'.format(pp_za[i], pv_za[i],t)) > i = i + 1 > > Eager to know that single file thing though! The animation module in matplotlib can do animations for you without you needing to explicitly write your data out to files. The code below is taken from some matplotlib documentation or wiki. I don't remember exactly where I got it from but I do remember that I needed to modify it slightly to get it to work. If you run the script it will create 200 png image files and then call an external program (mencoder or ffmpeg - need to install those separately) to convert the png files into an mp4 video file. #!/usr/bin/env python """ Matplotlib Animation Example author: Jake Vanderplas email: vanderplas at astro.washington.edu website: http://jakevdp.github.com license: BSD Please feel free to use and modify this, but keep the above information. Thanks! """ import numpy as np from matplotlib import pyplot as plt from matplotlib import animation # First set up the figure, the axis, and the plot element we want to animate fig = plt.figure() ax = plt.axes(xlim=(0, 2), ylim=(-2, 2)) line, = ax.plot([], [], lw=2) # initialization function: plot the background of each frame def init(): line.set_data([], []) return line, # animation function. This is called sequentially def animate(i): x = np.linspace(0, 2, 1000) y = np.sin(2 * np.pi * (x - 0.01 * i)) line.set_data(x, y) return line, # call the animator. blit=True means only re-draw the parts that have changed. anim = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True) # save the animation as an mp4. This requires ffmpeg or mencoder to be # installed. The extra_args ensure that the x264 codec is used, so that # the video can be embedded in html5. You may need to adjust this for # your system: for more information, see # http://matplotlib.sourceforge.net/api/animation_api.html anim.save('./basic_animation.mp4', fps=30) Oscar From walksloud at gmail.com Wed Apr 10 21:14:29 2013 From: walksloud at gmail.com (Andre' Walker-Loud) Date: Wed, 10 Apr 2013 12:14:29 -0700 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> Message-ID: Hi Sayan, > Is it that? We can have different plots and hence animation from a single data file.Very good!...if you have some time in your disposal, it will be kind of you to illumine in this matter...may be some useful link will do. > > I have written this small code from scratch,there's no 'get it to work' business...:) > > Here is the total code...not attaching as you might have problem opening random files from internet....:) I will leave the complete code snippet for the list memory. A couple things. With the code you have now, you do not even have to save any files. You can simply implant the plotting into the initial while loop. Right now, your saved files serve only as a temporary holding file for the data you had just created. Since your initial data is not read from another file, but simply generated in your code, there is no reason to write any thing to disk, except the figures you are saving. One thing to notice, your "t" and "i" while loops iterate over different counters. You have t = t + 0.01 i = i + 0.001 so your second loop will produce many calls that don't match anything (the files you created don't exist). The previous error is because the pp_za and pv_za are already 1D numpy arrays of dimension 999. That is why combining them with a single float, "np.array([pp_za,pv_za,t])", did not work - the dimension of "pp_za" and "t" don't match, so writing them with numpy.savetxt() gave an error. How do you want to include the "t" information in the figure? Do you want to make different plots with a time axis? Or, it sounds like you are talking about a 3D plot? If you want to store the time with the data, then make a t_array like so ''' inside your t while loop ''' # make an array filled with ones the same dimension as your pp_init, and then multiply each entry by "t" t_array = t * numpy.ones_like(pp_init) ''' then pack your data as ''' np.array([pp_za,pv_za,t_array]) but to have a single data file containing all of this: t_array = np.arange(0,1,.001) # initialize all the times you care about pp_init = np.linspace(0,1.99799799,999) #just taking from your code # initialize an array of zeros # first dimension spans time # second dimension is 3 to store value of pp_za, pv_za, t # third dimension is actual length of data all_data = np.zeros([len(t_array),3,len(pp_init)]) for i,t in enumerate(t_array): # make your pp_za and pv_za as in your code t_tmp = t * numpy.ones_like(pp_init) all_data[i] = np.array([pp_za,pv_za,t]) ''' now you have a single object (np.array) which contains all of your data. You could either make each of the figures in the above loop, or you can use a second loop to make them. I see Oscar has given you some advice on the plotting - so you could use this single object and his example to do what you want. Andre From fomcl at yahoo.com Wed Apr 10 22:45:33 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Wed, 10 Apr 2013 13:45:33 -0700 (PDT) Subject: [Tutor] Appending an extra column in a data file In-Reply-To: References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> Message-ID: <1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com> > Subject: Re: [Tutor] Appending an extra column in a data file > ? > The file you attached is a space-delimited text file. If you want to > add a third column with the value '1.0' on every row you can just do: > > with open('old.dat') as fin, open('new.dat', 'w') as > fout: > ? ? for line in fin: > ? ? ? ? fout.write(line[:-1] + ' 1.0\n') Is that Python 3.x? I thought this "double context manager" could only be done with contextlib.nested, e.g.: >>> with contextlib.nested(open(fn, "rb"), open(fn[:-4] + "_out.dat", "wb")) as (r, w): ...???? for inline in r: ...???????????? w.write(inline + " " + "somevalue" + "\n") Your code looks cleaner though. Regards, Albert-Jan From eryksun at gmail.com Wed Apr 10 23:17:00 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 10 Apr 2013 17:17:00 -0400 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: <1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com> References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> <1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: On Wed, Apr 10, 2013 at 4:45 PM, Albert-Jan Roskam wrote: > >> with open('old.dat') as fin, open('new.dat', 'w') as fout: > > Is that Python 3.x? It's the same syntax as an import statement such as the following: import numpy as np, matplotlib as mpl A downside with this is the inability to split long lines by adding parentheses. Obviously you can break at the open() call: with open('old.dat') as fin, open( 'new.dat', 'w') as fout: for line in fin: But I think it's more readable to break up a long line like this: fin = open('old.dat') fout = open('new.dat', 'w') with fin, fout: for line in fin: From oscar.j.benjamin at gmail.com Wed Apr 10 23:46:20 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 10 Apr 2013 22:46:20 +0100 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: <1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com> References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> <1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: On 10 April 2013 21:45, Albert-Jan Roskam wrote: > > >> Subject: Re: [Tutor] Appending an extra column in a data file >> > > >> The file you attached is a space-delimited text file. If you want to >> add a third column with the value '1.0' on every row you can just do: >> >> with open('old.dat') as fin, open('new.dat', 'w') as >> fout: >> for line in fin: >> fout.write(line[:-1] + ' 1.0\n') > > Is that Python 3.x? I thought this "double context manager" could only be done with contextlib.nested, e.g.: >>>> with contextlib.nested(open(fn, "rb"), open(fn[:-4] + "_out.dat", "wb")) as (r, w): > ... for inline in r: > ... w.write(inline + " " + "somevalue" + "\n") The contextlib.nested context manager does not work properly. The docs http://docs.python.org/2/library/contextlib.html#contextlib.nested say that it was deprecated in Python 2.7. To quote: '''Deprecated since version 2.7: The with-statement now supports this functionality directly (without the confusing error prone quirks).''' The reason for its deprecation was that it cannot catch errors raised during the function calls that create the underlying context managers. This means that if the first open succeeds and the second fails (e.g. because the file doesn't exist) then the with statement has no way of guaranteeing that the first file gets closed. Eryksun has pointed out the downside in relation to breaking long lines. My preferred solution is just to literally nest the with statements: with open('old.dat'): with open('new.dat', 'w'): for line in fin: fout.write(line[:-1] + ' 1.0\n') If your use case is more complicated then Python 3.3 gives you the ExitStack: http://docs.python.org/3.3/library/contextlib.html#contextlib.ExitStack Oscar From oscar.j.benjamin at gmail.com Wed Apr 10 23:49:07 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Wed, 10 Apr 2013 22:49:07 +0100 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> <1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: On 10 April 2013 22:17, eryksun wrote: > > But I think it's more readable to break up a long line like this: > > fin = open('old.dat') > fout = open('new.dat', 'w') > > with fin, fout: > for line in fin: This has the same problems as contextlib.nested: An error raised while opening 'new.dat' could prevent 'old.dat' from being closed properly. Oscar From eryksun at gmail.com Thu Apr 11 00:09:13 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 10 Apr 2013 18:09:13 -0400 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> <1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: On Wed, Apr 10, 2013 at 5:49 PM, Oscar Benjamin wrote: >> fin = open('old.dat') >> fout = open('new.dat', 'w') >> >> with fin, fout: >> for line in fin: > > This has the same problems as contextlib.nested: An error raised while > opening 'new.dat' could prevent 'old.dat' from being closed properly. Thanks for pointing out the potential bug there. It's not a big problem in this case with the file open for reading. But, yeah, I'm hanging my head in shame here... ;) From therealdotcomboy at gmail.com Thu Apr 11 02:18:41 2013 From: therealdotcomboy at gmail.com (Rodney Lewis) Date: Wed, 10 Apr 2013 17:18:41 -0700 Subject: [Tutor] Python bz2 "IOError: invalid data stream" when trying to decompress Message-ID: My question is at StackOverflow so I won't repeat it here. http://stackoverflow.com/questions/15938629/python-bz2-ioerror-invalid-data-stream-when-trying-to-decompress Thanks so much in advance for any help you can provide regarding this. http://www.squidoo.com/introductiontopython -- Rodney Lewis Please Visit My Homepage: http://www.squidoo.com/dotcomboy -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Thu Apr 11 03:23:26 2013 From: davea at davea.name (Dave Angel) Date: Wed, 10 Apr 2013 21:23:26 -0400 Subject: [Tutor] Python bz2 "IOError: invalid data stream" when trying to decompress In-Reply-To: References: Message-ID: <5166108E.2000204@davea.name> On 04/10/2013 08:18 PM, Rodney Lewis wrote: > My question is at StackOverflow so I won't repeat it here. > > http://stackoverflow.com/questions/15938629/python-bz2-ioerror-invalid-data-stream-when-trying-to-decompress > > Thanks so much in advance for any help you can provide regarding this. > > http://www.squidoo.com/introductiontopython > > Works for me, after I turned the fragment into a program. Python 2.7.3 and Linux. Perhaps you could be a bit more thorough in your problem description. Supply the whole program (40 lines isn't too big), and show the exact command line you used for both runs. And show the full traceback, not just a summary. -- DaveA From amitsaha.in at gmail.com Thu Apr 11 03:28:43 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Thu, 11 Apr 2013 11:28:43 +1000 Subject: [Tutor] Sharing Code Snippets Message-ID: Hello everyone, I am not sure if this has been shared on this list. However, to help both those seeking help and those wanting to help, may I suggest that for all of you posting your programs, how about using a service such as GitHub's Gists [1]. It allows you to post entire programs with advantages such as intact code formatting, syntax highlighting and perhaps others such as version control. I hope that's a useful suggestion. [1] https://gist.github.com/ Best, Amit. -- http://amitsaha.github.com/ From eryksun at gmail.com Thu Apr 11 04:16:48 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 10 Apr 2013 22:16:48 -0400 Subject: [Tutor] Python bz2 "IOError: invalid data stream" when trying to decompress In-Reply-To: References: Message-ID: On Wed, Apr 10, 2013 at 8:18 PM, Rodney Lewis wrote: > My question is at StackOverflow so I won't repeat it here. Short link: http://stackoverflow.com/q/15938629/205580 Your function worked fine for me on Windows Python 2.7.3, compressing/decompressing a text file that's about 150 KiB. The bz2 module raises IOError("invalid data stream") for the error codes BZ_DATA_ERROR and BZ_DATA_ERROR_MAGIC: http://hg.python.org/cpython/file/70274d53c1dd/Modules/bz2module.c#l192 According to the bzip2 docs, BZ_DATA_ERROR is raised when the computed CRC fails to match the stored CRC, or there's some other anomaly in the data. BZ_DATA_ERROR_MAGIC means the compressed data didn't start with the 'BZh' magic bytes. http://www.bzip.org/1.0.5/bzip2-manual-1.0.5.html#err-handling From sayanchatterjee at gmail.com Thu Apr 11 08:04:16 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Thu, 11 Apr 2013 11:34:16 +0530 Subject: [Tutor] Sharing Code Snippets In-Reply-To: References: Message-ID: Tried it out.It's really cool.From next time on, shall try to make use of this. Thanks. :) On 11 April 2013 06:58, Amit Saha wrote: > Hello everyone, > > I am not sure if this has been shared on this list. However, to help > both those seeking help and those wanting to help, may I suggest that > for all of you posting your programs, how about using a service such > as GitHub's Gists [1]. It allows you to post entire programs with > advantages such as intact code formatting, syntax highlighting and > perhaps others such as version control. > > I hope that's a useful suggestion. > > [1] https://gist.github.com/ > > Best, > Amit. > > -- > http://amitsaha.github.com/ > _______________________________________________ > 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 arijit.ukil at tcs.com Thu Apr 11 08:08:25 2013 From: arijit.ukil at tcs.com (Arijit Ukil) Date: Thu, 11 Apr 2013 11:38:25 +0530 Subject: [Tutor] Running python from windows command prompt In-Reply-To: References: Message-ID: Thanks for the help. Now I have modifed the code as: import sys def main(argv): data = int(sys.argv[1]) avg = average (data) print "Average:", avg def average(num_list): return sum(num_list)/len(num_list) if __name__ == "__main__": main(sys.argv[1:]) When running in command line I am getting these errors: In case 1. data = sys.argv[1] In case 2, data = float(sys.argv[1]) In case 3, data = int (sys.argv[1]) 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: 04/10/2013 10:58 PM Subject: Re: [Tutor] Running python from windows command prompt Sent by: "Tutor" On 10/04/13 13:32, Arijit Ukil wrote: > I like to run a python program "my_python.py" from windows command > prompt. This program ( a function called testing) takes input as block > data (say data = [1,2,3,4] and outputs processed single data. > Hopefully the code below is not your entire program. If it is it won't work. You define 2 functions but never call them. Also you don't print anything so there is no visible output. Finally this a code does not read the values from sys.argv. (See my tutorial topic 'Talking to the user') As for the error message, others have replied but basically you need to either change to the folder that your file exists in or specify the full path at the command prompt. > import math > > def avrg(data): > return sum(data)/len(data) > > def testing (data): > val = avrg(data) > out = pow(val,2) > return out 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 -------------- A non-text attachment was scrubbed... Name: not available Type: image/gif Size: 14160 bytes Desc: not available URL: From pasokan at talentsprint.com Thu Apr 11 08:24:17 2013 From: pasokan at talentsprint.com (Asokan Pichai) Date: Thu, 11 Apr 2013 11:54:17 +0530 Subject: [Tutor] Running python from windows command prompt In-Reply-To: References: Message-ID: On Thu, Apr 11, 2013 at 11:38 AM, Arijit Ukil wrote: > Thanks for the help. Now I have modifed the code as: > > import sys > > def main(argv): > > data = int(sys.argv[1]) > > avg = average (data) > > print "Average:", avg > > def average(num_list): > return sum(num_list)/len(num_list) > > if __name__ == "__main__": > main(sys.argv[1:]) > Two major problems: One: The __main__ methods processes (correctly) the args and drops argv[0] But your main() function is calling sys.argv again Two: sum() and len() expect a list -- more accurately an iterable. when you say data = argv[1] data is a scalar. If you know of list comprehensions, it can be easier or else, think of a function to convert a list of strings (argv[1:] to a list of floats; more general than int) -------------------- def arg2list(arg): args = [] for a in arg: args.append(float(a)) return args -------------------- Now replace the data = line with data = arg2list(argv) # NOT sys.argv HTH Asokan Pichai "Expecting the world to treat you fairly because you are a good person is a little like expecting the bull to not attack you because you are a vegetarian" -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Apr 11 08:29:32 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 11 Apr 2013 07:29:32 +0100 Subject: [Tutor] Running python from windows command prompt In-Reply-To: References: Message-ID: On 11/04/13 07:08, Arijit Ukil wrote: > Thanks for the help. Now I have modifed the code as: > > import sys > > def main(argv): > data = int(sys.argv[1]) > avg = average (data) > print "Average:", avg > > def average(num_list): > return sum(num_list)/len(num_list) > > if __name__ == "__main__": > main(sys.argv[1:]) > > When running in command line I am getting these errors: > In case 1. data = sys.argv[1] > In case 2, data = float(sys.argv[1]) > In case 3, data = int (sys.argv[1]) Try printing data to see what you are doing wrong in each case. You need data to be a list of numbers. None of your three cases produces that. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From after1990s at gmail.com Thu Apr 11 12:41:37 2013 From: after1990s at gmail.com (w qj) Date: Thu, 11 Apr 2013 18:41:37 +0800 Subject: [Tutor] Looks like a judgment bug. Message-ID: I found this under Windows Python3 >>> l="http://f/" >>> l[-1] is not '/' False >>> and this under Linux Python3 >>> l = "http://ff.f/" >>> l[-1] '/' >>> l[-1] is not '/' True It's Looks like a python bug? From timomlists at gmail.com Thu Apr 11 13:20:43 2013 From: timomlists at gmail.com (Timo) Date: Thu, 11 Apr 2013 13:20:43 +0200 Subject: [Tutor] Looks like a judgment bug. In-Reply-To: References: Message-ID: <51669C8B.2050001@gmail.com> Op 11-04-13 12:41, w qj schreef: > I found this under Windows Python3 >>>> l="http://f/" >>>> l[-1] is not '/' > False > and this under Linux Python3 >>>> l = "http://ff.f/" >>>> l[-1] > '/' >>>> l[-1] is not '/' > True > > It's Looks like a python bug? This looks like a "is not" versus "!=" thing. Someone (I think Steven Apprano) posted a couple of days ago on this mailing list to only use "is" and "is not" when comparing to None. It works fine with regular operators. $ python3 Python 3.2.3 (default, Oct 19 2012, 19:53:16) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> l = "http://ff.f/" >>> l[-1] '/' >>> l[-1] is not '/' True >>> l[-1] != '/' False Timo > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From fomcl at yahoo.com Thu Apr 11 13:24:31 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 11 Apr 2013 04:24:31 -0700 (PDT) Subject: [Tutor] Appending an extra column in a data file In-Reply-To: References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> <1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: <1365679471.57539.YahooMailNeo@web163806.mail.gq1.yahoo.com> > Subject: Re: [Tutor] Appending an extra column in a data file > > On Wed, Apr 10, 2013 at 5:49 PM, Oscar Benjamin > wrote: >>> ? ? fin = open('old.dat') >>> ? ? fout = open('new.dat', 'w') >>> >>> ? ? with fin, fout: >>> ? ? ? ? for line in fin: >> >> This has the same problems as contextlib.nested: An error raised while >> opening 'new.dat' could prevent 'old.dat' from being closed > properly. > > Thanks for pointing out the potential bug there. It's not a big > problem in this case with the file open for reading. But, yeah, I'm > hanging my head in shame here... ;) Cool. This solves a problem it had with contextlib.nested some time ago. (sorry for kinda hijacking this thread, but..) Would it be safe (both __exit__ calls are guaranteed to be made) to use code?like this (if it worked, that is!)? import sys import contextlib def someCloseFunc(): ? print "Yaaay properly closed!" @contextlib.contextmanager def funcOne(arg): ? e = None ? try: ??? yield arg ? except: ??? e = sys.exc_info()[1] ??? print e ? finally: ??? someCloseFunc() ??? if e: ????? yield e ??? yield None funcTwo = funcOne with contextlib.nested(funcOne("one-ish"), funcTwo("two-ish")) as (one, two): ? print one, two * traceback one-ish two-ish Yaaay properly closed! generator didn't stop Yaaay properly closed! Traceback (most recent call last): ? File "F:/mgr.py", line 23, in ??? print one, two ? File "C:\Program Files\Python27\lib\contextlib.py", line 24, in __exit__ ??? self.gen.next() ? File "C:\Program Files\Python27\lib\contextlib.py", line 121, in nested ??? if exit(*exc): ? File "C:\Program Files\Python27\lib\contextlib.py", line 36, in __exit__ ??? raise RuntimeError("generator didn't stop after throw()") RuntimeError: generator didn't stop after throw() >>> From fomcl at yahoo.com Thu Apr 11 13:33:56 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 11 Apr 2013 04:33:56 -0700 (PDT) Subject: [Tutor] Sharing Code Snippets In-Reply-To: References: Message-ID: <1365680036.67436.YahooMailNeo@web163806.mail.gq1.yahoo.com> > Subject: [Tutor] Sharing Code Snippets > > Hello everyone, > > I am not sure if this has been shared on this list. However, to help > both those seeking help and those wanting to help, may I suggest that > for all of you posting your programs, how about using a service such > as GitHub's Gists [1]. It allows you to post entire programs with > advantages such as intact code formatting, syntax highlighting and > perhaps others such as version control. > > I hope that's a useful suggestion. > > [1] https://gist.github.com/ Hi, ? Is this better than e.g. http://www.pastebin.com/? I wouldn't like it if the emails contain *only* links to such sites. That way the information is lost forever if github decides to remove the code. Often these sites have expiration dates for their contents. Albert-Jan From oscar.j.benjamin at gmail.com Thu Apr 11 13:56:05 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 11 Apr 2013 12:56:05 +0100 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: <1365679471.57539.YahooMailNeo@web163806.mail.gq1.yahoo.com> References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> <1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com> <1365679471.57539.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: On 11 April 2013 12:24, Albert-Jan Roskam wrote: > > >> Subject: Re: [Tutor] Appending an extra column in a data file >> >> On Wed, Apr 10, 2013 at 5:49 PM, Oscar Benjamin >> wrote: >>>> fin = open('old.dat') >>>> fout = open('new.dat', 'w') >>>> >>>> with fin, fout: >>>> for line in fin: >>> >>> This has the same problems as contextlib.nested: An error raised while >>> opening 'new.dat' could prevent 'old.dat' from being closed >> properly. >> >> Thanks for pointing out the potential bug there. It's not a big >> problem in this case with the file open for reading. But, yeah, I'm >> hanging my head in shame here... ;) > > Cool. This solves a problem it had with contextlib.nested some time ago. > (sorry for kinda hijacking this thread, but..) > Would it be safe (both __exit__ calls are guaranteed to be made) to use > code like this (if it worked, that is!)? Partly because it doesn't work I really can't figure out what you're trying to do. > > import sys > import contextlib > > def someCloseFunc(): > print "Yaaay properly closed!" > > @contextlib.contextmanager > def funcOne(arg): > e = None > try: > yield arg > except: > e = sys.exc_info()[1] > print e > finally: > someCloseFunc() > if e: I guess you already know that the lines two lines below will break the contextmanager decorator: > yield e > yield None > What effect are you actually wanting from the two lines below (I'm assuming that you didn't want the error message shown)? Is it significant that funcTwo is funcOne, or is that just to keep the demonstration simple? > funcTwo = funcOne > with contextlib.nested(funcOne("one-ish"), funcTwo("two-ish")) as (one, two): > print one, two > > * traceback > one-ish two-ish > Yaaay properly closed! > generator didn't stop > Yaaay properly closed! > > Traceback (most recent call last): > File "F:/mgr.py", line 23, in > print one, two > File "C:\Program Files\Python27\lib\contextlib.py", line 24, in __exit__ > self.gen.next() > File "C:\Program Files\Python27\lib\contextlib.py", line 121, in nested > if exit(*exc): > File "C:\Program Files\Python27\lib\contextlib.py", line 36, in __exit__ > raise RuntimeError("generator didn't stop after throw()") > RuntimeError: generator didn't stop after throw() >>>> Oscar From wayne at waynewerner.com Thu Apr 11 14:16:26 2013 From: wayne at waynewerner.com (Wayne Werner) Date: Thu, 11 Apr 2013 07:16:26 -0500 (CDT) Subject: [Tutor] Looks like a judgment bug. In-Reply-To: <51669C8B.2050001@gmail.com> References: <51669C8B.2050001@gmail.com> Message-ID: On Thu, 11 Apr 2013, Timo wrote: > Op 11-04-13 12:41, w qj schreef: >> I found this under Windows Python3 >>>>> l="http://f/" >>>>> l[-1] is not '/' >> False >> and this under Linux Python3 >>>>> l = "http://ff.f/" >>>>> l[-1] >> '/' >>>>> l[-1] is not '/' >> True >> >> It's Looks like a python bug? > This looks like a "is not" versus "!=" thing. Someone (I think Steven > Apprano) posted a couple of days ago on this mailing list to only use "is" > and "is not" when comparing to None. You're absolutely correct. `is` compares the identity (basically id('/') == id('/') ) *sometimes* CPython will use a trick that caches smaller strings, so this might work one time: >>> x = '/' >>> y = '/' >>> x is y True But then the next time you do the same thing it could return False. Or on a different OS. There's nothing (that I'm aware of) that will guarantee either result in this case. In the example case we were comparing that `l[-1]` referred to the same spot in memory as the literal string `/`. And as the example showed, sometimes it will be, other times it won't. The takeaway is to use `is` when you want to compare identity, and `==` when you want equaltiy. For example, That car is *my* car. The car I'm referring to is one specific car. But if I were to say... My car is a Chevette. That would be more like saying `car.model == 'Chevette'` - many different cars may actually be a Chevette. HTH, Wayne From fomcl at yahoo.com Thu Apr 11 14:25:35 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 11 Apr 2013 05:25:35 -0700 (PDT) Subject: [Tutor] Appending an extra column in a data file In-Reply-To: References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> <1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com> <1365679471.57539.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: <1365683135.79702.YahooMailNeo@web163801.mail.gq1.yahoo.com> >> Cool. This solves a problem it had with contextlib.nested some time ago. >> (sorry for kinda hijacking this thread, but..) >> Would it be safe (both __exit__ calls are guaranteed to be made) to use >> code like this (if it worked, that is!)? > > Partly because it doesn't work I really can't figure out what you're > trying to do. You are right, I should have stated the goal: make contextlib.nested work in a way that it does not have the shortcoming that caused it become deprecated, namely, ?__exit__?is not guaranteed to be called if the outer "with" raises an exception. ? >> import sys >> import contextlib >> >> def someCloseFunc(): >> ? print "Yaaay properly closed!" >> >> @contextlib.contextmanager >> def funcOne(arg): >> ? e = None >> ? try: >> ? ? yield arg >> ? except: >> ? ? e = sys.exc_info()[1] >> ? ? print e >> ? finally: >> ? ? someCloseFunc() >> ? ? if e: > > I guess you already know that the lines two lines below will break the > contextmanager decorator: > >> ? ? ? yield e >> ? ? yield None >> ? Nope, I didn't realize that. Thank you. ? > > What effect are you actually wanting from the two lines below (I'm > assuming that you didn't want the error message shown)? Is it > significant that funcTwo is funcOne, or is that just to keep the > demonstration simple? ? This is merely to keep the demonstration simple. And yes, I didn't want the error message. ? > >> funcTwo = funcOne >> with contextlib.nested(funcOne("one-ish"), > funcTwo("two-ish")) as (one, two): >> ? print one, two >> >> * traceback >> one-ish two-ish >> Yaaay properly closed! >> generator didn't stop >> Yaaay properly closed! >> ? Two times "Yaaay properly closed!" means that __exit__ is called twice, right? Anyway, the code below at least runs without errors. Too bad the outcommented version with tuple unpacking raises an AttributeError. ? import sys import contextlib ? def someCloseFunc(): ? print "Yaaay properly closed!" ? @contextlib.contextmanager def funcOne(arg): ? try: ??? yield arg ? except: ??? yield sys.exc_info()[1] ? finally: ??? someCloseFunc() funcTwo = funcOne ? with contextlib.nested(funcOne("one-ish"), funcTwo("two-ish")) as (one, two): ? print one, two ? ##funcs = (funcOne, funcTwo) ##with contextlib.nested(*funcs) as (one, two): ##? print one("one-ish"), two("two-ish") From oscar.j.benjamin at gmail.com Thu Apr 11 14:49:15 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Thu, 11 Apr 2013 13:49:15 +0100 Subject: [Tutor] Appending an extra column in a data file In-Reply-To: <1365683135.79702.YahooMailNeo@web163801.mail.gq1.yahoo.com> References: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com> <1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com> <1365679471.57539.YahooMailNeo@web163806.mail.gq1.yahoo.com> <1365683135.79702.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: On 11 April 2013 13:25, Albert-Jan Roskam wrote: > > >>> Cool. This solves a problem it had with contextlib.nested some time ago. >>> (sorry for kinda hijacking this thread, but..) >>> Would it be safe (both __exit__ calls are guaranteed to be made) to use >>> code like this (if it worked, that is!)? >> >> Partly because it doesn't work I really can't figure out what you're >> trying to do. > > You are right, I should have stated the goal: make contextlib.nested work in a way > that it does not have the shortcoming that caused it become deprecated, namely, > __exit__ is not guaranteed to be called if the outer "with" raises an exception. The problem with contextlib.nested is that it cannot catch errors raised while its arguments are generated because nested hasn't even been called yet. For example in the code with nested(open('foo'), open('bar')) as foo, bar: do_stuff() the expressions used as arguments to the nested function are evaluated before nested is called. This is always true of function calls: >>> def f1(): ... print('Calling f1') ... >>> def f2(): ... print('Calling f2') ... >>> def g(arg1, arg2): ... print('Calling g') ... >>> g(f1(), f2()) Calling f1 Calling f2 Calling g >>> def f_broken(): ... raise ValueError ... >>> g(f1(), f_broken()) Calling f1 Traceback (most recent call last): File "", line 1, in File "", line 2, in f_broken ValueError So if open raises an error nested is never called and the nested context manager does not exist in order to call the __exit__ methods of its arguments. > Two times "Yaaay properly closed!" means that __exit__ is called twice, right? Yes it does. > Anyway, the code below at least runs without errors. Too bad the outcommented > version with tuple unpacking raises an AttributeError. > > import sys > import contextlib > > def someCloseFunc(): > print "Yaaay properly closed!" > > @contextlib.contextmanager > def funcOne(arg): > try: > yield arg > except: > yield sys.exc_info()[1] Why do you want the two lines below? Attempting to yield twice gives an error like the one you showed before: >>> from contextlib import contextmanager >>> @contextmanager ... def f(): ... try: ... yield ... except: ... yield ... >>> with f(): ... raise ValueError ... Traceback (most recent call last): File "", line 2, in File "q:\tools\Python27\lib\contextlib.py", line 36, in __exit__ raise RuntimeError("generator didn't stop after throw()") RuntimeError: generator didn't stop after throw() The contextmanager decorator should be used with a generator function that hits exactly one yield in its execution. That yield statement corresponds to the code block in the with statement. There is nothing for any other yield to correspond to. > finally: > someCloseFunc() > funcTwo = funcOne > > > with contextlib.nested(funcOne("one-ish"), funcTwo("two-ish")) as (one, two): > print one, two Since there isn't really any way that funcOne or funcTwo would raise an error when called there isn't any problem with using nested *in this case*. The error would have to be raised before the yield statement. If that's not really possible for any of the context managers that you want to use then nested is fine and you can use it without worry. > > ##funcs = (funcOne, funcTwo) > ##with contextlib.nested(*funcs) as (one, two): > ## print one("one-ish"), two("two-ish") That's because you're passing functions into nested rather than calling the functions and passing the result into nested. Try this: context_managers = (funcOne('one'), funcTwo('two')) with contextlib.nested(*context_managers) as cms: # blah blah Note that if you're happy using nested there's no problem with creating the context managers on the line above. Oscar From ramit.prasad at jpmorgan.com Thu Apr 11 22:01:48 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 11 Apr 2013 20:01:48 +0000 Subject: [Tutor] Running python from windows command prompt In-Reply-To: References: Message-ID: <5B80DD153D7D744689F57F4FB69AF474182E39B8@SCACMX008.exchad.jpmchase.net> On 11/04/13 07:08, Arijit Ukil wrote: > Thanks for the help. Now I have modifed the code as: > > import sys > > def main(argv): > data = int(sys.argv[1]) > avg = average (data) > print "Average:", avg > > def average(num_list): > return sum(num_list)/len(num_list) Note that in Python 2.2-2.7 if sum returns an integer the division may not be what you expect. >>> 3/2 1 >>> 3/2.0 1.5 You may want to convert either the numerator or denominator to a float. It does not matter which as long as one of them is a float. ~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 etanes.rm at gmail.com Fri Apr 12 00:33:16 2013 From: etanes.rm at gmail.com (Scurvy Scott) Date: Thu, 11 Apr 2013 17:33:16 -0500 Subject: [Tutor] Guidance if possible Message-ID: Hello again wonderful python tutor mailing list. I've got I guess more of a broad question than is usually asked on this list and perhaps some of you might find it annoying, that's fine, if it's inappropriate feel free to say so. I want to start work on a new python project that would visit a specific companies contest site daily and everyday fill out the active contest forms, as they allow you to enter once a day. I've got an outline in my head but am a little green to know any of the good web scraping/manipulation frameworks or if one is better than the other for something like this. I have no intention of doing anything professional/shady/annoying with this code and want to write it purely for my own amusement as well as to learn and obviously to perhaps win something cool. Any information anyone feels like providing would be awesome, I'm running Lubuntu 12.10, 2gb ram, old crappy notebook. My basic outline goes something like this.. Everyday the program visits the site and scrapes the links for all the contests. The program visits each contest page and verifies there is an entry form, indicating that the contest is active If the contest is active at that moment, it adds the title of the page to a text file, if the contest is inactive it adds the title of the page to a text file. If the contest is active, it fills out the form with my details and sends it off If the contest is inactive the title of the page is added to the permanently blacklisted text file and never messed with again. This might be a bit convoluted as well and any pointers are appreciated. Scott From alan.gauld at btinternet.com Fri Apr 12 01:43:59 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 12 Apr 2013 00:43:59 +0100 Subject: [Tutor] Guidance if possible In-Reply-To: References: Message-ID: On 11/04/13 23:33, Scurvy Scott wrote: > the other for something like this. I have no intention of doing > anything professional/shady/annoying with this code and want to write > it purely for my own amusement as well as to learn and obviously to > perhaps win something cool. Which is fine but you should still check the terms and conditions of the web sites because many such sites explicitly prohibit the use of web scrapers. Using one could disqualify you from winning, and disguising the fact you are using one is non trivial. > Everyday the program visits the site and scrapes the links for all the contests. > The program visits each contest page and verifies there is an entry > form, indicating that the contest is active > If the contest is active at that moment, it adds the title of the page > to a text file, if the contest is inactive it adds the title of the > page to a text file. > If the contest is active, it fills out the form with my details and sends it off > If the contest is inactive the title of the page is added to the > permanently blacklisted text file and never messed with again. > > This might be a bit convoluted as well and any pointers are appreciated. Seems reasonable to me. Try looking at the http, urllib and cookie stuff in the stdlib. And then look at tools like Beautiful Soup and Element Tree for the content scraping bits. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From amitsaha.in at gmail.com Fri Apr 12 02:28:47 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Fri, 12 Apr 2013 10:28:47 +1000 Subject: [Tutor] Sharing Code Snippets In-Reply-To: <1365680036.67436.YahooMailNeo@web163806.mail.gq1.yahoo.com> References: <1365680036.67436.YahooMailNeo@web163806.mail.gq1.yahoo.com> Message-ID: On Thu, Apr 11, 2013 at 9:33 PM, Albert-Jan Roskam wrote: >> Subject: [Tutor] Sharing Code Snippets >> >> Hello everyone, >> >> I am not sure if this has been shared on this list. However, to help >> both those seeking help and those wanting to help, may I suggest that >> for all of you posting your programs, how about using a service such >> as GitHub's Gists [1]. It allows you to post entire programs with >> advantages such as intact code formatting, syntax highlighting and >> perhaps others such as version control. >> >> I hope that's a useful suggestion. >> >> [1] https://gist.github.com/ > > Hi, > > Is this better than e.g. http://www.pastebin.com/? I wouldn't like it if the emails contain *only* links to such sites. > That way the information is lost forever if github decides to remove the code. Often these sites have expiration > dates for their contents. GitHub's Gists doesn't have an expiration date, since its primary purpose is not a paste bin. But yes, I understand that if GitHub decides to remove this service some day, the code is lost. -Amit. > > Albert-Jan -- http://amitsaha.github.com/ From steve at pearwood.info Fri Apr 12 03:10:03 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 12 Apr 2013 11:10:03 +1000 Subject: [Tutor] Looks like a judgment bug. In-Reply-To: References: Message-ID: <51675EEB.2050003@pearwood.info> On 11/04/13 20:41, w qj wrote: > I found this under Windows Python3 >>>> l="http://f/" >>>> l[-1] is not '/' > False >>>> > > and this under Linux Python3 >>>> l = "http://ff.f/" >>>> l[-1] > '/' >>>> l[-1] is not '/' > True > > It's Looks like a python bug? No, it is a bug in your understanding. The "is" and "is not" operators are for testing object identity, not equality. Python makes very few promises about object identity, and in this case both examples are fine. When you write this code: l[-1] is not '/' # where l[-1] == '/' how does Python evaluate this expression? First, it looks up l[-1], which creates a new object equal to the single-character string '/'. Then, Python evaluates the literal '/'. Now it has a choice: it might *reuse* the object that was just created a microsecond ago, or it might create a *new* object with the same value. Both behaviours are allowed, the language does not specify one or the other. In the first case, you get one object referenced twice, and "is not" returns False. In the second case, you get two distinct objects referenced once each, and "is not" returns True. Both behaviours are correct, since Python doesn't promise when it will or won't create a new object in cases like this. Whether Python creates two distinct objects or not will depend on the version of Python you use, the implementation, the operating system, possibly even the day of the week. (Well, probably not the last one, but it *could*.) No promises are made, and you cannot rely on one behaviour or the other. You almost never need to use object identity, and should nearly always use == and != instead. Almost the only exception is when testing for the None singleton object. # if one of the values is None, always use "is" or "is not": if x is None # for everything else, always use == or != x == '/' There are some other exceptions, but they are rare. For interest, I ran this expression under various different versions of Python: print ('http://f/'[-1] is '/') And these are the results I got: Jython 2.5: False IronPython 2.6: False CPython: 1.5: True 2.4: True 2.5: True 2.6: True 2.7: True 3.1: False 3.2: False 3.3: True Unless you have the exact same versions, built with the exact same compiler, on the exact same operating systems, you may get different results. -- Steven From steve at pearwood.info Fri Apr 12 03:37:50 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 12 Apr 2013 11:37:50 +1000 Subject: [Tutor] Sharing Code Snippets In-Reply-To: References: Message-ID: <5167656E.7040202@pearwood.info> On 11/04/13 11:28, Amit Saha wrote: > Hello everyone, > > I am not sure if this has been shared on this list. However, to help > both those seeking help and those wanting to help, may I suggest that > for all of you posting your programs, how about using a service such > as GitHub's Gists [1]. It allows you to post entire programs with > advantages such as intact code formatting, syntax highlighting and > perhaps others such as version control. Please don't. Small code snippets should be posted directly in the body of the email, not on some external website. They should be posted in PLAIN TEXT (do not use so-called "rich-text", HTML formatted emails, since they destroy critical indentation and make it difficult for those using plain-text email clients to read your code). Like this: import random def coin_toss(): if random.random() > 0.5: return "head" else: return "tail" It's much less work for everyone to read code snippets in the email: compare: SENDER: copy and paste code directly into email READER: read email write response versus: SENDER: open browser log in to external site copy and paste code into external site make sure code has been saved copy and paste url into email READER: read email open browser copy and paste url fix url if it has been mangled by line-wrapping read code copy and paste back to email for the response to say nothing about how it may effect those who use a screen reader. (They generally work well with email, not so well with many websites.) People may have access to their email, and be able to read and answer your question, but they may not have access to the web. Perhaps they are behind a firewall that blocks the website. For whatever reason, just because somebody is reading your email doesn't mean that they can or will follow to a website to read the important bit (the actual code). You should make it *easy* for people to answer, not harder. Code sharing sites are great for posting entire programs, but you, the reader, shouldn't be posting entire programs and expecting us to work out where the problem lies. Identify where the problem lies, and eliminate all unnecessary code. Please read this for more details: http://sscce.org/ -- Steven From amitsaha.in at gmail.com Fri Apr 12 04:53:04 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Fri, 12 Apr 2013 12:53:04 +1000 Subject: [Tutor] Looks like a judgment bug. In-Reply-To: References: Message-ID: On Thu, Apr 11, 2013 at 8:41 PM, w qj wrote: > I found this under Windows Python3 >>>> l="http://f/" >>>> l[-1] is not '/' > False >>>> > > and this under Linux Python3 >>>> l = "http://ff.f/" >>>> l[-1] > '/' >>>> l[-1] is not '/' > True > > It's Looks like a python bug? No, this is not. The 'is' and 'is not' tests in Python are for checking the identities of Python objects - a string, a single character, a single number, everything is an object. So for example: >>> a=1 >>> b=1 >>> a is b True >>> id(a) == id(b) True When you perform the check, 'a is b', you are actually checking id(a) == id(b). In this case, since I am really referring to the same object, 1 with two different bindings - the identifier is the same. In your case, the check 'failed' on Windows and 'passed' on Linux, is because in one case, the identifiers were the same, and in another case it wasn't. So, when are identifiers same and when not? That depends on the type of object - mutable or immutable. You may want to read up on Python's data model to learn more about this. Also, more on "string interning" here. [1] [1] http://stackoverflow.com/questions/15541404/python-string-interning HTH, Amit. -- http://amitsaha.github.com/ From steve at pearwood.info Fri Apr 12 05:36:33 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Fri, 12 Apr 2013 13:36:33 +1000 Subject: [Tutor] Looks like a judgment bug. In-Reply-To: References: Message-ID: <51678141.6070809@pearwood.info> On 12/04/13 12:53, Amit Saha wrote: > So for example: > >>>> a=1 >>>> b=1 >>>> a is b > True >>>> id(a) == id(b) > True This is not a very good example, because that behaviour itself is implementation-dependent and not guaranteed. For example, in IronPython 2.6 I get completely different behaviour: >>> a = 1 >>> b = 1 >>> a is b False >>> print id(a), id(b) 43 44 Even in CPython, the implementation you are probably using, the behaviour will depend on all sorts of factors, such as the type of the object, and even the value: py> a = 10001 py> b = 10001 py> a is b False py> a = 1.0 py> b = 1.0 py> a is b False >So, when are identifiers same and when not? That > depends on the type of object - mutable or immutable. No, not really. The best you can say is this: If Python has a choice between creating a new object, and re-using an existing object, and the object is mutable, Python will never re-use the object since that might introduce bugs. If the object is immutable, Python *may* re-use it, or it may not. When does Python have a choice between re-using existing objects? That's a complicated question, and there's no straightforward answer. The best I can do is give some examples: # References to a name will ALWAYS use the same object: x is x # always True # References to another identifier MIGHT re-use the same object: x.attr is x.attr # sometimes True, sometimes False x[index] is x[index] # the same # References to a literal MIGHT re-use the same object, if it is immutable: 'x' is 'x' # might be True ['x'] is ['x'] # always False # The same literal on the same line of code MIGHT be re-used: x = 123.5; y = 123.5; x is y # might be True # ...even if they aren't re-used when on separate lines. x = 123.5 y = 123.5 x is y # probably will be False # If two or more identifiers are assigned to a value at the same time, # Python GUARANTEES to use the same object: x = y = anything_you_like() x is y # always True # Assignment in general never makes a new object: x = something() y = x x is y # always True[1] Object identity is almost never important. About the only time it is important is when comparing things to None. But in practice, you can expect (but not rely on!) CPython to re-use the following: * Small integers. Which values count as small depend on the version, but -1 to 100 is common. * Strings that look like identifiers, e.g. "x", "item", but not "hello world" or "?". But don't rely on this, as it is not guaranteed and could go away at any time. [1] Technically, if you change the current namespace to a custom dict type, you could do anything you like. But that's cheating, and it's harder than it sounds to change the current namespace. -- Steven From amitsaha.in at gmail.com Fri Apr 12 05:42:50 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Fri, 12 Apr 2013 13:42:50 +1000 Subject: [Tutor] Looks like a judgment bug. In-Reply-To: <51678141.6070809@pearwood.info> References: <51678141.6070809@pearwood.info> Message-ID: On Fri, Apr 12, 2013 at 1:36 PM, Steven D'Aprano wrote: > On 12/04/13 12:53, Amit Saha wrote: > >> So for example: >> >>>>> a=1 >>>>> b=1 >>>>> a is b >> >> True >>>>> >>>>> id(a) == id(b) >> >> True > > > > This is not a very good example, because that behaviour itself is > implementation-dependent and not guaranteed. For example, in IronPython 2.6 > I get completely different behaviour: > >>>> a = 1 >>>> b = 1 >>>> a is b > > False >>>> >>>> print id(a), id(b) > > 43 44 > > > Even in CPython, the implementation you are probably using, the behaviour > will depend on all sorts of factors, such as the type of the object, and > even the value: > > py> a = 10001 > py> b = 10001 > py> a is b > False > > py> a = 1.0 > py> b = 1.0 > py> a is b > False > > > > > >> So, when are identifiers same and when not? That >> depends on the type of object - mutable or immutable. > > > No, not really. The best you can say is this: > > If Python has a choice between creating a new object, and re-using an > existing object, and the object is mutable, Python will never re-use the > object since that might introduce bugs. If the object is immutable, Python > *may* re-use it, or it may not. Indeed. My point was to give the original poster at least *some* idea of what the issue really is. If he/she takes that hint and experiments, reads the Python data model, and finds something weird with that statement - he/she will discover the finer/exactly correct details. So, thanks for clarifying this. > > > When does Python have a choice between re-using existing objects? That's a > complicated question, and there's no straightforward answer. The best I can > do is give some examples: > > > # References to a name will ALWAYS use the same object: > x is x # always True > > > # References to another identifier MIGHT re-use the same object: > x.attr is x.attr # sometimes True, sometimes False > x[index] is x[index] # the same > > > # References to a literal MIGHT re-use the same object, if it is immutable: > 'x' is 'x' # might be True > ['x'] is ['x'] # always False > > > # The same literal on the same line of code MIGHT be re-used: > x = 123.5; y = 123.5; x is y # might be True > > # ...even if they aren't re-used when on separate lines. > x = 123.5 > y = 123.5 > x is y # probably will be False > > > # If two or more identifiers are assigned to a value at the same time, > # Python GUARANTEES to use the same object: > x = y = anything_you_like() > x is y # always True > > > # Assignment in general never makes a new object: > x = something() > y = x > x is y # always True[1] > > > Object identity is almost never important. About the only time it is > important is when comparing things to None. > > But in practice, you can expect (but not rely on!) CPython to re-use the > following: > > * Small integers. Which values count as small depend on the version, but -1 > to 100 is common. > > * Strings that look like identifiers, e.g. "x", "item", but not "hello > world" or "?". The link to the SO question discusses string interning to some detail. > > But don't rely on this, as it is not guaranteed and could go away at any > time. Yes, the 'is' check shouldn't really be relied on checks such as those for None objects. -Amit. -- http://amitsaha.github.com/ From amitsaha.in at gmail.com Fri Apr 12 05:45:26 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Fri, 12 Apr 2013 13:45:26 +1000 Subject: [Tutor] Looks like a judgment bug. In-Reply-To: References: <51678141.6070809@pearwood.info> Message-ID: On Fri, Apr 12, 2013 at 1:42 PM, Amit Saha wrote: > On Fri, Apr 12, 2013 at 1:36 PM, Steven D'Aprano wrote: >> On 12/04/13 12:53, Amit Saha wrote: >> >>> So for example: >>> >>>>>> a=1 >>>>>> b=1 >>>>>> a is b >>> >>> True >>>>>> >>>>>> id(a) == id(b) >>> >>> True >> >> >> >> This is not a very good example, because that behaviour itself is >> implementation-dependent and not guaranteed. For example, in IronPython 2.6 >> I get completely different behaviour: >> >>>>> a = 1 >>>>> b = 1 >>>>> a is b >> >> False >>>>> >>>>> print id(a), id(b) >> >> 43 44 >> >> >> Even in CPython, the implementation you are probably using, the behaviour >> will depend on all sorts of factors, such as the type of the object, and >> even the value: >> >> py> a = 10001 >> py> b = 10001 >> py> a is b >> False >> >> py> a = 1.0 >> py> b = 1.0 >> py> a is b >> False >> >> >> >> >> >>> So, when are identifiers same and when not? That >>> depends on the type of object - mutable or immutable. >> >> >> No, not really. The best you can say is this: >> >> If Python has a choice between creating a new object, and re-using an >> existing object, and the object is mutable, Python will never re-use the >> object since that might introduce bugs. If the object is immutable, Python >> *may* re-use it, or it may not. > > Indeed. My point was to give the original poster at least *some* idea > of what the issue really is. If he/she takes that hint and > experiments, reads the Python data model, and finds something weird > with that statement - he/she will discover the finer/exactly correct > details. So, thanks for clarifying this. > > >> >> >> When does Python have a choice between re-using existing objects? That's a >> complicated question, and there's no straightforward answer. The best I can >> do is give some examples: >> >> >> # References to a name will ALWAYS use the same object: >> x is x # always True >> >> >> # References to another identifier MIGHT re-use the same object: >> x.attr is x.attr # sometimes True, sometimes False >> x[index] is x[index] # the same >> >> >> # References to a literal MIGHT re-use the same object, if it is immutable: >> 'x' is 'x' # might be True >> ['x'] is ['x'] # always False >> >> >> # The same literal on the same line of code MIGHT be re-used: >> x = 123.5; y = 123.5; x is y # might be True >> >> # ...even if they aren't re-used when on separate lines. >> x = 123.5 >> y = 123.5 >> x is y # probably will be False >> >> >> # If two or more identifiers are assigned to a value at the same time, >> # Python GUARANTEES to use the same object: >> x = y = anything_you_like() >> x is y # always True >> >> >> # Assignment in general never makes a new object: >> x = something() >> y = x >> x is y # always True[1] >> >> >> Object identity is almost never important. About the only time it is >> important is when comparing things to None. >> >> But in practice, you can expect (but not rely on!) CPython to re-use the >> following: >> >> * Small integers. Which values count as small depend on the version, but -1 >> to 100 is common. >> >> * Strings that look like identifiers, e.g. "x", "item", but not "hello >> world" or "?". > > The link to the SO question discusses string interning to some detail. > >> >> But don't rely on this, as it is not guaranteed and could go away at any >> time. > > Yes, the 'is' check shouldn't really be relied on checks such as those > for None objects. Correction: Yes, the 'is' check shouldn't really be relied on checks other than checks for None objects (for example). -- http://amitsaha.github.com/ From wayne at waynewerner.com Fri Apr 12 13:11:33 2013 From: wayne at waynewerner.com (Wayne Werner) Date: Fri, 12 Apr 2013 06:11:33 -0500 (CDT) Subject: [Tutor] Guidance if possible In-Reply-To: References: Message-ID: On Fri, 12 Apr 2013, Alan Gauld wrote: > On 11/04/13 23:33, Scurvy Scott wrote: > >> the other for something like this. I have no intention of doing >> anything professional/shady/annoying with this code and want to write >> it purely for my own amusement as well as to learn and obviously to >> perhaps win something cool. > > Seems reasonable to me. > > Try looking at the http, urllib and cookie stuff in the stdlib. Ick httplib/urllib - if you want to write code for getting information off a website, the requests module is the way to go: http://docs.python-requests.org/en/latest/ It makes http requests pretty trivial. HTH, Wayne From sbjaved at gmail.com Sat Apr 13 01:52:52 2013 From: sbjaved at gmail.com (Saad Bin Javed) Date: Sat, 13 Apr 2013 04:52:52 +0500 Subject: [Tutor] creating dictionary from a list Message-ID: <51689E54.1010708@gmail.com> Hi, I'm using a script to fetch my calendar events. I split the output at newline which produced a list 'lst'. I'm trying to clean it up and create a dictionary with date:event key value pairs. However this is throwing up a bunch of errors. lst = ['', 'Thu Apr 04 Weigh In', '', 'Sat Apr 06 Collect NIC', \ ' Finish PTI Video', '', 'Wed Apr 10 Serum uric acid test', \ '', 'Sat Apr 13 1:00pm Get flag from dhariwal', '', 'Sun Apr 14 Louis CK Oh My God', '', ''] dict = {} same_day = '' for x in lst: c = x.split(' ') if c[0] is '': for q in c: if q is not '': dict.update({same_day: dict[same_day] + ', ' + q.strip()}) break else: if c[0].find(' '): print c[0] a = c[0].split(' ', 1) same_day = a[0] print a[0], a[1].lstrip() dict.update({a[0] : a[1].lstrip()}) else: same_day = c[0] dict.update({c[0] : c[1]}) I want a dictionary thats like this {'Thu Apr 04': 'Weigh In', 'Sat Apr 13': '1:00pm Get flag from dhariwal'...} Saad From steve at pearwood.info Sat Apr 13 03:22:37 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 13 Apr 2013 11:22:37 +1000 Subject: [Tutor] creating dictionary from a list In-Reply-To: <51689E54.1010708@gmail.com> References: <51689E54.1010708@gmail.com> Message-ID: <5168B35D.2060207@pearwood.info> On 13/04/13 09:52, Saad Bin Javed wrote: > Hi, I'm using a script to fetch my calendar events. I split the output at newline which produced a list 'lst'. I'm trying to clean it up and create a dictionary with date:event key value pairs. However this is throwing up a bunch of errors. Would you like us to guess what the errors are? Please copy and paste the complete traceback, starting with the line Traceback (most recent line last) all the way to the end. In the meantime, my comments are below, interleaved with your code: > lst = ['', 'Thu Apr 04 Weigh In', '', 'Sat Apr 06 Collect NIC', \ > ' Finish PTI Video', '', 'Wed Apr 10 Serum uric acid test', \ > '', 'Sat Apr 13 1:00pm Get flag from dhariwal', '', 'Sun Apr 14 Louis CK Oh My God', '', ''] There's no need to use line-continuation backslash \ inside a list. Any form of bracket (round, square or curly) automatically continues the line. Also, you might find it easier to process the list if you strip out empty items. There are two simple ways to do it: lst = [x for x in list if x != ''] # or lst = filter(None, lst) Either way should work nicely on the data shown, and that might then simplify your processing below. > dict = {} > same_day = '' > for x in lst: > c = x.split(' ') It's best not to rely on an exact number of spaces for the separation, if you can. If you call split() with no argument, the string will be split on runs of whitespace. If you must depend on the difference between one space and two spaces, it's probably best to split on " " (two spaces only), then delete any extra empty strings, as above. Also, please try to use more meaningful variable names. In this case, I would suggest "words" instead of "c". ("c" for "character"?) > if c[0] is '': Do you read the other emails on this tutor list? You should, you will learn a lot from other people's questions. We've just had a few emails explaining that you should never use "is" to test equality, since "is" tests for object identity. So, repeating myself from the last few emails: * always use "if x is None" or "if x is not None" when comparing against None; * otherwise, never use "is", always use == or != when comparing against (nearly) everything else. ("Always" and "never" of course are understood to be general rules which may be ignored by experts when necessary.) So replace the line above with "if c[0] == '':". > for q in c: > if q is not '': Likewise, replace this with "if q != '':". > dict.update({same_day: dict[same_day] + ', ' + q.strip()}) > break I'm not sure why you use a "break" here. That will stop processing the entire list. Is that intended? Maybe you meant to use "continue"? > else: > if c[0].find(' '): You can save an indentation level by using "elif" here. if test1: ... else: if test2: ... else: ... becomes more nicely written as: if test1: ... elif test2: ... else: ... > print c[0] > a = c[0].split(' ', 1) > same_day = a[0] > print a[0], a[1].lstrip() You can simplify your processing here by assigning directly to a list of names. Instead of: a = c[0].split(' ', 1) process(a[0]) process(a[1]) you can give each item a name directly: same_day, text = c[0].split(' ', 1) process(same_day) process(text) which makes your code cleaner and easier to understand. > dict.update({a[0] : a[1].lstrip()}) > else: > same_day = c[0] > dict.update({c[0] : c[1]}) If you're going to assign a value to a name, why don't you actually use the name? same_day = c[0] dict.update({same_day: c[1]}) Try making the changes I've suggested, and see if that makes the code cleaner and easier to understand. It might even fix some of the errors that you are getting. Good luck! -- Steven From sbjaved at gmail.com Sat Apr 13 06:00:26 2013 From: sbjaved at gmail.com (Saad Bin Javed) Date: Sat, 13 Apr 2013 09:00:26 +0500 Subject: [Tutor] creating dictionary from a list In-Reply-To: <51689E54.1010708@gmail.com> References: <51689E54.1010708@gmail.com> Message-ID: <5168D85A.10008@gmail.com> Thank you Steven! I followed your tips and came up with this: lst = filter(None, lst) lst = [item.split(' ', 1) for item in lst] lst = [item for sublist in lst for item in sublist] lst = filter(None, lst) dict = {} for item in lst: if item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')): dict.update({lst[lst.index(item)].lstrip(): lst[lst.index(item)+1].lstrip()}) print dict The program lines have halved :) From fomcl at yahoo.com Sat Apr 13 09:34:42 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 13 Apr 2013 00:34:42 -0700 (PDT) Subject: [Tutor] design question (Django?) Message-ID: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com> Hi, I am doing volunteer work for a charity. The job is to coordinate money collecting activities of people who raise money with collecting-boxes. I am involved with one postal code? 4 (pc4) area (our postal codes have the format 1234 AB (postal code 6). So 'one postal code 4 area'? means [0-9]{4}[A-Z]{2} (1234AA, 1234AB, etc.). One pc4 area is typically divided over a group of 8 people who actually go out there to collect the money. I would like to make a webtool that makes it possible for collectors to select what streets they want to visit. Other collectors of their pc4 area should also be able to see their selection, once it's final (it's a BIG no-no that the same street is visited by multiple collectors in the same week). Selection would be done by selecting street names or pc6 (tick boxes). A selection would be visualized on a map (a different color for each collector). The number of households associated with the selection is shown to see if the selection is a realistic amount. Now, this is where Python comes in. Or wait, maybe not quite yet. The problem should (I think) be divided into two major steps: (1) database design (2) UI design (Python, I hope!) (1) Database design. Here are the database tables I think are necessary: tblPostalcode: pc6, streetname, nHouseholds, isVisitable, remarks tblCollectorSelection: collectorname, streetname, selectiondate (2) UI design. Ah, finally, Python. ;-) I had Django in mind to create the web interface and GeoDjango to display the selection on a map. I am open for other suggestions though (D3?). I am not even sure how realistic this is, given that I have zilch experience with web programming (and Java script). The whole thing should be non-geeky, non-techy for users. I would love to hear your thoughts about this. Does this make sense? Is Django a good choice? Regards, Albert-Jan ps: sorry about the large amount of text. ;-) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~? From alan.gauld at btinternet.com Sat Apr 13 10:00:12 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Apr 2013 09:00:12 +0100 Subject: [Tutor] design question (Django?) In-Reply-To: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com> References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: Some clarification please. > (1) Database design. Here are the database tables I think are necessary: > tblPostalcode: pc6, streetname, nHouseholds, isVisitable, remarks > tblCollectorSelection: collectorname, streetname, selectiondate streetname is in both so presumably is the link between collector and the postcodes? Can a steetname be in multiple postcodes? So if a collector selects a street does he implicitly select multiple post codes? And Does a postcode only have a single street? (Ours can have several) I assume isVisitable is a derived field that you are going to calculate each time based on the number of collectors who have selected the postcode? If so it may be easier and more efficient to have a mapping table to manage the relationship of collectors to postcodes and another table for the collector data (although you don't appear to be holding much collector data, which surprises me... I assume the users will be collectors with login credentials etc?) As always when modelling data the important information is the relationships between the entities and I'm not sure I understand the relationships between street, postcode and collector. HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From fomcl at yahoo.com Sat Apr 13 10:48:01 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 13 Apr 2013 01:48:01 -0700 (PDT) Subject: [Tutor] design question (Django?) In-Reply-To: References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: <1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com> Hi Alan, Thanks for your reply! > Subject: Re: [Tutor] design question (Django?) > > Some clarification please. > >> (1) Database design. Here are the database tables I think are necessary: >> tblPostalcode: pc6, streetname, nHouseholds, isVisitable, remarks >> tblCollectorSelection: collectorname, streetname, selectiondate > > streetname is in both so presumably is the link between collector and the > postcodes? Can a steetname be in multiple postcodes? So if a collector selects a > street does he implicitly select multiple post codes? Yes, a street name can be in multiple postcodes (typically odd and even street numbers of long streets have different postcodes). For example, postcodes (pc4) of the longest street of the country (in The Hague) are 2517, 2555: http://www.postcode.nl/index.php?goto=postcoderesult&action=page&pagenum=0&address=den+haag%2C+Laan+van+Meerdervoort&TreeID=1 So, yes, the collector may select multiple postcodes when selecting just one street. Historically, pc6 is a concept from the mail service. One pc6 is (literally) a handful of mail for a mailman. One record in tblCollectorSelection = one pc6 selected by that collector. But since most people think in terms of street names rather than in pc6, the selection is made by ticking boxes with street names. Come to think of it, I may also need a tblCollectors, with name, adress, postal code, phone number of the collector, preferredPostalCode (some collectors want to collect in another pc6 than where they live). ? > Does a postcode only have a single street? (Ours can have several) It's the same as with you in the UK/Scotland. Often one postcode has just one street, but there are exceptions. > I assume isVisitable is a derived field that you are going to calculate each > time based on the number of collectors who have selected the postcode? isVisitable would be PO boxes, apartment buildings that do not admit any collectors at their main entrance, industrial zones, dangerous neighbourhoods, and maybe a few more categories. >If so it > may be easier and more efficient to have a mapping table to manage the > relationship of collectors to postcodes and another table for the collector data > (although you don't appear to be holding much collector data, which > surprises me... I assume the users will be collectors with login credentials > etc?) yes, collectors are assigned to groups (of about 8 persons) and they should get login credentials (which are stored in tblCollectors (?)). > As always when modelling data the important information is the relationships > between the entities and I'm not sure I understand > the relationships between street, postcode and collector. I think I have to make a diagram of this. This stuff is quite hard for me, but it's important to get the basis right. From brian.van.den.broek at gmail.com Sat Apr 13 10:51:59 2013 From: brian.van.den.broek at gmail.com (Brian van den Broek) Date: Sat, 13 Apr 2013 04:51:59 -0400 Subject: [Tutor] creating dictionary from a list In-Reply-To: <5168B35D.2060207@pearwood.info> References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info> Message-ID: On 12 Apr 2013 21:25, "Steven D'Aprano" wrote: > Also, you might find it easier to process the list if you strip out empty items. There are two simple ways to do it: > > > lst = [x for x in list if x != ''] > # or > lst = filter(None, lst) Hi all, For the first, I would use lst = [x for x in list if x] instead. Best, Brian vdB -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Apr 13 14:11:50 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Apr 2013 13:11:50 +0100 Subject: [Tutor] design question (Django?) In-Reply-To: <1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com> References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: On 13/04/13 09:48, Albert-Jan Roskam wrote: > I think I have to make a diagram of this. This stuff is quite hard You could use a simple UML class diagram (class -> table). See the OOP topic in my V3 tutorial for simple examples. Or you could use a proper entity relationship diagram(ERD) - see wikipedia for details and examples (there are various notational variations) They all show the same concepts. UML will be best if you plan on using OOP in the python code. ERD is better for vanilla database design. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sbjaved at gmail.com Sat Apr 13 16:34:49 2013 From: sbjaved at gmail.com (Saad Bin Javed) Date: Sat, 13 Apr 2013 19:34:49 +0500 Subject: [Tutor] creating dictionary from a list In-Reply-To: References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info> Message-ID: <51696D09.4000103@gmail.com> I ran into a bit of problem with my revised code based on Steven's suggestions. lst = ['', 'Thu Apr 04 Weigh In', '', 'Sat Apr 06 Collect NIC', ' Finish PTI Video', '', 'Wed Apr 10 Serum uric acid test', '', 'Sat Apr 13 1:00pm Get flag from dhariwal', '', 'Sun Apr 14 Louis CK Oh My God', '', ''] lst = filter(None, lst) lst = [item.split(' ') for item in lst] lst = [item for sublist in lst for item in sublist] lst = filter(None, lst) This code would produce: ['Thu Apr 04', ' Weigh In', 'Sat Apr 06', ' Collect NIC', ' Finish PTI Video', 'Wed Apr 10', ' Serum uric acid test', 'Sat Apr 13', ' 1:00pm', 'Get flag from dhariwal', 'Sun Apr 14', ' Download Louis CK Oh My God'] dict = {} for item in lst: if item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')): dict.update({lst[lst.index(item)].lstrip(): lst[lst.index(item)+1].lstrip()}) print dict Such a dictionary would only add the item next to the date as the value. But from the list you can see 'Sat Apr 06' has two items on the agenda while 'Sat Apr 13' show item and a time. So you can understand why such a dict would be useless. I want all agenda items joined as a comma delimited string and added to the date key as a value. I've been mulling over how to go about it. One idea was to get indices of dates in the list and add all items in between them as values. index_keys = [] #0, 2, 5, 7, 9 index_values = [] #1, 3, 4, 6, 8, 10 for item in lst: if item.lstrip().startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')): index_keys.append(lst.index(item)) else: index_values.append(lst.index(item)) But I can't quite get it to understand that i want all items between position 0 and 2 in the list to be assigned to item at 0 in the dictionary and so forth. Ideas? From breamoreboy at yahoo.co.uk Sat Apr 13 17:17:42 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 13 Apr 2013 16:17:42 +0100 Subject: [Tutor] creating dictionary from a list In-Reply-To: <51696D09.4000103@gmail.com> References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info> <51696D09.4000103@gmail.com> Message-ID: On 13/04/2013 15:34, Saad Bin Javed wrote: > I ran into a bit of problem with my revised code based on Steven's > suggestions. > > lst = ['', 'Thu Apr 04 Weigh In', '', 'Sat Apr 06 Collect > NIC', ' Finish PTI Video', '', 'Wed Apr 10 Serum > uric acid test', '', 'Sat Apr 13 1:00pm Get flag from dhariwal', '', > 'Sun Apr 14 Louis CK Oh My God', '', ''] > > lst = filter(None, lst) > lst = [item.split(' ') for item in lst] > lst = [item for sublist in lst for item in sublist] > lst = filter(None, lst) > > This code would produce: > > ['Thu Apr 04', ' Weigh In', 'Sat Apr 06', ' Collect NIC', ' Finish PTI > Video', 'Wed Apr 10', ' Serum uric acid test', 'Sat Apr 13', ' 1:00pm', > 'Get flag from dhariwal', 'Sun Apr 14', ' Download Louis CK Oh My God'] > > dict = {} > for item in lst: > if item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')): > > dict.update({lst[lst.index(item)].lstrip(): > lst[lst.index(item)+1].lstrip()}) > print dict > > Such a dictionary would only add the item next to the date as the value. > But from the list you can see 'Sat Apr 06' has two items on the agenda > while 'Sat Apr 13' show item and a time. So you can understand why such > a dict would be useless. > > I want all agenda items joined as a comma delimited string and added to > the date key as a value. I've been mulling over how to go about it. One > idea was to get indices of dates in the list and add all items in > between them as values. > > index_keys = [] #0, 2, 5, 7, 9 > index_values = [] #1, 3, 4, 6, 8, 10 > for item in lst: > if > item.lstrip().startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')): > index_keys.append(lst.index(item)) > else: > index_values.append(lst.index(item)) > > But I can't quite get it to understand that i want all items between > position 0 and 2 in the list to be assigned to item at 0 in the > dictionary and so forth. > > Ideas? > Don't fight Python, unlike this chap[1] :) Basically if you're looping around any data structure you rarely need to use indexing, so try this approach. for item in lst: if item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')): myDict[item] = [] saveItem = item else: myDict[saveItem].append(item.strip()) [1]http://www.bbc.co.uk/news/world-us-canada-22118773 -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From sbjaved at gmail.com Sat Apr 13 19:38:32 2013 From: sbjaved at gmail.com (Saad Javed) Date: Sat, 13 Apr 2013 22:38:32 +0500 Subject: [Tutor] creating dictionary from a list In-Reply-To: References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info> <51696D09.4000103@gmail.com> Message-ID: What just happened here? :) I am trying to learn python so i'm sorry if my mistakes seem trivial. On Saturday, April 13, 2013, Mark Lawrence wrote: > On 13/04/2013 15:34, Saad Bin Javed wrote: > >> I ran into a bit of problem with my revised code based on Steven's >> suggestions. >> >> lst = ['', 'Thu Apr 04 Weigh In', '', 'Sat Apr 06 Collect >> NIC', ' Finish PTI Video', '', 'Wed Apr 10 Serum >> uric acid test', '', 'Sat Apr 13 1:00pm Get flag from dhariwal', '', >> 'Sun Apr 14 Louis CK Oh My God', '', ''] >> >> lst = filter(None, lst) >> lst = [item.split(' ') for item in lst] >> lst = [item for sublist in lst for item in sublist] >> lst = filter(None, lst) >> >> This code would produce: >> >> ['Thu Apr 04', ' Weigh In', 'Sat Apr 06', ' Collect NIC', ' Finish PTI >> Video', 'Wed Apr 10', ' Serum uric acid test', 'Sat Apr 13', ' 1:00pm', >> 'Get flag from dhariwal', 'Sun Apr 14', ' Download Louis CK Oh My God'] >> >> dict = {} >> for item in lst: >> if item.startswith(('Mon','Tue','**Wed','Thu','Fri','Sat','Sun'))**: >> >> dict.update({lst[lst.index(**item)].lstrip(): >> lst[lst.index(item)+1].lstrip(**)}) >> print dict >> >> Such a dictionary would only add the item next to the date as the value. >> But from the list you can see 'Sat Apr 06' has two items on the agenda >> while 'Sat Apr 13' show item and a time. So you can understand why such >> a dict would be useless. >> >> I want all agenda items joined as a comma delimited string and added to >> the date key as a value. I've been mulling over how to go about it. One >> idea was to get indices of dates in the list and add all items in >> between them as values. >> >> index_keys = [] #0, 2, 5, 7, 9 >> index_values = [] #1, 3, 4, 6, 8, 10 >> for item in lst: >> if >> item.lstrip().startswith(('**Mon','Tue','Wed','Thu','Fri','** >> Sat','Sun')): >> index_keys.append(lst.index(**item)) >> else: >> index_values.append(lst.index(**item)) >> >> But I can't quite get it to understand that i want all items between >> position 0 and 2 in the list to be assigned to item at 0 in the >> dictionary and so forth. >> >> Ideas? >> >> > Don't fight Python, unlike this chap[1] :) Basically if you're looping > around any data structure you rarely need to use indexing, so try this > approach. > > for item in lst: > if item.startswith(('Mon','Tue','**Wed','Thu','Fri','Sat','Sun'))**: > myDict[item] = [] > saveItem = item > else: > myDict[saveItem].append(item.**strip()) > > > [1]http://www.bbc.co.uk/news/**world-us-canada-22118773 > > -- > 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 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sbjaved at gmail.com Sat Apr 13 20:19:58 2013 From: sbjaved at gmail.com (Saad Javed) Date: Sat, 13 Apr 2013 23:19:58 +0500 Subject: [Tutor] creating dictionary from a list In-Reply-To: References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info> <51696D09.4000103@gmail.com> Message-ID: > > Don't fight Python, unlike this chap[1] :) Basically if you're looping > around any data structure you rarely need to use indexing, so try this > approach. > > for item in lst: > if item.startswith(('Mon','Tue','**Wed','Thu','Fri','Sat','Sun'))**: > myDict[item] = [] > saveItem = item > else: > myDict[saveItem].append(item.**strip()) > This creates a dictionary whose keys are out of order in terms of dates. {'Thu Apr 04': ['Weigh In'], 'Sat Apr 06': ['Collect NIC', 'Finish PTI Video'], 'Wed Apr 10': ['Serum uric acid test'], 'Sun Apr 14': ['Download Louis CK Oh My God', '4:00pm', 'UPS Guy'], 'Sat Apr 13': ['1:00pm', 'Get flag from dhariwal']} Sat Apr 13 is appearing after Sun Apr 14. How do you sort this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sat Apr 13 20:29:00 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 13 Apr 2013 19:29:00 +0100 Subject: [Tutor] creating dictionary from a list In-Reply-To: References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info> <51696D09.4000103@gmail.com> Message-ID: On 13/04/2013 19:19, Saad Javed wrote: > > > Don't fight Python, unlike this chap[1] :) Basically if you're > looping around any data structure you rarely need to use indexing, > so try this approach. > > for item in lst: > if > item.startswith(('Mon','Tue','__Wed','Thu','Fri','Sat','Sun'))__: > myDict[item] = [] > saveItem = item > else: > myDict[saveItem].append(item.__strip()) > > > This creates a dictionary whose keys are out of order in terms of dates. > > {'Thu Apr 04': ['Weigh In'], 'Sat Apr 06': ['Collect NIC', 'Finish PTI > Video'], 'Wed Apr 10': ['Serum uric acid test'], 'Sun Apr 14': > ['Download Louis CK Oh My God', '4:00pm', 'UPS Guy'], 'Sat Apr 13': > ['1:00pm', 'Get flag from dhariwal']} > > Sat Apr 13 is appearing after Sun Apr 14. How do you sort this? > http://docs.python.org/3/library/collections.html#collections.OrderedDict -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From sbjaved at gmail.com Sat Apr 13 20:45:43 2013 From: sbjaved at gmail.com (Saad Javed) Date: Sat, 13 Apr 2013 23:45:43 +0500 Subject: [Tutor] creating dictionary from a list In-Reply-To: References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info> <51696D09.4000103@gmail.com> Message-ID: > for item in lst: >> if >> item.startswith(('Mon','Tue','**__Wed','Thu','Fri','Sat','Sun'**))__: >> myDict[item] = [] >> saveItem = item >> else: >> myDict[saveItem].append(item._**_strip()) >> >> Returns: File "gcalcli_agenda_test.py", line 38 if item.startswith(('Mon','Tue','__Wed','Thu','Fri','Sat','Sun'))__: ^ SyntaxError: invalid syntax -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sat Apr 13 21:08:13 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 13 Apr 2013 20:08:13 +0100 Subject: [Tutor] creating dictionary from a list In-Reply-To: References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info> <51696D09.4000103@gmail.com> Message-ID: On 13/04/2013 19:45, Saad Javed wrote: > > for item in lst: > if > > item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__: > myDict[item] = [] > saveItem = item > else: > myDict[saveItem].append(item.____strip()) > > Returns: > File "gcalcli_agenda_test.py", line 38 > if item.startswith(('Mon','Tue','__Wed','Thu','Fri','Sat','Sun'))__: > ^ > SyntaxError: invalid syntax > Please compare your original line with the line above and note the differences. That'll account for the syntax error, which appears to have been introduced by your email client. -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From sbjaved at gmail.com Sat Apr 13 21:30:51 2013 From: sbjaved at gmail.com (Saad Bin Javed) Date: Sun, 14 Apr 2013 00:30:51 +0500 Subject: [Tutor] creating dictionary from a list In-Reply-To: References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info> <51696D09.4000103@gmail.com> Message-ID: <5169B26B.1050707@gmail.com> On 04/14/2013 12:08 AM, Mark Lawrence wrote: > On 13/04/2013 19:45, Saad Javed wrote: >> >> for item in lst: >> if >> >> >> item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__: >> myDict[item] = [] >> saveItem = item >> else: >> myDict[saveItem].append(item.____strip()) >> >> Returns: >> File "gcalcli_agenda_test.py", line 38 >> if item.startswith(('Mon','Tue','__Wed','Thu','Fri','Sat','Sun'))__: >> ^ >> SyntaxError: invalid syntax >> > > Please compare your original line with the line above and note the > differences. That'll account for the syntax error, which appears to > have been introduced by your email client. > This is what I'm using: for item in lst: if item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__: dict[item] = [] saveItem = item else: dict[saveItem].append(item.____strip()) gives: File "gcalcli_agenda_test.py", line 39 if item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__: ^ SyntaxError: invalid syntax From breamoreboy at yahoo.co.uk Sat Apr 13 21:56:55 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 13 Apr 2013 20:56:55 +0100 Subject: [Tutor] creating dictionary from a list In-Reply-To: <5169B26B.1050707@gmail.com> References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info> <51696D09.4000103@gmail.com> <5169B26B.1050707@gmail.com> Message-ID: On 13/04/2013 20:30, Saad Bin Javed wrote: > On 04/14/2013 12:08 AM, Mark Lawrence wrote: >> On 13/04/2013 19:45, Saad Javed wrote: >>> >>> for item in lst: >>> if >>> >>> >>> item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__: >>> myDict[item] = [] >>> saveItem = item >>> else: >>> myDict[saveItem].append(item.____strip()) >>> >>> Returns: >>> File "gcalcli_agenda_test.py", line 38 >>> if >>> item.startswith(('Mon','Tue','__Wed','Thu','Fri','Sat','Sun'))__: >>> ^ >>> SyntaxError: invalid syntax >>> >> >> Please compare your original line with the line above and note the >> differences. That'll account for the syntax error, which appears to >> have been introduced by your email client. >> > This is what I'm using: > > for item in lst: > if > item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__: > dict[item] = [] > saveItem = item > else: > dict[saveItem].append(item.____strip()) > > gives: > File "gcalcli_agenda_test.py", line 39 > if > item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__: > ^ > SyntaxError: invalid syntax > Please compare your original line with the line above and note the differences. That'll account for the syntax error, which appears to have been introduced by your email client. -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From sbjaved at gmail.com Sat Apr 13 22:06:30 2013 From: sbjaved at gmail.com (Saad Javed) Date: Sun, 14 Apr 2013 01:06:30 +0500 Subject: [Tutor] creating dictionary from a list In-Reply-To: References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info> <51696D09.4000103@gmail.com> <5169B26B.1050707@gmail.com> Message-ID: I don't know what I'm doing wrong here. Ive tried copy-pasting the line. I've tried entering underscores manually. doesn't work. -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sat Apr 13 22:24:03 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 13 Apr 2013 21:24:03 +0100 Subject: [Tutor] creating dictionary from a list In-Reply-To: References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info> <51696D09.4000103@gmail.com> <5169B26B.1050707@gmail.com> Message-ID: On 13/04/2013 21:06, Saad Javed wrote: > I don't know what I'm doing wrong here. Ive tried copy-pasting the line. > I've tried entering underscores manually. doesn't work. > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > The underscores are the syntax error. If you'd bothered to read my previous two replies and actually compared your original line of code to the line with the underscores you'd have seen this for yourself. -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From ysoliman at uncc.edu Sat Apr 13 22:53:29 2013 From: ysoliman at uncc.edu (Soliman, Yasmin) Date: Sat, 13 Apr 2013 20:53:29 +0000 Subject: [Tutor] python lists/nested lists Message-ID: <211A029E048A2245A6E00BA02FEFF88A6BF5F62E@BL2PRD0310MB373.namprd03.prod.outlook.com> How can I calculate the average of a list of numbers (eg [2,5,8,7,3] ) and then subtract the avg from the original numbers in the list and print? Also, if I have a nested list: sick_patients=[['Sam', 'M', 65, 'chest pain', 101.6], [['Sarah', 'F', 73, 'dizziness', 98.6], [['Susie', 'F', 34, 'headache', 99.7], [['Scott', 'M', 12, 'stom ache', 102.3] and I would like to print out all the patients with a temp > 100 how would I do so? From breamoreboy at yahoo.co.uk Sat Apr 13 23:16:09 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 13 Apr 2013 22:16:09 +0100 Subject: [Tutor] python lists/nested lists In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A6BF5F62E@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A6BF5F62E@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: On 13/04/2013 21:53, Soliman, Yasmin wrote: > How can I calculate the average of a list of numbers (eg [2,5,8,7,3] ) and then subtract the avg from the original numbers in the list and print? > lst = [2,5,8,7,3] avg = sum(lst) / len(lst) print(avg) for n in lst: print(n - avg) > Also, if I have a nested list: > sick_patients=[['Sam', 'M', 65, 'chest pain', 101.6], [['Sarah', 'F', 73, 'dizziness', 98.6], [['Susie', 'F', 34, 'headache', 99.7], [['Scott', 'M', 12, 'stom ache', 102.3] > > and I would like to print out all the patients with a temp > 100 how would I do so? for patient in sick_patients: if patient[-1] > 100: print(patient) The above works if you fix the syntax errors in sick_patients, you do't need all the double brackets. -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From eryksun at gmail.com Sat Apr 13 23:29:01 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 13 Apr 2013 17:29:01 -0400 Subject: [Tutor] creating dictionary from a list In-Reply-To: <51689E54.1010708@gmail.com> References: <51689E54.1010708@gmail.com> Message-ID: On Fri, Apr 12, 2013 at 7:52 PM, Saad Bin Javed wrote: > Hi, I'm using a script to fetch my calendar events. I split the output at > newline which produced a list 'lst'. I'm trying to clean it up and create a > dictionary with date:event key value pairs. However this is throwing up a > bunch of errors. > > lst = ['', 'Thu Apr 04 Weigh In', '', 'Sat Apr 06 Collect NIC', \ > ' Finish PTI Video', '', 'Wed Apr 10 Serum > uric acid test', \ > '', 'Sat Apr 13 1:00pm Get flag from dhariwal', '', 'Sun Apr 14 > Louis CK Oh My God', '', ''] Don't forget to handle entries with times such as "Sat Apr 13 1:00pm". I think it would be simpler in the long run to use a module that parses iCalendar files. Your calendar application should support exporting to iCalendar (.ics, .ical). http://en.wikipedia.org/wiki/ICalendar Here's an example sorting the events in the Python event calendar: import urllib2 import datetime # https://pypi.python.org/pypi/icalendar import icalendar pyevent_url = ( 'http://www.google.com/calendar/ical/' 'j7gov1cmnqr9tvg14k621j7t5c%40' 'group.calendar.google.com/public/basic.ics') pyevent_ics = urllib2.urlopen(pyevent_url).read() pyevent_cal = icalendar.Calendar.from_ical(pyevent_ics) You need a key function to sort the VEVENT entries by DTSTART: def dtstart_key(vevent): try: dt = vevent['dtstart'].dt except KeyError: dt = datetime.datetime.min if isinstance(dt, datetime.date): dt = datetime.datetime.combine(dt, datetime.time.min) return dt If dt is a datetime.date, this key function converts it to a datetime.datetime set to midnight (datetime.time.min). If the DTSTART field is missing it uses datetime.datetime.min (0001-01-01 00:00). Use walk('vevent') to show only the VEVENT entries in the calendar (i.e. filter out VTODO, VJOURNAL, etc): events = sorted(pyevent_cal.walk('vevent'), key=dtstart_key) The last event (index -1) is PyCon DE 2013 on 14 Oct: >>> events[-1]['description'] vText(u'PyCon DE 2013') >>> events[-1]['dtstart'].dt datetime.date(2013, 10, 14) From alan.gauld at btinternet.com Sat Apr 13 23:30:20 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 13 Apr 2013 22:30:20 +0100 Subject: [Tutor] python lists/nested lists In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A6BF5F62E@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A6BF5F62E@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: On 13/04/13 21:53, Soliman, Yasmin wrote: > How can I calculate the average of a list of numbers (eg [2,5,8,7,3] ) > and then subtract the avg from the original numbers > in the list and print? This sounds like homework which we don;t do for you. However to calculate the average take the sum and divide by the count. Do you know how to do those two things? Once you have the average you need to iterate over your list and subtract the average you calculated (and stored) and print the result. > Also, if I have a nested list: > sick_patients=[ ['Sam', 'M', 65, 'chest pain', 101.6], [ ['Sarah', 'F', 73, 'dizziness', 98.6], [ ['Susie', 'F', 34, 'headache', 99.7], [ ['Scott', 'M', 12, 'stom ache', 102.3] I don't think that's really the structure you intended? but if it is there is a bunch of missing brackets at the end... > and I would like to print out all the patients with a temp > 100 how would I do so? You would iterate over the list testing the temperature element of each sublist against 100 and if necessary printing the result. Now try writing some code and if it doesn't work show us what you've done including any error messages(in full) that you get. PS. As a matter of style your patient records should probably be tuples or dictionaries rather than lists. But that's a nicety to keep for another time... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From zac_vanessa1fan at yahoo.ca Sun Apr 14 00:33:48 2013 From: zac_vanessa1fan at yahoo.ca (Mariel Jane Sanchez) Date: Sat, 13 Apr 2013 15:33:48 -0700 (PDT) Subject: [Tutor] Chapter 3 Projects In-Reply-To: <1365553797.57250.YahooMailNeo@web186001.mail.ir2.yahoo.com> References: <1364168328.77990.YahooMailNeo@web141005.mail.bf1.yahoo.com> <1365552412.1498.YahooMailNeo@web141006.mail.bf1.yahoo.com> <1365553797.57250.YahooMailNeo@web186001.mail.ir2.yahoo.com> Message-ID: <1365892428.9389.YahooMailNeo@web141003.mail.bf1.yahoo.com> Thank you for the help, it was really convenient.? ________________________________ From: ALAN GAULD To: Mariel Jane Sanchez Cc: "tutor at python.org" Sent: Tuesday, April 9, 2013 6:29:57 PM Subject: Re: [Tutor] Chapter 3 Projects Forwarded to group. Please use ReplyAll when responding to tutor posts. >________________________________ > From: Mariel Jane Sanchez >To: Alan Gauld >Sent: Wednesday, 10 April 2013, 1:06 >Subject: Re: [Tutor] Chapter 3 Projects > > > >Thank you so much, I finally figured out the 2nd project. I still have problems with 1 and 3 so I'll try to be more clear.? > >It would help if you posted your code. It shouldn't be long?and its much easier to see where you are getting confused if we can see the code! Chapter 3 Booklet PDF is attached > >Chapter 3? >Project 1 on page 90 on the PDF >"1. Write a program that gets a score from the player and rates it on the following: >- Given a score between 0-999, the program should display the message, 'Nothing to brag about." >- Given a score between 1000-9999, the program should display the message, 'Good score.' >- Given a score over 9999, the program should display the message, 'Very impressive!" >- If the score is a negative number, the program should display the message, 'That is not a legal score!'" > >I'd do it like this score = raw_input('score? ') if score < 0: print 'That is not a legal score' elif score > 9999: print 'Very impressive' elif 9999 >= score >= 1000: print 'Good score.' elif # student to complete... > >I tried using range as another tutor suggested which would make sense since it's dealing with ranges but I still get the same result as before. Can you explain how to do this step by step, if you don't mind? > >You can use range by substituting the elif lines above with: elif score in range(1000,10000): print 'Good score.' Project 3 (Guess My Number code on page 35) >"Modify the Guess My Number program from the chapter so that the player has only five guesses. If the player runs out of guesses, the program should end the game and display an appropriately chastising message" >For my case, I somehow, accidentally programmed it to have only 5 tries and also put a message that says " You ran out of tries," which I think is a good progress. However, on the last try; when I put my guess, hit enter and got the guess wrong, the message loops.? > >I ?showed you the structure for this last time. Without seeing your code I have no idea what?you did wrong. When you first started on Python, how did you do this project so there's no loop at the end? > >I did not do those projects because I did not do the course that?you are doing.? I did not in fact do any courses, I just read the official documents and made? up my own projects. So I can't tell you how I did it. I can only comment on how I might? do it now. ? Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Apr 14 03:36:31 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 14 Apr 2013 11:36:31 +1000 Subject: [Tutor] creating dictionary from a list In-Reply-To: References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info> <51696D09.4000103@gmail.com> Message-ID: <516A081F.5090407@pearwood.info> On 14/04/13 03:38, Saad Javed wrote: > What just happened here? :) > > I am trying to learn python so i'm sorry if my mistakes seem trivial. I have to ask the same question -- what just happened here? Why are you upset? Mark has given you some good advice, and even added some light-hearted joviality about somebody fighting an actual python in real life. Mark's advice about not "fighting" Python the language is excellent advice, but of course as a beginner you aren't expected to know what are the most natural ways to write Python code. If Mark had just stopped there, you would have reason to be annoyed. But he didn't, he gave you some ideas for how to re-write the code to be more "Pythonic" (natural for the language). Mark is correct -- you will very rarely need to use indexing in a for-loop. # don't do this for i in range(len(some_list)): value = some_list[i] process(value) # instead do this for value in some_list: process(value) When you need both the value and the index, the most Pythonic way to do so is to use the built-in function "enumerate": for index, value in enumerate(some_list): some_list[index] = process(value) Also, beware your email program, whatever it is (Outlook?). It has the unfortunate habit of adding extra characters into the text. Mark wrote these six lines: # there are no asterisks or underscores in the following: for item in lst: if item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')): myDict[item] = [] saveItem = item else: myDict[saveItem].append(item.strip()) but by the time it came back from you quoted, it contains extra asterisks added: # mangled by your email client, three lots of double asterisks added: for item in lst: if item.startswith(('Mon','Tue','**Wed','Thu','Fri','Sat','Sun'))**: myDict[item] = [] saveItem = item else: myDict[saveItem].append(item.**strip()) and in a later email from you, somehow those asterisks had turned into underscores! So beware of email clients that try to be "clever", and mangle what is written. -- Steven From steve at pearwood.info Sun Apr 14 03:50:32 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 14 Apr 2013 11:50:32 +1000 Subject: [Tutor] creating dictionary from a list In-Reply-To: References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info> <51696D09.4000103@gmail.com> Message-ID: <516A0B68.8060602@pearwood.info> On 14/04/13 04:19, Saad Javed wrote: > This creates a dictionary whose keys are out of order in terms of dates. Dictionaries are unordered. That is to say, they have no defined order, when you print them, or iterate over them, items will appear in whatever order they happen. If you modify a dict, the order can even change. This is by design: access to items in the dict is extremely fast, especially for large dicts, because Python doesn't have to search through the items one at a time. Dicts are a type of "hash table", which is why dictionary keys must be hashable. (If you don't know what a hash table is, please ask.) So you cannot rely on dicts being in any specific order. There is an OrderedDict in the collections module which remembers the order that items are inserted into the OrderedDict. But that's not quite the same as items being sorted. > {'Thu Apr 04': ['Weigh In'], 'Sat Apr 06': ['Collect NIC', 'Finish PTI > Video'], 'Wed Apr 10': ['Serum uric acid test'], 'Sun Apr 14': ['Download > Louis CK Oh My God', '4:00pm', 'UPS Guy'], 'Sat Apr 13': ['1:00pm', 'Get > flag from dhariwal']} > > Sat Apr 13 is appearing after Sun Apr 14. How do you sort this? You cannot sort a dictionary directly, but you can sort the keys, then iterate over them in that order. keys = sorted(mydict.keys()) for key in keys: print mydict[key] -- Steven From steve at pearwood.info Sun Apr 14 03:57:21 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 14 Apr 2013 11:57:21 +1000 Subject: [Tutor] creating dictionary from a list In-Reply-To: <5169B26B.1050707@gmail.com> References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info> <51696D09.4000103@gmail.com> <5169B26B.1050707@gmail.com> Message-ID: <516A0D01.6000903@pearwood.info> On 14/04/13 05:30, Saad Bin Javed wrote: > This is what I'm using: > > for item in lst: > if item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__: > dict[item] = [] > saveItem = item > else: > dict[saveItem].append(item.____strip()) > > gives: > File "gcalcli_agenda_test.py", line 39 > if item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__: > ^ > SyntaxError: invalid syntax Notice the little caret ^ on the line above "SyntaxError"? It points to where Python discovers a problem with the syntax of your code. The underscores do not belong there. They were added by your email program. Why, I have no idea. Take them out. Likewise with the following underscores. And with the '____Wed' string. This should be your first hint that something is wrong. The days of the week start Mon, Tue, Wed, not Mon, Tue, ____Wed. (I have no idea what your email program will do with these underscores. If in doubt, your mail client should give you a way to look at the raw, untouched message source. In Thunderbird, I can go to the View menu and select "Message Source", and that will show the complete email, including all headers and raw attachments. That at least ought to show you the text without any mangling. Hopefully.) -- Steven From steve at pearwood.info Sun Apr 14 04:08:06 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 14 Apr 2013 12:08:06 +1000 Subject: [Tutor] python lists/nested lists In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A6BF5F62E@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A6BF5F62E@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: <516A0F86.9080002@pearwood.info> On 14/04/13 06:53, Soliman, Yasmin wrote: > How can I calculate the average of a list of numbers (eg [2,5,8,7,3] ) and then subtract the avg from the original numbers in the list and print? You calculate the average by summing the list, then dividing by the number of items. To sum a list of numbers, use the sum() function. total = sum(some_list) To get the number of items, use the len() function. num = len(some_list) To divide, use the / operator. BUT beware, if you are using Python 2, there is a small problem with division: by default, Python will do integer division, which is not what you want. (Python 3 fixes this problem). For example, if you say 17/3 in Python 2, you will get 5, instead of 5.666666666666667. You can fix that two ways: put this line at the very top of your program, before anything except comments: from __future__ import division Or, use floats instead of ints. If you say 17.0/3 you will get 5.666666666666667 as expected. If you have a variable, you can convert it into a float using the float() function. Once you have the average, you can print the differences like this: for value in some_list: print value - average > Also, if I have a nested list: > sick_patients=[['Sam', 'M', 65, 'chest pain', 101.6], [['Sarah', 'F', 73, 'dizziness', 98.6], [['Susie', 'F', 34, 'headache', 99.7], [['Scott', 'M', 12, 'stom ache', 102.3] > > and I would like to print out all the patients with a temp > 100 how would I do so? for record in sick_patients: temp = ... # you have to fill this in, replace the dots with code if temp > 100: print record How would you extract the temperature from the internal lists? (Hint: the patient's name is record[0], their sex is record[1].) -- Steven From fomcl at yahoo.com Sun Apr 14 13:06:12 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 14 Apr 2013 04:06:12 -0700 (PDT) Subject: [Tutor] design question (Django?) In-Reply-To: References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com> Message-ID: <1365937572.26277.YahooMailNeo@web163801.mail.gq1.yahoo.com> ?> Subject: Re: [Tutor] design question (Django?) > > On 13/04/13 09:48, Albert-Jan Roskam wrote: > >> I think I have to make a diagram of this. This stuff is quite hard > > You could use a simple UML class diagram (class -> table). See the OOP topic > in my V3 tutorial for simple examples. > > Or you could use a proper entity relationship diagram(ERD) - see wikipedia for > details and examples (there are various notational variations) > > They all show the same concepts. UML will be best if you plan > on using OOP in the python code. ERD is better for vanilla database design. Hi Alan, I am reading it now. Thanks for the suggestion. I have to read more about Django to decide whether this is the way to do it. First impression: yes. The database abstraction API also implies that I should use OOP. Step #1: defining the model ;-) https://docs.djangoproject.com/en/dev/topics/db/models/ Would it also be a good idea to simultaneously make a paper-and-pencil drawing of the UI? It seems like a good way to figure out what I really want. For me, the hardest part of software construction is the design stage. Regards, Albert-Jan From dfjennings at gmail.com Sun Apr 14 15:27:26 2013 From: dfjennings at gmail.com (Don Jennings) Date: Sun, 14 Apr 2013 09:27:26 -0400 Subject: [Tutor] design question (Django?) In-Reply-To: <1365937572.26277.YahooMailNeo@web163801.mail.gq1.yahoo.com> References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1365937572.26277.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: On Apr 14, 2013, at 7:06 AM, Albert-Jan Roskam wrote: > > > > Subject: Re: [Tutor] design question (Django?) >> >> On 13/04/13 09:48, Albert-Jan Roskam wrote: >> >>> I think I have to make a diagram of this. This stuff is quite hard >> >> You could use a simple UML class diagram (class -> table). See the OOP topic >> in my V3 tutorial for simple examples. >> >> Or you could use a proper entity relationship diagram(ERD) - see wikipedia for >> details and examples (there are various notational variations) >> >> They all show the same concepts. UML will be best if you plan >> on using OOP in the python code. ERD is better for vanilla database design. > > Hi Alan, I am reading it now. Thanks for the suggestion. I have to read more about Django to decide whether this is the way to do it. First impression: yes. The database abstraction API also implies that I should use OOP. Step #1: defining the model ;-) https://docs.djangoproject.com/en/dev/topics/db/models/ > Would it also be a good idea to simultaneously make a paper-and-pencil drawing of the UI? Absolutely! Test it with three users. See Jakob Nielsen's brief take on the matter: http://www.nngroup.com/articles/paper-prototyping/ Take care, Don From alan.gauld at btinternet.com Sun Apr 14 16:45:00 2013 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 14 Apr 2013 15:45:00 +0100 (BST) Subject: [Tutor] design question (Django?) In-Reply-To: <1365937572.26277.YahooMailNeo@web163801.mail.gq1.yahoo.com> References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1365937572.26277.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: <1365950700.87155.YahooMailNeo@web186005.mail.ir2.yahoo.com> >Would it also be a good idea to simultaneously make a paper-and-pencil drawing of the UI??Personally I do. At work we call these UI sketches ?"wireframes" and they are used to figure? out the interaction. The focus is on the relative position of controls and the workflow for? the user rather than the cosmetics.?There are lots of articles and web sites on the science? of UI design and usability. the hardest part of software construction is the design stage.It always is and the bigger the project the more formal the design needs to be. Most of the projects discussed on the tutor list can be done with little or no design? (the equivalent of building a dog kennel or garden shed) but as you progress to? more complex designs (think house extension) you need at least a basic design? diagram to follow. And as you move into big projects with multiple developers? or even multiple teams (think skyscraper or?airport terminal) you really need? clear, formally expressed designs to keep?everything consistent. One of the things? I like about UML is that it can be used at all levels, just pick the bits that are? relevant to your project. HTH, Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sbjaved at gmail.com Sun Apr 14 18:46:35 2013 From: sbjaved at gmail.com (Saad Javed) Date: Sun, 14 Apr 2013 21:46:35 +0500 Subject: [Tutor] creating dictionary from a list In-Reply-To: <516A0D01.6000903@pearwood.info> References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info> <51696D09.4000103@gmail.com> <5169B26B.1050707@gmail.com> <516A0D01.6000903@pearwood.info> Message-ID: Steven, You're right about Mark's email. I didn't get the humor and thought the remark was kinda tough on me. You correctly pointed out his intent. So my apologies to Mark. As for the underscores, what happened is that *I didn't voluntarily add the underscores to begin with. *If you read the emails again, after Mark's answer about not looping, I asked that the dictionary created as a result of his code wasn't ordered. In reply, he sent me a portion of his previous email containing underscores before Wed (__Wed)! I thought it was the strange but since I'm a beginner, I copied the code and applied it which of course threw up a syntax error. What I wanted to ask Mark was that *why* had *he* added underscores because they were throwing up errors for me. He kept pointing me to his earlier email and asking me compare my line with his line and I'll find out what the problem is. In my mind, I thought I was not entering the underscores correctly or at the right position. As you have explained it turns out it was the email client which was adding stuff on its own. It added the underscores to Mark's first response to my dictionary order question and I took it as *Mark's answer.* Regards, Saad -------------- next part -------------- An HTML attachment was scrubbed... URL: From dkemeza at gmail.com Tue Apr 9 19:14:07 2013 From: dkemeza at gmail.com (David Kemeza) Date: Tue, 9 Apr 2013 13:14:07 -0400 Subject: [Tutor] FYI: An Introduction to Interactive Programming in Python In-Reply-To: References: <516359B2.2040300@pearwood.info> Message-ID: I'd really be interested in see that code since. I'm learning python right now and looking at code helps with my learning process. Thanx -dave On Tue, Apr 9, 2013 at 11:32 AM, brian arb wrote: > One game wrote along time ago when I was first learning Python and App > Engine is http://cdacabeecdebcabab.appspot.com/ > It's kind of a non-interactive Sudoku puzzle, the only really > interaction is to click "solve this" or "display next puzzle" then to watch > the python code written attempt to solve the puzzle you click on the button > "next iteration" until you reach a solution or the code fails to resolve > any more of the cells. > > > > > On Mon, Apr 8, 2013 at 7:58 PM, Steven D'Aprano wrote: > >> On 09/04/13 06:38, brian arb wrote: >> >>> An Introduction to Interactive Programming in PythonJoe Warren, Scott >>> >>> Rixner, Stephen Wong and John Greiner >>> >>> This course is designed to be a fun introduction to the basics of >>> programming in Python. Our main focus will be on building simple >>> interactive games such as Pong, Blackjack and Asteroids. >>> >>> https://www.coursera.org/**course/interactivepython >>> >> >> Thanks for the link Brian. >> >> As an aside, I wonder, apart from Conway's Game of Life, which isn't >> actually a game at all, what's a non-interactive game? >> >> >> >> -- >> Steven >> ______________________________**_________________ >> 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 luckytsukune at gmail.com Wed Apr 10 16:21:54 2013 From: luckytsukune at gmail.com (John Bochicchio) Date: Wed, 10 Apr 2013 10:21:54 -0400 Subject: [Tutor] Issue With a Python Game Message-ID: I have a question about a game I am making. I finished the overall code, but keep getting errors when I try to play. This is my most common error: C:\Users\John\Documents\Python Games\Noah>python nickeladventuredemo.py Traceback (most recent call last): File "nickeladventuredemo.py", line 451, in main() File "nickeladventuredemo.py", line 78, in main levels = readLevelsFile('levels.txt') File "nickeladventuredemo.py", line 371, in readLevelsFile assert startx != None and starty!= None, 'Level %s (around line %s) in %s i s missing a "@" or "+" to mark the start point.' % (levelNum+1, lineNum, filenam e) AssertionError: Level 1 (around line 10) in levels.txt is missing a "@" or "+" t o mark the start point. The error has something to do with the levels. I will attach the code and levels, as they are fairly long. -- 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: -------------- next part -------------- ; Starting demo level: ######## ## # # . # # $ # # .$@$. # ####$ # #. # # ## ##### ; 1 ### ## # #### ## ### # ## $ # # @$ # # ### $### # # #.. # ## ##.# ## # ## # ## ####### ; 2 ## ##### ## ## . # # ## $. # ## $ # ## $@ ### # $ ## #.. ## ## # # ## ##### # ; 3 ##### ## # # # #### # $ ## # ####$ $# # $ $ # ## ## $ $ $# # .# $ $ # # .# # ##### ######### #.... @ # #.... # ## ###### #### ; 4 ########### ## # @# ### $ $$# # # ##$ $$ # # # $ # # ###### ###### #.. ..$ #*## # .. ### # ..##### ######### ; 5 ########### ## # ## ### $ $#$ $ ### # #$ $ # $ $# # # $ ..#.. $ # # $...#...$ # # $ .. * .. $ # ###### @ ###### # $ .. .. $ # # $...#...$ # # $ ..#.. $ # # #$ $ # $ $# # ### $ $#$ $ ### ## # ## ########### ; 6 ########### ###. .$. .### ## $ $ $ ## ## ..$.. ## ##$#$#$## #.$ $.# # @ # ### ### ## $ $ ## #. $ .# ### . ### ##### ; 7 ###### #### ## # ### # # ## ### ### #### # $ # # $ @ ...*.. $ # # $ $ ## ### ### ### ### # ##### # ### # #### ##### ; 8 ####### # ## ##### ### ## # # ## #@$***. ##$ # # # ## .# ## ## # $ # ## ####.$.# ## # ###### ## #### ; 9 ######### #. . # #.$. . # ## ###@ # # $ ## # $$ ## # $ # # ### #### ; 10 ###### # # # @ ### #### # # # ####..#.#$##### # $ $ ##... # # .....#$$ # ###### ##$## ##### # $ # #### #### # # # ##### ### $ # # $ $ # # #$# #### # # ####### ; 11 #### ### #### # @ ## # #. .#.### # $$$ $$$ # ###.#.#.# # ## # #### ### #### ; 12 ##### # # ##### # ####### # ##### # ..... # ##### # ## # # # # # # $ $ $ $ $ # ## ## $ # # # ##......#### ### $$ ### # ## * # # # $$ # ##########+$$ ## # # #.$ $# # ######## #.## # ######## ; 13 ####### ### ## # ### # # # # ###$#@ # # # ##### # # # *. # ##$$# *.## # *..# #### #...## # #$$$ # # $ # ##### # #### ; 14 ####### ## # # # *.$.# # *.#.### # #$@$$ # # ## # # ###### # ##### ; 15 #### #@ # ## # # .$# #$. # ###..$### # ..$ # # $ $ # # ##### # # # # ##### ; 16 ###### ## # ### ## # # ## # # $.# # ## $ $.# # # #####. ## # $. @# # $. #### ### # #*# # ### #### .$ # # .$ # ## .##### # # #.$ $ ## # #.$ # # ## # # ## ### # ## ###### ; 17 ########### ## . . . . ### # $$ $ $ $ # # ######## # ##### #### ## $ # # # # # $ $ # ### # # ## # # #### $ # #... ##### $ #### ### #... @ $ # # #...############ $ $ # ##### ##### # #### ; 18 #### ##### # # # #$ $ $ # #.*.*.*# #*.*.*.# # $ $ $# #......# #.*.*.*# #$ $ $ # # $ $ $# #$ $ $ # # # #@ ##### #### ; 19 ##### # ####### # $ ## ## ###### ## # # # # ######## # # ## $ ## # #. #@###### $ ## # #.# ### ## $ ## # #. # ## $ ## # #.# # ## ## $ ## ## #.# ## ### ## $ # # #.# # #*## ## # # .# # # ##*## ##### ###### # ###### ##### ; 20 #### # # ######$.# # $ $.# # $@$...# # $$$..## # $ ..# ######## ; 21 ##### ######## # ### . $ # # $ *.. #$ ## ## $# ..* $ @# # $ . ### # ######## ##### ; 22 ##### #### #@ .### ### #### $$ $ # # # . . ## # # $ # . . ## # ## . $ $$ # # # # ###. # # # #### ##### # # # # ####### # #### # .$ # #### # ## ##### ### ; 23 ####### ###### ###### # . ..$#$.. . # # $ $ . $ $ # ###$####@####$### # $ $ . $ $ # # . ..$#$.. . # ###### ###### ####### ; 24 ###### # ## ####### $ # # $ $ $ #$ # # #. $ # ####.#.# $### # ..... # # $ ..##$# ### ## .. # # $.#$ # $# # $ # # ##@ # #### ## #### #### ; 25 ##### ##### ##### # .#$ $ # # #. $$$ @ ## # .#$ $ # ###.# $ $ # #. ##$ ### #######*###.$ # # $ ....#### ## #$#$$....# # $ $ #..# # $ #..# # ########## ##### ; 26 #### ########### # # $ $ $ $ ## # # # # # #$## ##. . . . . .# #$# # # # #$#### ###. . . . . . # ###$# # # # # @ # # $ $ $ $ ### # ########### #### ; 27 ######## ###### ########## ## $ ### ## # $ $ ## # ######### # # $ # # # # $ $ # # ######### # # # $ # # #. . . . # # # $ $ # # . . . .## # # $ # # # . . . . # # ##$ $## # #### # # ## # #@ # # #### ###### ##### # # ## # # # ##### ## ## ## ## ###### ; 28 ###### # ### ##### $ $ # #### #.# ## # $ #$#.##$##### # $$. .#.$ ## # $.#.#.##### #### ## ....... @# # ####$ #.### #$###$## ## $ . # $ $ $ # # $ ### # # # ############ ##### ; 29 #### # # #### # ######## ####### # # ### ## $ # ##.###### ... #. # #.# # .# # $ # #$$$$#$$$ #.# ##. # #.# $ $ #.. ## #.# $ $ # # ## # # $$ # ##### #. ##$ ###### #. # $. # ##. @ ###.#$ # # # # # # ## ###### ###### ; 30 ##### # # # # ###### ### ## ##### # ### # # ## #$$ # ##$ ########## $ $ # ### ## ..........$ #$$@# # # $$# ####### $ # # $ #...# ### #### # # $ ### ## #### ######## # # # # # ###### ; 31 ######### ### ## #### ##### # * ## # # # #### **** ####$.## # .$ *@* $. # ##.$#### **** #### # # # ## * # ##### #### ## ### ######### ; 32 ##### # # ######### $ # ###### # # # # # # # $ $ #@# ### ## #### ### ## ### # $ $ # # # # $ $ # #$ # $$ $$ # ###### $ # # # # ## ## ############### # .# $ # # #.. # ###### #...#### # #....# #### #....# ###### ; 33 ####### ## ## # ### # # ## $ #### # # .# $.#### # # * *###.$ # # # *# ### ##### # # @ * * # # # # # ### #*# * # # ## # * *.# # ####### # # # ....$ $ # # # ## $# $####$ # ###* * # ####### # ########## #### # # ## ############ #### ; 34 ##### # ..######## # ......# # #.. ##$$ $# #####.## $ # # ....# $ $$# ##### ## # .. .#$ $ # # # # ##.### $$ $### # ### # ## # $ # # # @ #### # # # ###$ # # # # $ $ # # #### ### ####$$## # ## #### # # # # ## ###### # #### ## # # $ # ## # # # ###### ##### ; 35 ##### # # ## # ##### # ## ####### # # $ #### # #### $ $$ # # ##### # $$$ $ #$ # # $ $ $ $ ###### ###$ #$ $ $ # # $ $$ ### @ ## # $ $$$$####... # # $ $ #. .#...# ### $$$$ ...... # # ##..#.....# ###### ##.....#### # .....# # ########## ; 36 ##### #### # ###### # # # $ $ # # #### # $##$ ### # ######### # $ $ # # ..........# $ # ###### ##....@### # $$ # # # #####.## # ## $ # # # #$ $$ $ # #### # ##### # # $ # # # # # # ### #### # # # # ##### # # ##### ##### # ####### ; 37 ##### ######### # # # # ### #$### ##### # # # ##### # $. . # # . . . . # # # # #$### # # # # # # #$# # . . . . $ $ $ $ . . # ###$# # #$###########$# #$# # . . ## # . # ###$# #$####### # #$# #$### # . .$ $ $ # # . . # #$# # # # # #####$# # # # # . . . . . $ . . . # ### # # # # # # # # # # # # $ $. . .$ $ $ $ $ $ # ##### # # ############# # @ # ####### ; 38 #### #### ######## # ###@ ## # # # # # # ### $ $ # # ....########## # #..# # . # ## $ $ $# # #..# ### # $ $$$ # # $ $ # # ...# $ $$ # # # # # ..# $ $ $ # # ## # ##...# $ $$ $ #$# ##### # ## $ $ $ # # ### ###### ### # ### # . ## #### . . # ## . # # #.#.# # # . # # # # # # # . #### ######### # ## #### ; 39 #### ##### # ####### #### # # @ $ #### $ # # ###.# # $$ # ###.## $ #$ # # ## # ..# $ ...# ### ## # $ ...$##.## ## ##.###$ $.. $$ ## #. #. .### $ $ # # $...## ## # # ## ###### # ## ## ## ##### # $$ # # $ # ### $ # # ## #### ; 40 ####### #### # # # ### $$$ # # ....$ ##### # ..# $ # @# ###$##$#### # ###### #.*....$ $ ### ##### # ..##### ## $ $ # #....*.... # $$ # $ # ########## #$$ ## # # # $.### $ ## # $###$# # # ##### $ $ #### #### #### ###### ; 41 ##### # # ### ######## ## *** # # # # * * ## # ##### ## *** ## # ## ## ### #### # # # # # # # # ####$ $### ## ## # ## $...$ ## ##### # ## . at . # # # # $...$ ## ########$ $### # # ##### ; 42 #### # ###### # #### # $ $ # ##### ##### ### $ # # # $ # # # ##$###### # $### # ...# # ## #@#$ ##.#.# # # # #...# # # $ ##$ $#...##### ### ## #... # # # $ $ $ # # # # $### ###### # # # # # ############# # ##### ; 43 #### ## ############# ## .......... # ## # ####$### ## # # # # ## # # # $$$ # # ##### ##### # . .# ### . . . ## # $. .# # $$ $ $ @# ####### ### # ####### # $ $ # ## ### # $ $ # # ## # #### # $### #### # # # ## #### # $ $$$ # ## # ## # ## # ## #### $$$ # ## ####### ..... ##### # $ ###### # # ###### ## #### ##### #### ; 44 ############# ## # ### # $ $$$$$ # ### $ $ ### # # $ $ $### # # ## $ ## # ### #### #### # ### # ### #### #### # #@ $ ### #.# ##### # $ $ ## # .... # # $$ ## ####..... # ## $ # #..#.## # # $ $ ## #...... # # $ $ # # . ..# ## ## $ # ## ##.# # # ## # # ###### ######## ; 45 #### ######## # ##### ## # # # $ ### $ $ # # $ # ## $ #### ### # # ###$## # ##### ### #### $ # # # $ $$## .. ##$ # # $$ # $ ## ## # $## #### # #### ### # ##$ ###..#..# # ###.. # .....### # # *.### # #.. # ##$$# *.##@ # # # # *. #### ### # ###### # # # ##### ## ### # ### #### ; 46 #### ################### ##### ### .$ # ### $. #####$#### # # # $. #### # . ### .# # $ $.### ## # #### # $.# $# ### $.## # # # # # # $ # # ###### # ## #$ $ ## #. # # ##### #.#. # ### # # ##### # # ### ### # # ##*## # .# # #$$* ## #*### ### ## ## ## # .#. ## ###*# # .$ .# $.$.## ### # ##*## # #.#### # $. ## #*### # $$ ### ### ## ## ###*# # # . $@$ #######. # ##### # ### ####.# $ # # # ########### # ####### #### ; 47 ######### # # ###### # $ ###### ### # #$#$ $ $ # $ # # $ $@$ $ $ $ $$ # # $ $# $ # $$$ # # $ $ ####### ##### ## ###....##### ..# ###$$# $$$$ #...* ..# # ## #.. # # # #$###....##*## # ##..$. .... # ### .* .#....# # ################## ; 48 #### #### ## # # # ####### ### ###$ ## # ### # $ $ ### # # $ $ ###$ # # # ### ### # # # # # $ # ## ### # ### # $ # #@ ## # $# # ### ### # # # $ # # $ $ # # # # ## # $ # #. # ## # # ## #.. ### ## # # ## #... ## ### # #### #....## # $.*.## ############..## #### ; 49 'Parallel Logic' ######################### # # # # # # # # # # $#$ # $#$ # $#$ # $#$ # # # # # # # # # # ## # ### # ### # ### # ## # # # # # # # # # # # # # # # ### # ### # ### # ### # # # # # # # # # # # # # $ # # # # # ### # ### # ### # # # . . . . + . . . . # ######################### ; 50 'Particle Theory' # # # # # # # # # # # # # # # # # # # # # # # # # # .$ . $. . $ .$ # # $# #$# # # #$# # # # # # . . $. . .$ . . # # #$# # # # #$#$ $# #$# # # . .$ .$ . $. . # # $# # # # #@# # # # #$ # # . .$ . $. $. . # # #$# #$ $#$# # # # #$# # # . . $. . .$ . . # # # # # #$# # # #$# #$ # # $. $ . .$ . $. # # # # # # # # # # # # # # # # # # # # # # # # # # -------------- next part -------------- A non-text attachment was scrubbed... Name: nickeladventuredemo.py Type: application/octet-stream Size: 16531 bytes Desc: not available URL: From luckytsukune at gmail.com Sat Apr 13 15:13:07 2013 From: luckytsukune at gmail.com (John Bochicchio) Date: Sat, 13 Apr 2013 09:13:07 -0400 Subject: [Tutor] Issue With a Python Game Message-ID: I have a question about a game I am making. I finished the overall code, but keep getting errors when I try to play. This is my most common error: C:\Users\John\Documents\Python Games\Noah>python nickeladventuredemo.py Traceback (most recent call last): File "nickeladventuredemo.py", line 451, in main() File "nickeladventuredemo.py", line 78, in main levels = readLevelsFile('levels.txt') File "nickeladventuredemo.py", line 371, in readLevelsFile assert startx != None and starty!= None, 'Level %s (around line %s) in %s i s missing a "@" or "+" to mark the start point.' % (levelNum+1, lineNum, filenam e) AssertionError: Level 1 (around line 10) in levels.txt is missing a "@" or "+" t o mark the start point. The Code: import random, sys, copy, os, pygame from pygame.locals import * FPS = 30 WINWIDTH = 800 WINHEIGHT = 600 HALF_WINWIDTH = int(WINWIDTH / 2) HALF_WINHEIGHT = int(WINHEIGHT / 2) TILEWIDTH = 50 TILEHEIGHT = 85 TILEFLOORHEIGHT = 45 CAM_MOVE_SPEED = 5 OUTSIDE_DECORATION_PCT = 20 BRIGHTBLUE = ( 0, 170, 255) WHITE = (255, 255, 255) BGCOLOR = BRIGHTBLUE TEXTCOLOR = WHITE UP = 'up' DOWN = 'down' LEFT = 'left' RIGHT = 'right' def main(): global FPSCLOCK, DISPLAYSURF, IMAGESDICT, TILEMAPPING, OUTSIDECOMAPPING, BASICFONT, PLAYERIMAGES, currentImage pygame.init() FPSCLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((WINWIDTH, WINHEIGHT)) pygame.display.set_caption('Noah Nickel Adventure!') BASICFONT = pygame.font.Font('freesansbold.ttf', 18) IMAGESDICT = {'uncovered goal': pygame.image.load('RedSelector.png'), 'covered goal': pygame.image.load('Selector.png'), 'star': pygame.image.load('Star.png'), 'corner': pygame.image.load('Wall Block Tall.png'), 'wall': pygame.image.load('Wood Block Tall.png'), 'inside floor': pygame.image.load('Plain Block.png'), 'outside floor': pygame.image.load('Grass Block.png'), 'title': pygame.image.load('star_title.png'), 'solved': pygame.image.load('star_solved.png'), 'princess': pygame.image.load('princess.png'), 'boy': pygame.image.load('boy.png'), 'catgirl': pygame.image.load('catgirl.png'), 'horngirl': pygame.image.load('horngirl.png'), 'pinkgirl': pygame.image.load('pinkgirl.png'), 'rock': pygame.image.load('Rock.png'), 'short tree': pygame.image.load('Tree_Short.png'), 'tall tree': pygame.image.load('Tree_Tall.png'), 'ugly tree': pygame.image.load('Tree_Ugly.png')} TILEMAPPING = {'X': IMAGESDICT['corner'], '#': IMAGESDICT['wall'], 'o': IMAGESDICT['inside floor'], ' ': IMAGESDICT['outside floor']} OUTSIDECOMAPPING = {'1': IMAGESDICT['rock'], '2': IMAGESDICT['short tree'], '3': IMAGESDICT['tall tree'], '4': IMAGESDICT['ugly tree']} #Super important to remember: #DEAR GOD REMEMBER THIS IS AN INDEX OF PLAYER IMAGES. currentImage = 0 PLAYERIMAGES = [IMAGESDICT['princess'], IMAGESDICT['boy'], IMAGESDICT['catgirl'], IMAGESDICT['horngirl'], IMAGESDICT['pinkgirl']] startScreen() levels = readLevelsFile('levels.txt') currentLevelIndex = 0 while True: result = runLevel(levels, currentLevelIndex) if result in ('solved', 'next'): currentLevelIndex += 1 if currentLevelIndex >= len(levels): currentLevelIndex = 0 elif result == 'back': currentLevelIndex -= 1 if currentLevelIndex <0: currentLevelIndex = len(levels)-1 elif result == 'reset': pass def runLevel(levels, levelNum): global currentImage level0bj = levels[levelnum] map0bj = decorateMap(level0bj['map0bj'], level0bj['startState']['player']) gameState0bj = copy.deepcopy(level0bj['startState']) mapNeedsRedraw = True levelSurf = BASICFONT.render('Level %s of %s' % (level0bj['levelNum'] +1, totalNumOfLevels), 1, TEXTCOLOR) levelRect = levelSurf.get_rect() levelRect.bottomleft = (20, WINHEIGHT - 35) mapWidth = len(map0bj) * TITLEWIDTH mapHeight = (len(map0bj[0]) - 1) * (TITLEHEIGHT - TILEFLOORHEIGHT) + TILEHEIGHT MAX_CAM_X_PAN = abs(HALF_WINHEIGHT - int(mapHeight / 2)) + TILEWIDTH MAX_CAM_Y_PAN = abs(HALF_WINWIDTH - int(mapWidth / 2)) + TILEHEIGHT levelIsComplete = False camera0ffsetX = 0 camera0ffsety = 0 cameraUp = False cameraDown = False cameraLeft = False cameraRight = False while True: playerMoveTo = None kepPressed = False for event in pygame.event.get(): if event.type == QUIT: terminate() elif event.type == KEYDOWN: keyPressed == True if event.key == K_LEFT: playerMoveTo = LEFT elif event.key == K_RIGHT: playerMoveTo = RIGHT elif event.key == K_UP: playerMoveTo = UP elif event.key == K_DOWN: playerMoveTo = DOWN elif event.key == K_a: cameraLeft = True elif event.key == K_d: cameraRight = True elif event.key == K_w: cameraUp = True elif event.key == K_s: cameraDown = True elif event.key == K_n: return 'next' elif event.key == K_b: return 'back' elif event.key == K_ESCAPE: terminate() #Perhaps add a print box confirmation? elif event.key == K_BACKSPACE: return 'reset' #Same confirmation for level reset. elif event.key == K_p: currentImage += 1 if currentImage >= len(PLAYERIMAGES): currentImage = 0 mapNeedsRedraw = True elif event.type == KEYUP: if event.key == K_a: cameraLeft = False elif event.key == K_d: cameraRight = False elif event.key == K_w: cameraUp = False elif event.key == K_s: cameraDown = False if playerMoveTo != None and not levelIsComplete: moved = makeMove(map0bj, gameState0bj, playerMoveTo) if moved: gameState0bj['stepCounter'] += 1 mapNeedsRedraw = True if isLevelFinished(level0bj, gameState0bj): levelIsComplete = True keyPressed = False DISPLAYSURF.fill(BGCOLOR) if mapNeedsRedraw: mapSurf = drawMap(map0bj, gameState0bj, level0bj['goals']) mapNeedsRedraw = False if cameraUp and camera0ffsetY < MAX_CAM_X_PAN: camera0ffsetY += CAM_MOVE_SPEED elif cameraDown and camera0ffsetY > -MAX_CAM_X_PAN: camera0ffsetY -= CAM_MOVE_SPEED if cameraLeft and camera0ffsetX < MAX_CAM_Y_PAN: camera0ffsetX += CAM_MOVE_SPEED elif cameraRight and camera0ffsetX > -MAX_CAM_Y_PAN: camera0ffsetX -= CAM_MOVE_SPEED mapSurfRect = mapSurf.get_rect() mapSurfRect.center = (HALF_WINWIDTH + camera0ffsetX, HALF_WINHEIGHT + camera0ffsetY) DISPLAYSURF.blit(mapSurf, levelRect) stepSurf = BASICFONT.render('Steps: %s' %(gameState0bj['stepCounter']), 1, TEXTCOLOR) stepRect = stepSurf.get_rect() stepRect.bottomleft = (20, WINHEIGHT -10) DISPLAYSURF.blit(stepSurf, stepRect) if levelIsComplete: solvedRect = IMAGESDICT['solved'].get_rect() dolvedRect.center = (HALF_WINWIDTH, HALF_WINHEIGHT) DISPLAYSURF.blit(IMAGESDICT['solved'], solvedRect) if keyPressed: return 'solved' pygame.display.update() FPSCLOCK.tick() def decorateMap(map0bj, startxy): startx, starty = startxy map0bjCopy = copy.deepcopy(map0bj) for x in range(len(map0bjCopy)): for y in range(len(map0bjCopy[0])): if map0bjCopy[x][y] in ('$', '.', '@', '+', '*'): map0bjCopy[x][y] = ' ' floodFill(map0bjCopy, startx, starty, ' ', 'o') for x in range(len(map0bjCopy)): for y in range(len(map0bjCopy[0])): if (isWall(mapObjCopy, x, y-1) and isWall(mapObjCopy, x+1, y)) or \ (isWall(mapObjCopy, x+1, y) and isWall(mapObjCopy, x, y+1)) or \ (isWall(mapObjCopy, x, y+1) and isWall(mapObjCopy, x-1, y)) or \ (isWall(mapObjCopy, x-1, y) and isWall(mapObjCopy, x, y-1)): map0bjCopy[x][y] = 'x' elif map0bjCopy[x][y] == ' ' and random.randint(0, 99) < OUTSIDE_DECORATION_PCT: map0bjCopy[x][y] = random.choice(list(OUTSIDECOMAPPING.keys())) return map0bjCopy def isBlocked(map0bj, gameState0bj, x, y): if isWall(map0bj, x, y): return True elif x < 0 or x >= len(map0bj) or y < 0 or y >= len(map0bj[x]): return True return False def makeMove(map0bj, gameState0bj, playerMoveTo): playerx, playery = gameState0bj['player'] stars = gameState0bj['stars'] if playerMoveTo == UP: x0ffset = 0 y0ffset = -1 elif playerMoveTo == RIGHT: x0ffset = 1 y0ffset = 0 elif playerMoveTo == DOWN: x0ffset = 0 y0ffset = 1 elif playerMoveTo == LEFT: x0ffset = -1 y0ffset = 0 if isWall(map0bj, playerx, x0ffset, playery + y0ffset): return False else: if (playerx + x0ffset, playery + y0ffset) in stars: if not isBlocked(map0bj, gameState0bj, playerx + (x0ffset*2), playery + (y0ffset*2)): ind = stars.index((playerx + x0ffset, playery + y0ffset)) stars[ind] = (stars[ind][0] + x0ffset, stars[ind][1] + y0ffset) else: return False gameState0bj['player'] = (playerx + x0ffset, playery + y0ffset) return True def startScreen(): titleRect = IMAGESDICT['title'].get_rect() topCoord = 50 titleRect.top = topCoord titleRect.centerx = HALF_WINWIDTH topCoord += titleRect.height instructionText = ['Push the stars over the marks.', 'Arrow keys move the player, WASD controls the camera, and P changes the characer.', 'Backspaced resets the level, Escape quits the game.', 'N for next level, B to go back a level.'] DISPLAYSURF.fill(BGCOLOR) DISPLAYSURF.blit(IMAGESDICT['title'], titleRect) for i in range(len(instructionText)): instSurf = BASICFONT.render(instructionText[i], 1, TEXTCOLOR) instRect = instSurf.get_rect() topCoord += 10 instRect.top = topCoord instRect.centerx = HALF_WINWIDTH topCoord += instRect.height DISPLAYSURF.blit(instSurf, instRect) while True: for event in pygame.event.get(): if event.type == QUIT: terminate() elif event.type == KEYDOWN: if event.key ==K_ESCAPE: terminate() return pygame.display.update() FPSCLOCK.tick() def readLevelsFile(filename): assert os.path.exists(filename), 'Cannot find the level file: %s' % (filename) mapFile = open(filename, 'r') content = mapFile.readlines() + ['\r\n'] mapFile.close() levels = [] levelNum = 0 mapTextLines = [] map0bj = [] for lineNum in range (len(content)): line = content[lineNum].rstrip('\r\n') if ';' in line: line = line[:line.find(';')] if line != '': mapTextLines.append(line) elif line == '' and len(mapTextLines) > 0: maxWidth = -1 for i in range(len(mapTextLines)): if len(mapTextLines[i]) > maxWidth: maxWidth = len(mapTextLines[i]) for i in range(len(mapTextLines)): mapTextLines[i] += ' ' * (maxWidth - len(mapTextLines[i])) for x in range(len(mapTextLines[0])): map0bj.append([]) for y in range(len(mapTextLines)): for x in range(maxWidth): map0bj[x].append(mapTextLines[y][x]) startx = None starty = None goals = [] stars = [] for x in range(maxWidth): for y in range (len(map0bj[x])): if map0bj[x][y] in ('@', '+'): startx = x starty = y if map0bj [x][y] in ('.', '+', '*'): goals.append((x, y)) assert startx != None and starty!= None, 'Level %s (around line %s) in %s is missing a "@" or "+" to mark the start point.' % (levelNum+1, lineNum, filename) assert len(goals) > 0, 'Level %s (around line %s) in %s must have at least one goal.' % (levelNum+1, lineNum, filename) assert len(stars) >= len(goals), 'Level %s (around line %s) in %s is impossible to solve. It has %s goals but only %s stars.' % (levelNum+1, lineNum, filename, len(goals), len(stars)) gameState0bj = {'player': (startx, starty), 'stepCounter': 0, 'stars': stars} level0bj = {'width': maxWidth, 'height': len(map0bj), 'map0bj': map0bj, 'goals': goals, 'startState': gameState0bj} levels.append(level0bj) mapTextLines = [] map0bj = [] gameState0bj = {} levelNum += 1 return levels def floodFill(map0bj, x, y, oldCharacter, newCharacter): if map0bj[x][y] == oldCharacter: map0bj[x][y] = newCharacter if x < len(map0bj) - 1 and map0bj[x+1][y] == oldCharacter: floodFill(map0bj, x+1, y, oldCharacter, newCharacter) if x > 0 and map0bj[x-1][y] == oldCharacter: floodFill(mapObj, x-1, y, oldCharacter, newCharacter) if y < len(mapObj[x]) - 1 and mapObj[x][y+1] == oldCharacter: floodFill(mapObj, x, y+1, oldCharacter, newCharacter) if y > 0 and mapObj[x][y-1] == oldCharacter: floodFill(mapObj, x, y-1, oldCharacter, newCharacter) def drawMap(map0bj, gamestate0bj, goals): mapSurfWidth = len(map0bj) * TILEWIDTH mapSurfHeight = len(len(map0bj[0]) - 1) * (TILEHEIGHT - TILEFLOORHEIGHT) + TILEHEIGHT mapSurf = pygame.Surface((mapSurfWidth, mapSurfHeight)) mapSurf.fill(BGCOLOR) for x in range(len(map0bj)): for y in range(len(map0bj)): spaceRect = pygame.Rect((x * TILEWIDTH, y * (TILEHEIGHT - TILEFLOORHEIGHT), TILEWIDTH, TILEHEIGHT)) if map0bj[x][y] in TILEMAPPING: baseTile = TILEMAPPING[map0bj[x][y]] elif map0bj[x][y] in OUTSIDECOMAPPING: baseTile = TILEMAPPING[' '] mapSurf.blit(baseTile, spaceRect) if map0bj[x][y] in OUTSIDECOMAPPING: mapSurf.blit(OUTSIDEDECOMAPPING[map0bj[x][y]], spaceRect) elif (x, y) in gameState0bj['stars']: if (x, y) in goals: mapSurf.blit(IMAGESDICT['covered goal'], spaceRect) mapSurf.blit(IMAGESDICT['star'], spaceRect) elif (x, y) in goals: mapSurf.blit(IMAGESDICT['uncovered goal'], spaceRect) if (x, y) == gameState0bj['player']: mapSurf.blit(PLAYERIMAGES[currentImage], spaceRect) return mapSurf def isLevelFinished(level0bj, gameState0bj): for goal in level0bj['goals']: if goal not in gameState0bj['stars']: return False return True def terminate(): pygame.quit() sys.exit() if __name__ == '__main__': main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From n.nayeri at hotmail.com Tue Apr 9 03:31:43 2013 From: n.nayeri at hotmail.com (Negin Nayeri) Date: Tue, 9 Apr 2013 03:31:43 +0200 Subject: [Tutor] Create Library Message-ID: Hi!Im supposed to do a Library in Python and I don't even know how to begin! Please just help me. Like what kind of attributes do you think I should have, how do I store information? The file with the books and authors I must fix, do think I should write in txt format or like in Excel. Please help me. Write a program used to handling simpler library routines. The program should be able to search for books in terms of both author and title. You should also be able to borrow and return books, put new books in the registry and remove the old books, and print a list on the screen of all books. The books will be sorted with respect to the author.The books are stored in a text file that you can write yourself. Your file does not contain more than ten books, but your program should be valid also for a large number of books.The program will remember which books are utl?nade?ven if the user turns off and restarts the application.It can look some thing like this:Welcome to Adriana's Library:T search for titelF search by authorL Borrow BookR Return BookN Register new bookB remove book from registerA see a list of all booksQ quitWhat do you want to do? TWich title do you looking for? ...(write a list of all the books found)and so on. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rocketmanblamb at gmail.com Tue Apr 9 23:59:00 2013 From: rocketmanblamb at gmail.com (Brian Lamb) Date: Tue, 9 Apr 2013 17:59:00 -0400 Subject: [Tutor] building a website with python In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474182BD269@SCACMX008.exchad.jpmchase.net> References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com> <5B80DD153D7D744689F57F4FB69AF474182BD269@SCACMX008.exchad.jpmchase.net> Message-ID: <0B40E011-D620-4205-A3CF-14A32DD98E23@gmail.com> Without overly proselytizing any particular host you might want to check out Webfaction for hosting. They have an excellent reputation for Python hosting and reasonable rates. There are of course others that some may prefer, you can certainly google for other web hosting comparisons. Also there are other frameworks that may be worth your time to investigate, as with everything it really depends what you are trying to accomplish. Best of Luck, Brian On Apr 9, 2013, at 5:54 PM, Prasad, Ramit wrote: > Benjamin Fishbein wrote: >> >> Hello. I learned Python this past year (with help from many of you) and wrote many programs for my >> small business. Now I want to build a website. I acquired the domain name through godaddy.com >> (bookchicken.com) but have not found hosting yet. >> I learned html, css, and javascript via codeacademy.org, but have never built a website. >> I would like to build it with Python, and was wondering if you could give me some pointers about what >> I need to learn first: Django is the thing to use? And do I need specific hosting to use python or are >> all hosts basically the same. >> Thanks, >> Ben > > http://wiki.python.org/moin/WebFrameworks > > Lots of Python frameworks to choose from, though Django is the most famous/popular. There are > lighter frameworks too, depending on what you need. > > Your hosting solution to support Python, and I do not believe all hosts support Python. You > should double check with whatever host you choose. > > > ~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. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From s.shall at virginmedia.com Mon Apr 8 16:49:50 2013 From: s.shall at virginmedia.com (Sydney Shall) Date: Mon, 08 Apr 2013 15:49:50 +0100 Subject: [Tutor] How to extract a float from an instancemethod call In-Reply-To: <5162BD85.7070207@davea.name> References: <5162BAB1.8010700@virginmedia.com> <5162BD85.7070207@davea.name> Message-ID: <5162D90E.8050603@virginmedia.com> On 08/04/2013 13:52, Dave Angel wrote: > On 04/08/2013 08:40 AM, Sydney Shall wrote: >> Hi, >> I am learning Python. >> >> I use MAC OSX 10.6.8 >> Python 2.7.3 >> >> I have been given a project to write a program involving random walks. >> I have drafted a program which has passed all the static tests, but on >> testing my program i get the following error message: >> >> >> Traceback (most recent call last): >> File "/Users/Sydney/Documents/6.00x Files/Problem >> Sets/ProblemSet7/ps7 copy.py", line 303, in >> testRobotMovement(StandardRobot, RectangularRoom) >> File "ps7_verify_movement.py", line 12, in testRobotMovement >> File "/Users/Sydney/Documents/6.00x Files/Problem >> Sets/ProblemSet7/ps7 copy.py", line 285, in updatePositionAndClean >> while self.room.isPositionInRoom(self.position) == False: >> File "/Users/Sydney/Documents/6.00x Files/Problem >> Sets/ProblemSet7/ps7 copy.py", line 163, in isPositionInRoom >> return self.room[(x,y)] in self.room >> KeyError: (> 0x4699490>>, > 0x4699490>>) >> >>> >> >> The program text referred to is the following, I give the whole module, >> which is part of a larger program. >> def isPositionInRoom(self, pos): >> """ >> Return True if pos is inside the room. >> >> pos: a Position object. >> returns: True if pos is in the room, False otherwise. >> """ >> x = pos.getX >> y = pos.getY > > You never show the code for Position.getX and Position.getY, but I'd > expect they're methods that take no arguments. in that case, you need > parens in order to call them. > > x = pos.getX() > y = pos.getY() > >> return self.room[(x,y)] in self.room >> > > a simple print of x and y could have revealed this as well. > > Dear Dave, Thanks for pointing out my mistake. I thought it would be some small error on my part. I had a print statement, but I could not correctly interpret the output. It solves that problem. -- Sydney Shall From breamoreboy at yahoo.co.uk Sun Apr 14 19:41:00 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 14 Apr 2013 18:41:00 +0100 Subject: [Tutor] Issue With a Python Game In-Reply-To: References: Message-ID: On 13/04/2013 14:13, John Bochicchio wrote: > I have a question about a game I am making. I finished the overall code, > but keep getting errors when I try to play. This is my most common error: > C:\Users\John\Documents\Python Games\Noah>python nickeladventuredemo.py > Traceback (most recent call last): > File "nickeladventuredemo.py", line 451, in > main() > File "nickeladventuredemo.py", line 78, in main > levels = readLevelsFile('levels.txt') > File "nickeladventuredemo.py", line 371, in readLevelsFile > assert startx != None and starty!= None, 'Level %s (around line > %s) in %s i > s missing a "@" or "+" to mark the start point.' % (levelNum+1, lineNum, > filenam > e) > AssertionError: Level 1 (around line 10) in levels.txt is missing a "@" > or "+" t > o mark the start point. > > The Code: > import random, sys, copy, os, pygame > I've stripped the remaining 450 lines of code as it's got the dread double spaced google disease, please see my signature. You're also far more likely to get responses if your question follows the guidelines given here http://www.sscce.org/, particularly if someone already has pygame installed, which I don't. However I did note one area where you can simplfy your code. You've many lines using this type of construct. for i in range(len(ships)): doSomething(ships[i]) There's rarely a need for this in Python. Use this instead. for ship in ships: doSomething(ship) -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From eryksun at gmail.com Sun Apr 14 19:50:44 2013 From: eryksun at gmail.com (eryksun) Date: Sun, 14 Apr 2013 13:50:44 -0400 Subject: [Tutor] creating dictionary from a list In-Reply-To: References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info> <51696D09.4000103@gmail.com> <5169B26B.1050707@gmail.com> <516A0D01.6000903@pearwood.info> Message-ID: On Sun, Apr 14, 2013 at 12:46 PM, Saad Javed wrote: > > As for the underscores, what happened is that I didn't voluntarily add the > underscores to begin with. If you read the emails again, after Mark's answer > about not looping, I asked that the dictionary created as a result of his > code wasn't ordered. You replied with a multipart MIME message that included both plain text and HTML versions. HTML: if item.startswith(( 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')) Text: item.startswith( ('Mon','Tue','**Wed','Thu','Fri','Sat','Sun'))** I don't know how the underline tags got in there. They aren't in the quote in Mark's message. Either way, for the plain text part, your email program substituted "**". Others substituted "__". There'd be no problem if you didn't use rich text in the first place. Email programs always manage to mangle HTML. Besides, it really has no place whatsoever on this forum. I always reply in plain text here. From sbjaved at gmail.com Sun Apr 14 22:27:11 2013 From: sbjaved at gmail.com (Saad Bin Javed) Date: Mon, 15 Apr 2013 01:27:11 +0500 Subject: [Tutor] creating dictionary from a list In-Reply-To: References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info> <51696D09.4000103@gmail.com> <5169B26B.1050707@gmail.com> <516A0D01.6000903@pearwood.info> Message-ID: <516B111F.9050303@gmail.com> On 04/14/2013 10:50 PM, eryksun wrote: > I don't know how the underline tags got in there. They aren't > in the quote in Mark's message. Either way, for the plain text part, > your email program substituted "**". Others substituted "__". > > There'd be no problem if you didn't use rich text in the first place. > Email programs always manage to mangle HTML. Besides, it really has no > place whatsoever on this forum. I always reply in plain text here. I've set changed settings in thunderbird to send plain text emails to python.org domain. Hopefully it won't be an issue again! From wprins at gmail.com Sun Apr 14 23:16:05 2013 From: wprins at gmail.com (Walter Prins) Date: Sun, 14 Apr 2013 22:16:05 +0100 Subject: [Tutor] Issue With a Python Game In-Reply-To: References: Message-ID: Hi John, On 10 April 2013 15:21, John Bochicchio wrote: > I have a question about a game I am making. I finished the overall code, > but keep getting errors when I try to play. This is my most common error: > C:\Users\John\Documents\Python Games\Noah>python nickeladventuredemo.py > Traceback (most recent call last): > File "nickeladventuredemo.py", line 451, in > main() > File "nickeladventuredemo.py", line 78, in main > levels = readLevelsFile('levels.txt') > File "nickeladventuredemo.py", line 371, in readLevelsFile > assert startx != None and starty!= None, 'Level %s (around line %s) > in %s i > s missing a "@" or "+" to mark the start point.' % (levelNum+1, lineNum, > filenam > e) > AssertionError: Level 1 (around line 10) in levels.txt is missing a "@" or > "+" t > o mark the start point. > > The error has something to do with the levels. I will attach the code and > levels, as they are fairly long. > Firstly please next time include a segment of the failing code in the email -- not everyone is prepared to or can be bothered to download and wade through a large source file just to get to the bottom of an program error. Secondly, re your your first assertion statement: it assumes that the problem is due to a problem in the levels.txt file, which is not the case here. You'd do better IMHO to maybe not be so creative/presumptuous with the error message, and rather have it report exactly what the actual assertion conditions (and maybe variable values at the time) is that failed (in this case values of startx, starty.) You might also consider rather using Exceptions here. All that said, the problem is you have the code throwing the exception at the wrong level of indent. You need to de-indent all the assert statements as well as the code that follows up to but excluding the return statement so that it's at the same level of the first "for" loop. (Differently put, the reason the assertion is likely failing is because you're doing your asserts before the loops have finished processing/reading your mapObj. You presumably want the asserts once the mapObj's been finished processing by the loop.) As an aside, the next failure you'll likely run into is the third assert, which expects len(stars) >= len(goals), which I assume will fail as you are not reading anything into "stars" list anywhere as you do for goals. Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Mon Apr 15 01:56:06 2013 From: davea at davea.name (Dave Angel) Date: Sun, 14 Apr 2013 19:56:06 -0400 Subject: [Tutor] Create Library In-Reply-To: References: Message-ID: <516B4216.3010909@davea.name> On 04/08/2013 09:31 PM, Negin Nayeri wrote: > Hi!Im supposed to do a Library in Python and I don't even know how to begin! Please just help me. Like what kind of attributes do you think I should have, how do I store information? The file with the books and authors I must fix, do think I should write in txt format or like in Excel. Please help me. > > > Write a program used to handling simpler library routines. The program should be able to search for books in terms of both author and title. You should also be able to borrow and return books, put new books in the registry and remove the old books, and print a list on the screen of all books. The books will be sorted with respect to the author.The books are stored in a text file that you can write yourself. Your file does not contain more than ten books, but your program should be valid also for a large number of books.The program will remember which books are utl?nade?ven if the user turns off and restarts the application.It can look some thing like this:Welcome to Adriana's Library:T search for titelF search by authorL Borrow BookR Return BookN Register new bookB remove book from registerA see a list of all booksQ quitWhat do you want to do? TWich title do you looking for? ...(write a list of all the books found)and so on. > > The formatting of that message sure got messed up. Two very long lines. You must have sent the message as html, instead of text. Your assignment does NOT say you're supposed to create a Library. It says you're supposed to create routines that might be used in a library. It DOES tell you how to store your information; use a text file. -- DaveA From ysoliman at uncc.edu Mon Apr 15 02:35:51 2013 From: ysoliman at uncc.edu (Soliman, Yasmin) Date: Mon, 15 Apr 2013 00:35:51 +0000 Subject: [Tutor] (no subject) Message-ID: <211A029E048A2245A6E00BA02FEFF88A6BF5F7E0@BL2PRD0310MB373.namprd03.prod.outlook.com> Hi everyone. I just need to know why this programs tells me End is not defined, what can I o to fix this issue? Thanks in advance. hrList=[] while True: heartrate= float(input('Enter heart rate as beats per min: ')) hrList.append(heartrate) if heartrate=='End': print '\nThank you for using this program! Bye.' break total_sum = 0; length = len(hrList) for i in range(0, length): total_sum += hrList[i] average = total_sum / length print average From davea at davea.name Mon Apr 15 04:44:08 2013 From: davea at davea.name (Dave Angel) Date: Sun, 14 Apr 2013 22:44:08 -0400 Subject: [Tutor] (no subject) In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A6BF5F7E0@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A6BF5F7E0@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: <516B6978.4010404@davea.name> On 04/14/2013 08:35 PM, Soliman, Yasmin wrote: > Hi everyone. I just need to know why this programs tells me End is not defined, what can I o to fix this issue? Thanks in advance. > > hrList=[] > while True: > heartrate= float(input('Enter heart rate as beats per min: ')) > hrList.append(heartrate) > > if heartrate=='End': > print '\nThank you for using this program! Bye.' > break > > total_sum = 0; > length = len(hrList) > > for i in range(0, length): > total_sum += hrList[i] > > average = total_sum / length > > print average > I can't see any place there where such an error might occur. But I can see where you forgot the parens in the call to print(). You might get better advice by telling us the Python version, and the complete error message traceback. That'll show us exactly what was executing when the exception happened. Oh wait. Perhaps you were running Python 2.x, rather than 3.x. In that case, you should have used raw_input(), not input. Input will eval whatever the user types, and if he types "End" he'll get an error: Enter heart rate as beats per min: End Traceback (most recent call last): File "soliman2.py", line 6, in heartrate= float(input('Enter heart rate as beats per min: ')) File "", line 1, in NameError: name 'End' is not defined Once you fix that, you'll get another error. Enter heart rate as beats per min: End Traceback (most recent call last): File "soliman2.py", line 6, in heartrate= float(raw_input('Enter heart rate as beats per min: ')) ValueError: could not convert string to float: End That's because you try to convert the string "End" into an integer before you check it for the terminating value. You want to do the raw_input first, then the check for End, then convert to int, then append and print the stuff. Alternatively, you could just tell the user to enter "0" when he wants to quit. -- DaveA From zakiakhmad at gmail.com Mon Apr 15 07:59:56 2013 From: zakiakhmad at gmail.com (Zaki Akhmad) Date: Mon, 15 Apr 2013 12:59:56 +0700 Subject: [Tutor] Scheduling Python Execution Message-ID: Hi all, I'd like to execute python script for specific times. I prefer not to use cron, since this times will be very varies. Example, my requirement is, this python script will execute at: 13:00:00 14:05:00 14:35:00 15:20:00 I know this is gonna be a long script to run. Check the time.ctime() then execute. Is designing with this approach isn't good? Since it will be a long script running. I've read the sched module. And the enter module has delay argument. So is better that I calculate the delay rather than the ctime to execute? Regards, -- Zaki Akhmad From ybronhei at redhat.com Mon Apr 15 09:01:37 2013 From: ybronhei at redhat.com (Yaniv Bronheim) Date: Mon, 15 Apr 2013 03:01:37 -0400 (EDT) Subject: [Tutor] How to extract a float from an instancemethod call In-Reply-To: <5162D90E.8050603@virginmedia.com> References: <5162BAB1.8010700@virginmedia.com> <5162BD85.7070207@davea.name> <5162D90E.8050603@virginmedia.com> Message-ID: <1986072937.168546.1366009297778.JavaMail.root@redhat.com> by reading the exception you see that you pass function pointer instead of a value "KeyError: (>, >)" as if you just print pos.getX and not pos.getX(), you will see the exact output - <__main__.Position object at 0x4699490> .. Regards, Yaniv. ----- Original Message ----- > From: "Sydney Shall" > To: "Dave Angel" > Sent: Monday, April 8, 2013 5:49:50 PM > Subject: Re: [Tutor] How to extract a float from an instancemethod call > > > > On 08/04/2013 13:52, Dave Angel wrote: > > On 04/08/2013 08:40 AM, Sydney Shall wrote: > >> Hi, > >> I am learning Python. > >> > >> I use MAC OSX 10.6.8 > >> Python 2.7.3 > >> > >> I have been given a project to write a program involving random walks. > >> I have drafted a program which has passed all the static tests, but on > >> testing my program i get the following error message: > >> > >> > >> Traceback (most recent call last): > >> File "/Users/Sydney/Documents/6.00x Files/Problem > >> Sets/ProblemSet7/ps7 copy.py", line 303, in > >> testRobotMovement(StandardRobot, RectangularRoom) > >> File "ps7_verify_movement.py", line 12, in testRobotMovement > >> File "/Users/Sydney/Documents/6.00x Files/Problem > >> Sets/ProblemSet7/ps7 copy.py", line 285, in updatePositionAndClean > >> while self.room.isPositionInRoom(self.position) == False: > >> File "/Users/Sydney/Documents/6.00x Files/Problem > >> Sets/ProblemSet7/ps7 copy.py", line 163, in isPositionInRoom > >> return self.room[(x,y)] in self.room > >> KeyError: ( >> 0x4699490>>, >> 0x4699490>>) > >> >>> > >> > >> The program text referred to is the following, I give the whole module, > >> which is part of a larger program. > >> def isPositionInRoom(self, pos): > >> """ > >> Return True if pos is inside the room. > >> > >> pos: a Position object. > >> returns: True if pos is in the room, False otherwise. > >> """ > >> x = pos.getX > >> y = pos.getY > > > > You never show the code for Position.getX and Position.getY, but I'd > > expect they're methods that take no arguments. in that case, you need > > parens in order to call them. > > > > x = pos.getX() > > y = pos.getY() > > > >> return self.room[(x,y)] in self.room > >> > > > > a simple print of x and y could have revealed this as well. > > > > > Dear Dave, > Thanks for pointing out my mistake. I thought it would be some small > error on my part. > I had a print statement, but I could not correctly interpret the output. > It solves that problem. > > > > -- > Sydney Shall > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Mon Apr 15 10:51:37 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Apr 2013 09:51:37 +0100 Subject: [Tutor] Scheduling Python Execution In-Reply-To: References: Message-ID: On 15/04/13 06:59, Zaki Akhmad wrote: > I'd like to execute python script for specific times. I prefer not to > use cron, since this times will be very varies. multiple cron jobs will be less work for your computer than running a long term program constantly checking times and launching your scripts... That's called reinventing the wheel with a square one... There are more modern (and more efficent) replacements for cron but given your requirements cron still looks like the best bet. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jappy.db at gmail.com Mon Apr 15 10:54:33 2013 From: jappy.db at gmail.com (Jabesa Daba) Date: Mon, 15 Apr 2013 09:54:33 +0100 Subject: [Tutor] Help on python Message-ID: is it possible to reorder a sentence in the form of SVO (Subject Verb Object) into the form of SOV (Subject Object Verb) by using a python program? if so, how? regards, -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon Apr 15 11:23:40 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 15 Apr 2013 10:23:40 +0100 Subject: [Tutor] (no subject) In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A6BF5F7E0@BL2PRD0310MB373.namprd03.prod.outlook.com> References: <211A029E048A2245A6E00BA02FEFF88A6BF5F7E0@BL2PRD0310MB373.namprd03.prod.outlook.com> Message-ID: You've already had a sound answer from Dave Angel, I've just a few comments below. On 15/04/2013 01:35, Soliman, Yasmin wrote: > Hi everyone. I just need to know why this programs tells me End is not defined, what can I o to fix this issue? Thanks in advance. > > hrList=[] > while True: > heartrate= float(input('Enter heart rate as beats per min: ')) > hrList.append(heartrate) > > if heartrate=='End': > print '\nThank you for using this program! Bye.' > break > > total_sum = 0; No need for the semicolon. > length = len(hrList) > for i in range(0, length): > total_sum += hrList[i] For the third time in three days, you rarely need to write a loop like this in Python :) for hr in hrList: total_sum += hr > > average = total_sum / length Part of the learning curve, but the lot could be written as. average = sum(hrList) / len(hrList) > > print average > -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From zakiakhmad at gmail.com Mon Apr 15 11:23:56 2013 From: zakiakhmad at gmail.com (Zaki Akhmad) Date: Mon, 15 Apr 2013 16:23:56 +0700 Subject: [Tutor] Scheduling Python Execution In-Reply-To: References: Message-ID: On Mon, Apr 15, 2013 at 3:51 PM, Alan Gauld wrote: > multiple cron jobs will be less work for your computer than running a long > term program constantly checking times and launching your scripts... That's > called reinventing the wheel with a square one... > > There are more modern (and more efficent) replacements for cron but given > your requirements cron still looks like the best bet. Actually, I want to write a twitter bot which runs on a specific time. For an idea, I'd like to have this twitter bot tweet every sunrise and sunset, everyday. Since everyday the sunrise and the sunset time are vary, what are the best way to do it? Should I entered the sunset and the sunrise manually? Thanks! -- Zaki Akhmad From breamoreboy at yahoo.co.uk Mon Apr 15 11:31:45 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 15 Apr 2013 10:31:45 +0100 Subject: [Tutor] Help on python In-Reply-To: References: Message-ID: On 15/04/2013 09:54, Jabesa Daba wrote: > is it possible to reorder a sentence in the form of SVO (Subject Verb > Object) into the form of SOV (Subject Object Verb) by using a python > program? if so, how? > > regards, > Yes. By writing code. You could have answered your own question by typing something like "python natural language processing" into your favourite search engine. -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From Steve.Flynn at capita.co.uk Mon Apr 15 11:35:29 2013 From: Steve.Flynn at capita.co.uk (Flynn, Stephen (L & P - IT)) Date: Mon, 15 Apr 2013 10:35:29 +0100 Subject: [Tutor] Scheduling Python Execution In-Reply-To: References: Message-ID: > I want to write a twitter bot which runs on a specific time. For an > idea, I'd like to have this twitter bot tweet every sunrise and > sunset, everyday. Since everyday the sunrise and the sunset time are > vary, what are the best way to do it? Have the bot calculate sunrise and sunset for the following day and re-schedule itself for those times. This email and any attachment to it are confidential. Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately. Any views or opinions expressed in this email are those of the sender only, unless otherwise stated. All copyright in any Capita material in this email is reserved. All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law. From svenito at gmail.com Mon Apr 15 12:53:05 2013 From: svenito at gmail.com (Sven) Date: Mon, 15 Apr 2013 11:53:05 +0100 Subject: [Tutor] Scheduling Python Execution In-Reply-To: References: Message-ID: I assume that you are getting these times from somewhere, hopefully a website. To do as Steve says, you would just scrape (or use the API if there is one) to get the times, and schedule a tweet at that time. If you do use cron you can make use of https://pypi.python.org/pypi/python-crontab On 15 April 2013 10:23, Zaki Akhmad wrote: > On Mon, Apr 15, 2013 at 3:51 PM, Alan Gauld > wrote: > > > multiple cron jobs will be less work for your computer than running a > long > > term program constantly checking times and launching your scripts... > That's > > called reinventing the wheel with a square one... > > > > There are more modern (and more efficent) replacements for cron but given > > your requirements cron still looks like the best bet. > > Actually, > > I want to write a twitter bot which runs on a specific time. For an > idea, I'd like to have this twitter bot tweet every sunrise and > sunset, everyday. Since everyday the sunrise and the sunset time are > vary, what are the best way to do it? > > Should I entered the sunset and the sunrise manually? > > Thanks! > -- > Zaki Akhmad > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- ./Sven -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Apr 15 13:56:10 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 15 Apr 2013 12:56:10 +0100 Subject: [Tutor] Help on python In-Reply-To: References: Message-ID: On 15/04/13 09:54, Jabesa Daba wrote: > is it possible to reorder a sentence in the form of SVO (Subject Verb > Object) into the form of SOV (Subject Object Verb) by using a python > program? if so, how? Python is a general purpose programming language so yes, you can program it to do any computational task. How much work is involved depends on how well you can define the algorithm and whether somebody else has already implemented it for you in Python. In your case you need to consider which language you are processing and what the grammatical rules are (what is a word? How do you identify a subject, object and verb? What are the separator rules and do you need to consider changes of endings etc when you change order? etc) Just how sophisticated does it need to be?) There are several libraries that can help ranging from general purpose text processing and parsers to natural language tookits. Whatever you use you will still need a fair amount of effort to get it working. Google (or any other search engine!) is your friend. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sbjaved at gmail.com Mon Apr 15 15:48:06 2013 From: sbjaved at gmail.com (Saad Bin Javed) Date: Mon, 15 Apr 2013 18:48:06 +0500 Subject: [Tutor] creating dictionary from a list In-Reply-To: <516BBD7D.2060306@virginmedia.com> References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info> <51696D09.4000103@gmail.com> <5169B26B.1050707@gmail.com> <516A0D01.6000903@pearwood.info> <516B111F.9050303@gmail.com> <516BBD7D.2060306@virginmedia.com> Message-ID: <516C0516.8010104@gmail.com> On 04/15/2013 01:42 PM, Sydney Shall wrote: > Dear Saad, > Could you please tell me how to change the Thunderbird settings to plain > text. > I could not find the correct menu. > Many thanks, > Sydney Go to Preferences > Composition > Send Options and add python.org under Plain Text Domains. From doark at mail.com Mon Apr 15 21:00:19 2013 From: doark at mail.com (frank ernest) Date: Mon, 15 Apr 2013 15:00:19 -0400 Subject: [Tutor] The proper use of classes Message-ID: <20130415190020.51550@gmx.com> Thanks guys! I've got my class up and running and am having a fine time programming in python... again. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Tue Apr 16 00:56:58 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Mon, 15 Apr 2013 16:56:58 -0600 Subject: [Tutor] Help on python In-Reply-To: References: Message-ID: For example, see: http://nltk.org. From steve at pearwood.info Tue Apr 16 03:27:30 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Tue, 16 Apr 2013 11:27:30 +1000 Subject: [Tutor] Scheduling Python Execution In-Reply-To: References: Message-ID: <516CA902.8090204@pearwood.info> On 15/04/13 19:23, Zaki Akhmad wrote: > On Mon, Apr 15, 2013 at 3:51 PM, Alan Gauld wrote: > >> multiple cron jobs will be less work for your computer than running a long >> term program constantly checking times and launching your scripts... That's >> called reinventing the wheel with a square one... >> >> There are more modern (and more efficent) replacements for cron but given >> your requirements cron still looks like the best bet. > > Actually, > > I want to write a twitter bot which runs on a specific time. That is exactly what cron is designed to do. Although given that the time you want will vary, my guess is that the lesser-known "at" job will be better. Another option is the sched module, that lets you schedule tasks to run while your program is idling. It is not a replacement for cron or at, since it requires your program to be running. But for simple needs, it may do the job. http://docs.python.org/2/library/sched.html http://pymotw.com/2/sched/ >For an > idea, I'd like to have this twitter bot tweet every sunrise and > sunset, everyday. Since everyday the sunrise and the sunset time are > vary, what are the best way to do it? Sunrise and sunset *where*? Because the world is a globe, sunrise and sunset vary from place to place. Even in one place, they also vary at different times of the year. If you google for "sunrise sunset algorithm", you may find a formula for calculating the time of each at a given latitude and longitude. Or not. I don't really know how complicated it is. > Should I entered the sunset and the sunrise manually? I don't know about "manually", but there's no standard Python command for giving you sunset and sunrise. You'll either need to find an existing program that does it, or write one yourself. -- Steven From amckenzie4 at gmail.com Tue Apr 16 17:58:15 2013 From: amckenzie4 at gmail.com (Andy McKenzie) Date: Tue, 16 Apr 2013 11:58:15 -0400 Subject: [Tutor] Hello, and a newbie question Message-ID: Hey folks. I'm just starting to pick up Python, and I'd like to avoid some of the mistakes I made in the past. To elaborate on that, my primary programming/scripting experience is PHP, with a little bit of Perl thrown in. Like so many people who write in PHP, I was entirely self-taught, and would be the first to admit that a lot of what I've written is, well... wrong. It works, but it's sloppy and inefficient, because there were standard constructions and solutions I just didn't know about. I'd like to avoid that with Python. So: my first two questions to the list. 1) Python 2.7 or 3.x? I know I'm going to want to do some work with NLTK (which appears to only have an alpha version out for Python 3), but I've just gone through the hassle of dealing with an upgrade from PHP 4 to 5.3, and I'd rather not start learning something that's already obsolete. Any words of advice? 2) Best practices. I have the WROX Press Beginning Python book, which targets Python 2. Clearly that's of only limited value if I'm going to go with Python 3, but it looks like it's at least going to be a good overview. But some of the stuff they do seems to be fairly personalized, rather than trying to follow standards. Should I just start out with the tutorial from docs.python.org? I would assume that that would start putting me in the right habits from the beginning... is that accurate, or is there a better way to go? Thanks in advance, Andy McKenzie -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Apr 16 18:22:56 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 16 Apr 2013 17:22:56 +0100 Subject: [Tutor] Hello, and a newbie question In-Reply-To: References: Message-ID: On 16/04/13 16:58, Andy McKenzie wrote: > 1) Python 2.7 or 3.x? I know I'm going to want to do some work with > NLTK (which appears to only have an alpha version out for Python 3), but > I've just gone through the hassle of dealing with an upgrade from PHP 4 > to 5.3, and I'd rather not start learning something that's already > obsolete. Any words of advice? Upgrading from P2 to P3 is not too onerous but there will be some changes to make at some po9nt. However P2 is the one to go for if you want to do anything industrial just now because not all the 3rd party libraries (like NLTK) are fully ported to v3 yet, including some pretty significant ones. OTOH If you are only experimenting/learning then going with P3 will avoid any relearning in the future. > 2) Best practices. I have the WROX Press Beginning Python book, Sorry, I've never even seen that one so can't comment... > ? I would assume that that would start putting > me in the right habits from the beginning... is that accurate, Yes, for existing programmers new to Python the official tutor is nearly always the best place to start. You can fill in the gaps elsewhere later. And the tutor is pretty short and fast paced, you can just about get through it all in an afternoon - certainly in a day. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From leamhall at gmail.com Tue Apr 16 18:30:10 2013 From: leamhall at gmail.com (leam hall) Date: Tue, 16 Apr 2013 12:30:10 -0400 Subject: [Tutor] Fwd: Hello, and a newbie question In-Reply-To: References: Message-ID: Python 2.x if you're working on existing servers like RHEL. If you're having fun on a desktop, Python 3. Free on-line college level class just started: https://class.coursera.org/interactivepython-002/class/index BTW, PHP ROCKS! :P Leam -- Also a PHP programmer -- Mind on a Mission -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Tue Apr 16 19:43:57 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Tue, 16 Apr 2013 10:43:57 -0700 Subject: [Tutor] How did this decimal error pop up? Message-ID: I was doing a simple training prog to figure change, and wanted to avoid computer inaccuracy by using only two-decimal input and not using division or mod where it would cause error. Yet, on a simple subtraction I got a decimal error instead of a two decimal result, as per below. What gives? cost = float(input('How much did the item cost?: ')) paid = float(input('How much did the customer give you?: ')) change = paid - cost *#using 22.89 as cost and 248.76 as paid* twenties = int(change / 20) if twenties != 0: twentiesAmount = 20 * twenties change = change - twentiesAmount *#change is 5.8700000000000045, not 5.87 - how did I get this decimal error when simply subtracting an integer from what should be a #two-decimal amount? * print(twenties, ' twenties') print(change) #and so forth for the rest of the change -- *Jim Mooney If you shoot a child you're a bad guy. If you splatter forty children across a wall with a bomb, you're a heroic, manly Top Gun with gleaming Tom Cruise teeth. The moral is you'll get laid more if you snuff a lot of children than if you only snuff a few.* -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Tue Apr 16 19:48:14 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Tue, 16 Apr 2013 10:48:14 -0700 Subject: [Tutor] oops - resending as plain text Message-ID: I accidentally sent as HTML so this is a resend in case that choked the mailing prog ;') I was doing a simple training prog to figure monetary change, and wanted to avoid computer inaccuracy by using only two-decimal input and not using division or mod where it would cause error. Yet, on a simple subtraction I got a decimal error instead of a two decimal result, as per below. What gives? cost = float(input('How much did the item cost?: ')) paid = float(input('How much did the customer give you?: ')) change = paid - cost #using 22.89 as cost and 248.76 as paid twenties = int(change / 20) if twenties != 0: twentiesAmount = 20 * twenties change = change - twentiesAmount #change is 5.8700000000000045, not 5.87 - how did I get this decimal error when simply subtracting an integer from what should be a #two-decimal amount? print(twenties, ' twenties') print(change) #and so forth for the rest of the prog Jim Mooney From joel.goldstick at gmail.com Tue Apr 16 20:16:24 2013 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 16 Apr 2013 14:16:24 -0400 Subject: [Tutor] oops - resending as plain text In-Reply-To: References: Message-ID: On Tue, Apr 16, 2013 at 1:48 PM, Jim Mooney wrote: > I accidentally sent as HTML so this is a resend in case that choked > the mailing prog ;') > > I was doing a simple training prog to figure monetary change, and > wanted to avoid computer inaccuracy by using only two-decimal input > and not using division or mod where it would cause error. Yet, on a > simple subtraction I got a decimal error instead of a two decimal > result, as per below. What gives? > > cost = float(input('How much did the item cost?: ')) > paid = float(input('How much did the customer give you?: ')) > change = paid - cost > > #using 22.89 as cost and 248.76 as paid > > twenties = int(change / 20) > if twenties != 0: > twentiesAmount = 20 * twenties > change = change - twentiesAmount > #change is 5.8700000000000045, not 5.87 - how did I get this decimal > error when simply subtracting an integer from what should be a > #two-decimal amount? > because binary computers convert decimal numbers to binary numbers. There is often a rounding error. > print(twenties, ' twenties') > print(change) > > #and so forth for the rest of the prog > > Jim Mooney > _______________________________________________ > 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 dfjennings at gmail.com Tue Apr 16 20:29:48 2013 From: dfjennings at gmail.com (Don Jennings) Date: Tue, 16 Apr 2013 14:29:48 -0400 Subject: [Tutor] oops - resending as plain text In-Reply-To: References: Message-ID: <373E45EA-D702-4A95-AF37-262BCB45AE80@gmail.com> On Apr 16, 2013, at 1:48 PM, Jim Mooney wrote: > I accidentally sent as HTML so this is a resend in case that choked > the mailing prog ;') > > I was doing a simple training prog to figure monetary change, and > wanted to avoid computer inaccuracy by using only two-decimal input > and not using division or mod where it would cause error. Yet, on a > simple subtraction I got a decimal error instead of a two decimal > result, as per below. What gives? > > cost = float(input('How much did the item cost?: ')) > paid = float(input('How much did the customer give you?: ')) > change = paid - cost > > #using 22.89 as cost and 248.76 as paid > > twenties = int(change / 20) > if twenties != 0: > twentiesAmount = 20 * twenties > change = change - twentiesAmount > #change is 5.8700000000000045, not 5.87 - how did I get this decimal > error when simply subtracting an integer from what should be a Now that Joel Goldstick has pointed out the reason, you may wonder what to do now. Answer? Use the decimal module: http://docs.python.org/2/library/decimal.html Although, you might prefer Doug Hellmann's introduction: http://pymotw.com/2/decimal/ Take care, Don From sander.sweers at gmail.com Tue Apr 16 20:55:17 2013 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 16 Apr 2013 20:55:17 +0200 Subject: [Tutor] oops - resending as plain text In-Reply-To: References: Message-ID: <516D9E95.2050203@gmail.com> On 04/16/2013 07:48 PM, Jim Mooney wrote: > I accidentally sent as HTML so this is a resend in case that choked > the mailing prog ;') > > I was doing a simple training prog to figure monetary change, and > wanted to avoid computer inaccuracy by using only two-decimal input > and not using division or mod where it would cause error. Yet, on a > simple subtraction I got a decimal error instead of a two decimal > result, as per below. What gives? Floats can not be represented accurately in binary and will have small rounding errors. See https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems. > cost = float(input('How much did the item cost?: ')) > paid = float(input('How much did the customer give you?: ')) > change = paid - cost > > #using 22.89 as cost and 248.76 as paid > > twenties = int(change / 20) > if twenties != 0: > twentiesAmount = 20 * twenties > change = change - twentiesAmount > #change is 5.8700000000000045, not 5.87 - how did I get this decimal > error when simply subtracting an integer from what should be a > #two-decimal amount? > print(twenties, ' twenties') > print(change) > > #and so forth for the rest of the prog You can use string formatting to show as much precision you want. Example: >>> n = 5.8700000000000045 >>> print '%.2f' % n 5.87 >>> print '%.4f' % n 5.8700 Or use round(), example: >>> round(n,2) 5.87 In your case I would just use string formatting to hide the rounding error. Greets ~sander From davea at davea.name Tue Apr 16 22:18:16 2013 From: davea at davea.name (Dave Angel) Date: Tue, 16 Apr 2013 16:18:16 -0400 Subject: [Tutor] Hello, and a newbie question In-Reply-To: References: Message-ID: <516DB208.80006@davea.name> On 04/16/2013 11:58 AM, Andy McKenzie wrote: > Hey folks. > > I'm just starting to pick up Python, and I'd like to avoid some of the > mistakes I made in the past. To elaborate on that, my primary > programming/scripting experience is PHP, with a little bit of Perl thrown > in. Like so many people who write in PHP, I was entirely self-taught, and > would be the first to admit that a lot of what I've written is, well... > wrong. It works, but it's sloppy and inefficient, because there were > standard constructions and solutions I just didn't know about. I'd like to > avoid that with Python. > Welcome to the mailing list. I expect you'll find Python a much cleaner language than the other two, though php has some definite convenience for its particular niche. > So: my first two questions to the list. > > 1) Python 2.7 or 3.x? I know I'm going to want to do some work with NLTK > (which appears to only have an alpha version out for Python 3), but I've > just gone through the hassle of dealing with an upgrade from PHP 4 to 5.3, > and I'd rather not start learning something that's already obsolete. Any > words of advice? > If you have to use a library that's not available yet for 3.x, then you need to use 2.x on the other hand, if you're learning now, maybe that library will be available by the time you actually need it. For most people, I'd advise against trying to use a tutorial that targets a different version than you're running. If you get frustrated quickly, you can get bogged down by the differences when you're just copying an exact program out of some book. Python 3 in particular has spent some substantial effort cleaning up the warts, the biggest one being Unicode. For beginning programmers using only ASCII, probably the main thing that'll bog you down is that print() is now a function, rather than a statement, so you need parentheses. But once you get used to seeing syntax error, you quickly get the hang of it. And once you do, the function is much nicer. > 2) Best practices. I have the WROX Press Beginning Python book, which > targets Python 2. Clearly that's of only limited value if I'm going to go > with Python 3, but it looks like it's at least going to be a good overview. > But some of the stuff they do seems to be fairly personalized, rather than > trying to follow standards. Should I just start out with the tutorial from > docs.python.org? I would assume that that would start putting me in the > right habits from the beginning... is that accurate, or is there a better > way to go? > > Thanks in advance, > Andy McKenzie I'd start with the python.org tutorial for the version you're trying to learn. Get serious about trying everything, and don't try to absorb it all in one sitting, even though it can be done. And use a text editor that helps you indent, or even that colorizes your code. And when you just want to try things, use the interpreter directly. It's amazing what you can learn directly from it. You can ask the interpreter lots of questions about an object: help(obj) dir(obj) print( type(obj) ) print( repr(obj) ) And don't forget to post here when you seem to be stuck. Sometimes a well placed comment beats days of struggling. When you do get an exception you don't understand, paste the whole thing, as well as the code you were trying. Best of luck. -- DaveA From davea at davea.name Tue Apr 16 22:31:31 2013 From: davea at davea.name (Dave Angel) Date: Tue, 16 Apr 2013 16:31:31 -0400 Subject: [Tutor] oops - resending as plain text In-Reply-To: References: Message-ID: <516DB523.20305@davea.name> On 04/16/2013 01:48 PM, Jim Mooney wrote: > I accidentally sent as HTML so this is a resend in case that choked > the mailing prog ;') > > I was doing a simple training prog to figure monetary change, and > wanted to avoid computer inaccuracy by using only two-decimal input > and not using division or mod where it would cause error. Yet, on a > simple subtraction I got a decimal error instead of a two decimal > result, as per below. What gives? > > cost = float(input('How much did the item cost?: ')) > paid = float(input('How much did the customer give you?: ')) > change = paid - cost > > #using 22.89 as cost and 248.76 as paid > > twenties = int(change / 20) > if twenties != 0: > twentiesAmount = 20 * twenties > change = change - twentiesAmount > #change is 5.8700000000000045, not 5.87 - how did I get this decimal > error when simply subtracting an integer from what should be a > #two-decimal amount? The other responses have been good. But let me point some things out. Binary floating point has been around as long as I've been in computers, which was in 1967. I saw a detailed rant about avoiding errors in manipulating floats, in that year. The fact is that rounding errors can occur in lots of surprising places. For example, if you're using pencil and paper, and you divide 7 by 3, you get 2.333333 and at some point you'll stop writing the 3's. if you then multiply by 3, you get 6.99999 not 7. Now if you're doing it by hand, you just adjust it without thinking much. But a computer is a very literal thing, and fudging numbers isn't necessarily a good idea. In the code above you divided a number by 20, then multiplied by 20 again. That's an operation that happens to come out even in decimal, because 20 is a factor of 100, the base squared. But just like 1/3 is a problem in a decimal system, so 1/20 is a problem in a binary one. The chief advantage of decimal is NOT that it's more accurate, but that it gets the numbers wrong when YOU expect it, not by some other, more subtle rule. And the second advantage is that there are fewer places where the numbers need to be converted, and each conversion might produce an error. It happens that binary floats, as used on Intel hardware, are accurate for integers up to a fairly large value. So some people will represent money in pennies, adjusting only when it's time to print. Others will simply use integers (which have no practical size limit on python 3.x) for the same purpose. That's frequently necessary when doing accounting or banking, since many transactions are rounded or truncated to the nearest penny at each step, according to some standardized rules, rather than keeping the numbers more "accurate." Bottom line, you need to understand enough about what's going on to avoid getting burned. And in case it wasn't obvious, it's not unique to Python. It's potentially a problem in any environment that doesn't have infinite precision. -- DaveA From amckenzie4 at gmail.com Tue Apr 16 23:20:01 2013 From: amckenzie4 at gmail.com (Andy McKenzie) Date: Tue, 16 Apr 2013 17:20:01 -0400 Subject: [Tutor] Hello, and a newbie question In-Reply-To: <516DB208.80006@davea.name> References: <516DB208.80006@davea.name> Message-ID: On Tue, Apr 16, 2013 at 4:18 PM, Dave Angel wrote: > On 04/16/2013 11:58 AM, Andy McKenzie wrote: > >> Hey folks. >> >> I'm just starting to pick up Python, and I'd like to avoid some of the >> mistakes I made in the past. To elaborate on that, my primary >> programming/scripting experience is PHP, with a little bit of Perl thrown >> in. Like so many people who write in PHP, I was entirely self-taught, and >> would be the first to admit that a lot of what I've written is, well... >> wrong. It works, but it's sloppy and inefficient, because there were >> standard constructions and solutions I just didn't know about. I'd like >> to >> avoid that with Python. >> >> > Welcome to the mailing list. I expect you'll find Python a much cleaner > language than the other two, though php has some definite convenience for > its particular niche. > > > > > So: my first two questions to the list. >> >> 1) Python 2.7 or 3.x? I know I'm going to want to do some work with NLTK >> (which appears to only have an alpha version out for Python 3), but I've >> just gone through the hassle of dealing with an upgrade from PHP 4 to 5.3, >> and I'd rather not start learning something that's already obsolete. Any >> words of advice? >> >> > If you have to use a library that's not available yet for 3.x, then you > need to use 2.x on the other hand, if you're learning now, maybe that > library will be available by the time you actually need it. > > For most people, I'd advise against trying to use a tutorial that targets > a different version than you're running. If you get frustrated quickly, > you can get bogged down by the differences when you're just copying an > exact program out of some book. > > Python 3 in particular has spent some substantial effort cleaning up the > warts, the biggest one being Unicode. For beginning programmers using only > ASCII, probably the main thing that'll bog you down is that print() is now > a function, rather than a statement, so you need parentheses. But once you > get used to seeing syntax error, you quickly get the hang of it. And once > you do, the function is much nicer. > > > > 2) Best practices. I have the WROX Press Beginning Python book, which >> targets Python 2. Clearly that's of only limited value if I'm going to go >> with Python 3, but it looks like it's at least going to be a good >> overview. >> But some of the stuff they do seems to be fairly personalized, rather >> than >> trying to follow standards. Should I just start out with the tutorial >> from >> docs.python.org? I would assume that that would start putting me in the >> right habits from the beginning... is that accurate, or is there a better >> way to go? >> >> Thanks in advance, >> Andy McKenzie >> > > I'd start with the python.org tutorial for the version you're trying to > learn. Get serious about trying everything, and don't try to absorb it all > in one sitting, even though it can be done. > > And use a text editor that helps you indent, or even that colorizes your > code. And when you just want to try things, use the interpreter directly. > It's amazing what you can learn directly from it. You can ask the > interpreter lots of questions about an object: > > help(obj) > dir(obj) > print( type(obj) ) > print( repr(obj) ) > > And don't forget to post here when you seem to be stuck. Sometimes a well > placed comment beats days of struggling. When you do get an exception you > don't understand, paste the whole thing, as well as the code you were > trying. > > Best of luck. > > > > Thanks for the advice, folks. Given that it looks like the biggest changes are unicode handling (which I'm not going to need any time soon) and the way the print function works, I decided to stick with 2.7. I'm an IT guy, though unemployed at the moment, and it occurred to me that "I'm familiar with Python, but not the version your entire established codebase is in" wasn't a great thing to have on a resume. Since it looks like the new formatting for print -- that is, print("Print this stuff!") -- works fine in 2.7, I'm just getting myself used to doing that from the beginning. I went through the first four or five sections of the tutorial this afternoon, with a few side trips into things that got me interested, and I figure I'll do at least one more section after dinner. I did find it interesting that one of the first things I wanted to know turned out to be an extremely common question: "What's the Python equivalent to print_r() from PHP?" If any of you are familiar with PHP (I know at least a couple of you seemed to be), you'll know that pprint() (which seems to be the most common answer) isn't actually very close. Its output isn't nearly as readable. For instance: output of running print_r on a very short dictionary from PHP: Array ( [key3] => thing3 [key2] => thing2 [key1] => thing1 ) And running pprint on the same dict in Python: {'key1': 'thing1', 'key2': 'thing2', 'key3': 'thing3'} I finally decided that a good project would be building a quick function that recreates the print_r function, and I got that working. New function output, in Python: ( [key3] => thing3 [key2] => thing2 [key1] => thing1 ) So at least I've figured out enough to do SOMETHING useful, which is reassuring. Anyway, thanks again to all of you, and I'm sure I'll be posting soon with problems. -Andy -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Tue Apr 16 23:31:41 2013 From: davea at davea.name (Dave Angel) Date: Tue, 16 Apr 2013 17:31:41 -0400 Subject: [Tutor] Hello, and a newbie question In-Reply-To: References: <516DB208.80006@davea.name> Message-ID: <516DC33D.1050304@davea.name> On 04/16/2013 05:20 PM, Andy McKenzie wrote: > > >> >> > Thanks for the advice, folks. Given that it looks like the biggest changes > are unicode handling (which I'm not going to need any time soon) and the > way the print function works, I decided to stick with 2.7. I'm an IT guy, > though unemployed at the moment, and it occurred to me that "I'm familiar > with Python, but not the version your entire established codebase is in" > wasn't a great thing to have on a resume. > > Since it looks like the new formatting for print -- that is, print("Print > this stuff!") -- works fine in 2.7, I'm just getting myself used to doing > that from the beginning. > The degenerate print, where you're printing exactly one thing, works the same. But if you have two things to print, putting parens around them in Python 2.x will cause a tuple to be printed, rather than printing the two with a space between. >>> print(3,5) -- version 2.x (3, 5) >>> print(3,5) -- version 3.x 3 5 To get 3.x functionality, you'd want to use from __future__ import print_function and I do not think that works in 2.6 or older versions. It also can be awkward even in 2.7 if you're mixing existing code with new print functions. -- DaveA From amckenzie4 at gmail.com Tue Apr 16 23:47:23 2013 From: amckenzie4 at gmail.com (Andy McKenzie) Date: Tue, 16 Apr 2013 17:47:23 -0400 Subject: [Tutor] Hello, and a newbie question In-Reply-To: <516DC33D.1050304@davea.name> References: <516DB208.80006@davea.name> <516DC33D.1050304@davea.name> Message-ID: On Tue, Apr 16, 2013 at 5:31 PM, Dave Angel wrote: > On 04/16/2013 05:20 PM, Andy McKenzie wrote: > >> >> >> > > >>> >>> Thanks for the advice, folks. Given that it looks like the biggest >> changes >> are unicode handling (which I'm not going to need any time soon) and the >> way the print function works, I decided to stick with 2.7. I'm an IT guy, >> though unemployed at the moment, and it occurred to me that "I'm familiar >> with Python, but not the version your entire established codebase is in" >> wasn't a great thing to have on a resume. >> >> Since it looks like the new formatting for print -- that is, print("Print >> this stuff!") -- works fine in 2.7, I'm just getting myself used to doing >> that from the beginning. >> >> > The degenerate print, where you're printing exactly one thing, works the > same. But if you have two things to print, putting parens around them in > Python 2.x will cause a tuple to be printed, rather than printing the two > with a space between. > > >>> print(3,5) -- version 2.x > (3, 5) > > >>> print(3,5) -- version 3.x > 3 5 > > To get 3.x functionality, you'd want to use > from __future__ import print_function > > and I do not think that works in 2.6 or older versions. It also can be > awkward even in 2.7 if you're mixing existing code with new print functions. > > That's good to know, since I hadn't run into it yet. So am I correct in understanding that I can just put the from __future__ import print_function in each new 2.7 script, and get identical functionality to what happens in 3.x? Or do I need to do that system-wide somehow? -Andy -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Tue Apr 16 23:49:31 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Tue, 16 Apr 2013 14:49:31 -0700 Subject: [Tutor] Tutor Digest, Vol 110, Issue 69 In-Reply-To: References: Message-ID: > Now that Joel Goldstick has pointed out the reason, you may wonder what to do now. Answer? Use the decimal module: > > http://docs.python.org/2/library/decimal.html > > Although, you might prefer Doug Hellmann's introduction: > > http://pymotw.com/2/decimal/ Thanks. I was about to ask that but you beat me to it. I'll try Hellmann. The manual is just a tad wordy and it's hard to find what you want. Jim > From cybervigilante at gmail.com Tue Apr 16 23:46:44 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Tue, 16 Apr 2013 14:46:44 -0700 Subject: [Tutor] oops - resending as plain text In-Reply-To: <516D9E95.2050203@gmail.com> References: <516D9E95.2050203@gmail.com> Message-ID: Further question. If I round the input right at the beginning, round(paid,2) does that mean I still have the original error from using .76 even before math, or does the rounding kill it? I would guess not if it's binary, although Python must have a way to handle money amounts. I'm only on Chapter 2 ;') I assume Python has some automatic way to filter input, so that if someone entered three decimals instead of two for a money amount, they could get a wrist slap. Can you direct me to that functionality? Thanks. Jim On 16 April 2013 11:55, Sander Sweers wrote: > On 04/16/2013 07:48 PM, Jim Mooney wrote: >> I accidentally sent as HTML so this is a resend in case that choked >> the mailing prog ;') >> >> I was doing a simple training prog to figure monetary change, and >> wanted to avoid computer inaccuracy by using only two-decimal input >> and not using division or mod where it would cause error. Yet, on a >> simple subtraction I got a decimal error instead of a two decimal >> result, as per below. What gives? > > Floats can not be represented accurately in binary and will have small > rounding errors. See > https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems. > >> cost = float(input('How much did the item cost?: ')) >> paid = float(input('How much did the customer give you?: ')) >> change = paid - cost >> >> #using 22.89 as cost and 248.76 as paid >> >> twenties = int(change / 20) >> if twenties != 0: >> twentiesAmount = 20 * twenties >> change = change - twentiesAmount >> #change is 5.8700000000000045, not 5.87 - how did I get this decimal >> error when simply subtracting an integer from what should be a >> #two-decimal amount? >> print(twenties, ' twenties') >> print(change) >> >> #and so forth for the rest of the prog > > You can use string formatting to show as much precision you want. Example: > >>>> n = 5.8700000000000045 >>>> print '%.2f' % n > 5.87 >>>> print '%.4f' % n > 5.8700 > > Or use round(), example: > >>>> round(n,2) > 5.87 > > In your case I would just use string formatting to hide the rounding error. > > Greets > ~sander -- Jim Mooney If you shoot a child you're a bad guy. If you splatter forty children across a wall with a bomb, you're a heroic, manly Top Gun with gleaming Tom Cruise teeth. The moral is you'll get laid more if you snuff a lot of children than if you only snuff a few. From davea at davea.name Wed Apr 17 00:09:47 2013 From: davea at davea.name (Dave Angel) Date: Tue, 16 Apr 2013 18:09:47 -0400 Subject: [Tutor] oops - resending as plain text In-Reply-To: References: <516D9E95.2050203@gmail.com> Message-ID: <516DCC2B.7070607@davea.name> On 04/16/2013 05:46 PM, Jim Mooney wrote: > Further question. If I round the input right at the beginning, > round(paid,2) does that mean I still have the original error from > using .76 even before math, or does the rounding kill it? I would > guess not if it's binary, You guess right. round() function is only theoretical, when applied to floats. It can be useful when combined with formatting, as suggested elsewhere in the thread. But even if .76 prints out "correctly," you have no assurance that adding two such apparently-exact figures will give one that will also print out easily. > although Python must have a way to handle > money amounts. I'm only on Chapter 2 ;') > > I assume Python has some automatic way to filter input, so that if > someone entered three decimals instead of two for a money amount, they > could get a wrist slap. Can you direct me to that functionality? > Thanks. > There's no "money type" in Python, and if you want your user to get slapped, you have to write your own. Normally, you take input in the form of text, validate it, then convert to int, float, Decimal, or whatever. If the conversion itself will catch the errors, then you can just use try/catch to make such errors more polite to your users. That's the case if they enter "charlie" when you're asking for a salary value. But if they were to put 7.500 when the value is supposed to be in dollars and cents, then by the time it's turned into a float or decimal, the extra zero is long gone. -- DaveA From davea at davea.name Wed Apr 17 00:17:21 2013 From: davea at davea.name (Dave Angel) Date: Tue, 16 Apr 2013 18:17:21 -0400 Subject: [Tutor] Hello, and a newbie question In-Reply-To: References: <516DB208.80006@davea.name> <516DC33D.1050304@davea.name> Message-ID: <516DCDF1.6040306@davea.name> On 04/16/2013 05:47 PM, Andy McKenzie wrote: > On Tue, Apr 16, 2013 at 5:31 PM, Dave Angel wrote: > >> >> >> To get 3.x functionality, you'd want to use >> from __future__ import print_function >> >> and I do not think that works in 2.6 or older versions. It also can be >> awkward even in 2.7 if you're mixing existing code with new print functions. >> >> > That's good to know, since I hadn't run into it yet. > > So am I correct in understanding that I can just put the from __future__ > import print_function in each new 2.7 script, and get identical > functionality to what happens in 3.x? Or do I need to do that system-wide > somehow? > Someone else may know if "identical" has some exceptions. But as for where to put it, you'd need it for any module (including your own script) which is going to use the newer print() function. And the nice thing is that the from-future directive is ignored in 3.x, so you don't have to remove it when you do progress. -- DaveA From hugo.yoshi at gmail.com Wed Apr 17 00:10:57 2013 From: hugo.yoshi at gmail.com (Hugo Arts) Date: Wed, 17 Apr 2013 00:10:57 +0200 Subject: [Tutor] How did this decimal error pop up? In-Reply-To: References: Message-ID: On Tue, Apr 16, 2013 at 7:43 PM, Jim Mooney wrote: > I was doing a simple training prog to figure change, and wanted to avoid > computer inaccuracy by using only two-decimal input and not using division > or mod where it would cause error. Yet, on a simple subtraction I got a > decimal error instead of a two decimal result, as per below. What gives? > > Your assumption that using only two-decimal input and no division/modulo would avoid computer inaccuracy is wrong. In fact, for some values floating point numbers don't even have 1 decimal accuracy (all examples done in python 2.7.3): >>> 0.1 + 0.2 0.30000000000000004 This is a limitation of the way floating point numbers are represented in hardware (some python versions may actually print 0.3 here, but the number stored in memory is *not* 0.3. It can't be). floating point accuracy isn't as simple as "accurate to 5 decimal places, always." Some numbers simply *can not* be represented as a floating point value. A simple example of this is the number 0.1, it has no exact floating point representation. Note that python appears to have no problem storing the value 0.1: >>> a = 0.1 >>> a 0.1 But this is just because python actually rounds numbers when it is displaying them. We can show that there are still errors by adding the errors up to make them visible: >>> i = 0 >>> for _ in range(1000): i += 0.1 >>> i 99.9999999999986 That should, by all the laws of math, be 100. But it isn't. Because the computer can't store 0.1 in a float, so it stores the closest possible number it can instead. The value stored in a above is not actually 0.1, it's closer to: 0.1000000000000000055511151231257827021181583404541015625 The precise value kind of depends on what hardware you have, but it can *never* be 0.1 exactly. The format that floating point numbers are stored in simply cannot represent the value 0.1. The reason for this is kind of complicated, it has to do with how the number is stored in hardware. A good analogy for base 10 is the number 1/3. To write that number down in a decimal notation you'd need an infinite amount of space: 0.3333333..... and so on. In floating point, 0.1, along with a ton of other numbers, are the same way: you'd need an infinite amount of space to store them. To store decimals with perfect accuracy, you have 2 options. The most basic is what is generally called "fixed point" arithmetic. You decide beforehand on the amount of accuracy you would like to have, say 2 decimals. Then you simply multiply all numbers by 10^decimals_of_accuracy (in this case, 100) and store them in a regular int. So 10.43 would become 1043. Then when you're displaying a number, just put the decimal point back in. This is pretty simple, gives you perfect (though fixed) accuracy, but it's also kind of tedious. The other option, and probably the simplest to use, is python's built in decimal module, which provides a special class that implements perfectly accurate decimal calculations. Why don't we use it for all applications, you might ask? Well, it is extremely slow when compared to floats, and usually float accuracy is good enough for people that they don't care about the inaccuracies. Only packages that absolutely need accuracy use decimal, like accounting software. The documentation for the decimal module is here: http://docs.python.org/2/library/decimal.html everything a computer scientist should know about floating point is here: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html HTH, Hugo -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Wed Apr 17 00:45:41 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 16 Apr 2013 18:45:41 -0400 Subject: [Tutor] oops - resending as plain text In-Reply-To: <516DCC2B.7070607@davea.name> References: <516D9E95.2050203@gmail.com> <516DCC2B.7070607@davea.name> Message-ID: On Tue, Apr 16, 2013 at 6:09 PM, Dave Angel wrote: > If the conversion itself will catch the errors, then you can just use > try/catch to make such errors more polite to your users. That's the case if > they enter "charlie" when you're asking for a salary value. But if they > were to put 7.500 when the value is supposed to be in dollars and cents, > then by the time it's turned into a float or decimal, the extra zero is long > gone. With Decimal it's not really 'long gone'. It affects the number of significant digits retained in arithmetic operations: >>> from decimal import Decimal >>> context = decimal.getcontext() >>> Decimal('7.500') + Decimal('0.50') Decimal('8.000') You could look specifically at the _exp attribute, or quantize with a trap for inexact rounding: >>> Decimal('7.500')._exp -3 def round_money(value): with decimal.localcontext() as ctx: ctx.traps[decimal.Inexact] = 1 return Decimal(value).quantize(Decimal('1.00')) >>> try: round_money('7.500') ... except decimal.Inexact: print 'ack!' ... Decimal('7.50') >>> try: round_money('7.501') ... except decimal.Inexact: print 'ack!' ... ack! >>> try: round_money('charlie') ... except decimal.InvalidOperation as e: print 'ack!' ... ack! Please don't print a useless error message like 'ack'; it was just a silly example. Handle the error within the logical context of your application. From davea at davea.name Wed Apr 17 01:02:45 2013 From: davea at davea.name (Dave Angel) Date: Tue, 16 Apr 2013 19:02:45 -0400 Subject: [Tutor] How did this decimal error pop up? In-Reply-To: References: Message-ID: <516DD895.3060806@davea.name> On 04/16/2013 06:10 PM, Hugo Arts wrote: > > > The other option, and probably the simplest to use, is python's built in > decimal module, which provides a special class that implements perfectly > accurate decimal calculations. Why don't we use it for all applications, > you might ask? Well, it is extremely slow when compared to floats, and I've been told (here) that starting with about Python 3.3, the decimal package is nearly as fast as float, for typical use. The underlying processor logic is much slower, but it gets swamped by Python's overhead manipulating objects and searching dicts. By nearly as fast, I'm thinking like 30%, rather than the previous 1000%. Or some such. -- DaveA From eryksun at gmail.com Wed Apr 17 01:06:48 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 16 Apr 2013 19:06:48 -0400 Subject: [Tutor] How did this decimal error pop up? In-Reply-To: References: Message-ID: On Tue, Apr 16, 2013 at 6:10 PM, Hugo Arts wrote: >>>> i = 0 >>>> for _ in range(1000): > i += 0.1 > >>>> i > 99.9999999999986 > > That should, by all the laws of math, be 100. But it isn't. Because the > computer can't store 0.1 in a float, so it stores the closest possible > number it can instead. The value stored in a above is not actually 0.1, it's > closer to: > > 0.1000000000000000055511151231257827021181583404541015625 Now you have to explain how the summation ends up as less than 100. ;) That really gets to the heart of error introduced by intermediate rounding with fixed-precision arithmetic. This is a more important point than the fact that 0.1 doesn't have an exact representation in binary floating point. Python's floats are limited to hardware precision, which is 53 bits or floor(53*log10(2)) == 15 decimal digits. There's no option to extend the precision arbitrarily as is possible with the Decimal type. BTW, did you know Decimal got a C implementation in 3.3? It's a lot faster than the pure Python implementation in previous versions, but still not as fast as hardware floats. From alan.gauld at btinternet.com Wed Apr 17 01:39:14 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 17 Apr 2013 00:39:14 +0100 Subject: [Tutor] Hello, and a newbie question In-Reply-To: References: <516DB208.80006@davea.name> Message-ID: On 16/04/13 22:20, Andy McKenzie wrote: > For instance: output of running print_r on a very short dictionary from > PHP: > > Array > ( > [key3] => thing3 > [key2] => thing2 > [key1] => thing1 > ) > > And running pprint on the same dict in Python: > > {'key1': 'thing1', 'key2': 'thing2', 'key3': 'thing3'} > > > I finally decided that a good project would be building a quick function > that recreates the print_r function, and I got that working. New > function output, in Python: > > ( > [key3] => thing3 > [key2] => thing2 > [key1] => thing1 > ) You should probably use {} instead of () as the delimiter to indicate that the thing is a dictionary and not a tuple. but otherwise that's a good starter project. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From eryksun at gmail.com Wed Apr 17 01:39:03 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 16 Apr 2013 19:39:03 -0400 Subject: [Tutor] Hello, and a newbie question In-Reply-To: <516DCDF1.6040306@davea.name> References: <516DB208.80006@davea.name> <516DC33D.1050304@davea.name> <516DCDF1.6040306@davea.name> Message-ID: On Tue, Apr 16, 2013 at 6:17 PM, Dave Angel wrote: > Someone else may know if "identical" has some exceptions. But as for where > to put it, you'd need it for any module (including your own script) which is > going to use the newer print() function. I think any differences will result from the I/O system redesign in 3.x. In 2.x sys.stdout is still the old "file" type, which is basically a wrapper around CRT FILE streams, while in 3.x it's a TextIOWrapper wrapping a BufferedWriter wrapping a FileIO object. Off the top of my head I don't have a clear example where it matters. I vaguely recall having an issue with the default buffer flushing not being the same. I think I was simulating scrolling text by printing a carriage return ('\r') to overwrite a line. IRRC, in the end I opted to directly use sys.stdout.write() and sys.stdout.flush(). Since __future__ imports are compiler directive, you have to include them at the top of every module. "print_function" works in 2.6+. If you just want the function under a different name, you can grab it from the __builtin__ module: >>> import __builtin__ >>> printf = getattr(__builtin__, 'print') >>> printf('spam') spam From amckenzie4 at gmail.com Wed Apr 17 01:46:06 2013 From: amckenzie4 at gmail.com (Andy McKenzie) Date: Tue, 16 Apr 2013 19:46:06 -0400 Subject: [Tutor] Hello, and a newbie question In-Reply-To: References: <516DB208.80006@davea.name> Message-ID: On Tue, Apr 16, 2013 at 7:39 PM, Alan Gauld wrote: > On 16/04/13 22:20, Andy McKenzie wrote: > > For instance: output of running print_r on a very short dictionary from >> PHP: >> >> Array >> ( >> [key3] => thing3 >> [key2] => thing2 >> [key1] => thing1 >> ) >> >> And running pprint on the same dict in Python: >> >> {'key1': 'thing1', 'key2': 'thing2', 'key3': 'thing3'} >> >> >> I finally decided that a good project would be building a quick function >> that recreates the print_r function, and I got that working. New >> function output, in Python: >> >> ( >> [key3] => thing3 >> [key2] => thing2 >> [key1] => thing1 >> ) >> > > > You should probably use {} instead of () as the delimiter to indicate that > the thing is a dictionary and not a tuple. but otherwise that's a good > starter project. > > Good idea. I went with () because I was just trying to duplicate the output in PHP. Now that I've got that, I can start thinking about improvements. Varying the punctuation to match the type would probably be a good idea. Thanks, Andy -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Wed Apr 17 02:11:03 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Wed, 17 Apr 2013 10:11:03 +1000 Subject: [Tutor] Hello, and a newbie question In-Reply-To: References: Message-ID: <516DE897.8070404@pearwood.info> On 17/04/13 01:58, Andy McKenzie wrote: > 1) Python 2.7 or 3.x? I know I'm going to want to do some work with NLTK > (which appears to only have an alpha version out for Python 3), but I've > just gone through the hassle of dealing with an upgrade from PHP 4 to 5.3, > and I'd rather not start learning something that's already obsolete. Any > words of advice? Python 3.3 is awesome and much cleaner and better than 2.7, and 2.7 is pretty damn good! So if you have a choice, pick 3.3. It's the future of Python, 2.7 is the past. But, 2.7 is still good, and if you need NLTK *right now* you might not have a choice. (Unless you like being a guinea pig working with an alpha version.) Also, the *incompatibilities* between 2.7 and 3.3 are fairly small. The biggest difference from a beginner's perspective is that print is no longer a statement, it is a function, so instead of writing this: print "Hello world!" you have to write this: print("Hello world!") That doesn't seem too onerous, does it? If you can cope with a few differences of that complexity, why not learn both? > 2) Best practices. I have the WROX Press Beginning Python book, which > targets Python 2. Clearly that's of only limited value if I'm going to go > with Python 3, but it looks like it's at least going to be a good overview. > But some of the stuff they do seems to be fairly personalized, rather than > trying to follow standards. Should I just start out with the tutorial from > docs.python.org? I would assume that that would start putting me in the > right habits from the beginning... is that accurate, or is there a better > way to go? If there's a Python 3 version of "Learning Python", from O'Reilly Books (sorry I forget the authors), give it a go. The first edition, at least, is an awesome book although you will want a more recent version since the first edition deals with Python 1.5, which truly is ancient history! I haven't done the official Python tutorial, but from what I've seen of it, it's pretty good. -- Steven From eryksun at gmail.com Wed Apr 17 02:15:07 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 16 Apr 2013 20:15:07 -0400 Subject: [Tutor] Hello, and a newbie question In-Reply-To: <1366156656384.bcbb86a8@Nodemailer> References: <1366156656384.bcbb86a8@Nodemailer> Message-ID: On Tue, Apr 16, 2013 at 7:57 PM, Virgilio Rodriguez Jr wrote: > Can someone please do me the favor and remove me from this god forsaken > email list I am sorry I signed up all it has done is taken over my phone and > rings all night long with emails I am not interested in any more because it > is just too many darn emails. I keep trying to log in and nothing it will > not let me unsubscribe and it is BS already. You can get a password reminder here: http://mail.python.org/mailman/options/tutor If you're sure that you have the correct password and still can't unsubscribe, then email the administrator, tutor-owner at python.org. Alan Gauld is active in this thread, BTW, in case you happen to have read the admin page where it says "Tutor list run by wescpy at gmail.com, alan.gauld at btinternet.com". From eryksun at gmail.com Wed Apr 17 02:34:24 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 16 Apr 2013 20:34:24 -0400 Subject: [Tutor] Hello, and a newbie question In-Reply-To: References: <1366156656384.bcbb86a8@Nodemailer> Message-ID: On Tue, Apr 16, 2013 at 8:15 PM, eryksun wrote: >> Can someone please do me the favor and remove me from this god forsaken >> email list I am sorry I signed up all it has done is taken over my phone and >> rings all night long with emails I am not interested in any more because it >> is just too many darn emails. I keep trying to log in and nothing it will >> not let me unsubscribe and it is BS already. > > You can get a password reminder here: > http://mail.python.org/mailman/options/tutor > > If you're sure that you have the correct password and still can't > unsubscribe, then email the administrator, tutor-owner at python.org. > Alan Gauld is active in this thread, BTW, in case you happen to have > read the admin page where it says "Tutor list run by wescpy at > gmail.com, alan.gauld at btinternet.com". I just went through the steps. You don't even need your password. Enter your email address in the bottom field of the list info page: http://mail.python.org/mailman/listinfo/tutor Click the button that says "Unsubscribe or edit options". Then simply click the "Unsubscribe" button in the middle of the options page. You'll get a confirmation email with instructions to complete the process. From sander.sweers at gmail.com Wed Apr 17 02:44:32 2013 From: sander.sweers at gmail.com (Sander Sweers) Date: Wed, 17 Apr 2013 02:44:32 +0200 Subject: [Tutor] Hello, and a newbie question In-Reply-To: References: <1366156656384.bcbb86a8@Nodemailer> Message-ID: <516DF070.4080301@gmail.com> On 04/17/2013 02:34 AM, eryksun wrote: > I just went through the steps. You don't even need your password. > Enter your email address in the bottom field of the list info page: > > http://mail.python.org/mailman/listinfo/tutor > > Click the button that says "Unsubscribe or edit options". Then simply > click the "Unsubscribe" button in the middle of the options page. > You'll get a confirmation email with instructions to complete the > process. Or send an e-mail to tutor-request at python.org with unsubscribe in the subject. ~sander From cybervigilante at gmail.com Wed Apr 17 03:02:26 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Tue, 16 Apr 2013 18:02:26 -0700 Subject: [Tutor] regex to promote Py 2 to Py 3? Message-ID: I already tried an example I copied from something online, in Py 2, that had a ton of print statements. So I did some fast search and replace to make them Py 3 with (), since I'm using Py 3. (Except Wing 101 won't do Replace All for some reason I haven't figured out, so it's a bit tedious) So for online progs, examples, ebooks, etc, that still have Py 2 examples I can copy, has anyone come up with a nice regex package to do most of the conversions and produce a mostly Py3 from a Py2? That might make some things a bit easier. I use Clipmate, which has a regex option so I could just copy a Py2 script, run the regex, and paste back a Py3. I could probably work one out but since I don't know Py yet, that could be problematic ;') Jim From michael.weylandt at gmail.com Wed Apr 17 03:35:48 2013 From: michael.weylandt at gmail.com (Michael Weylandt) Date: Tue, 16 Apr 2013 21:35:48 -0400 Subject: [Tutor] regex to promote Py 2 to Py 3? In-Reply-To: References: Message-ID: On Apr 16, 2013, at 21:02, Jim Mooney wrote: > I already tried an example I copied from something online, in Py 2, > that had a ton of print statements. So I did some fast search and > replace to make them Py 3 with (), since I'm using Py 3. (Except Wing > 101 won't do Replace All for some reason I haven't figured out, so > it's a bit tedious) > > So for online progs, examples, ebooks, etc, that still have Py 2 > examples I can copy, has anyone come up with a nice regex package to > do most of the conversions and produce a mostly Py3 from a Py2? That > might make some things a bit easier. I use Clipmate, which has a regex > option so I could just copy a Py2 script, run the regex, and paste > back a Py3. I could probably work one out but since I don't know Py > yet, that could be problematic ;') Much ink has been spilled on just such a translation, but you may as well start with the 2to3 script and see if that suffices for your needs: http://docs.python.org/2/library/2to3.html Michael > > Jim > _______________________________________________ > 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 Wed Apr 17 04:24:08 2013 From: eryksun at gmail.com (eryksun) Date: Tue, 16 Apr 2013 22:24:08 -0400 Subject: [Tutor] regex to promote Py 2 to Py 3? In-Reply-To: References: Message-ID: On Tue, Apr 16, 2013 at 9:02 PM, Jim Mooney wrote: > So for online progs, examples, ebooks, etc, that still have Py 2 > examples I can copy, has anyone come up with a nice regex package to > do most of the conversions and produce a mostly Py3 from a Py2? That > might make some things a bit easier. Generally the 2to3 script does an OK job. If you're using Windows it's [Python_Dir]\Tools\Scripts\2to3.py. http://docs.python.org/3/library/2to3 lib2to3 doesn't have a stable API, but you can use it in the REPL if you want to experiment: >>> from lib2to3.refactor import RefactoringTool >>> rt = RefactoringTool(['lib2to3.fixes.fix_print']) >>> code2 = r''' ... for s in strings: ... print >>myfile, s, ... ''' >>> code3 = str(rt.refactor_string(code2, '')) >>> print(code3) for s in strings: print(s, end=' ', file=myfile) If you want all the fixes applied, you can use >>> from lib2to3.refactor import ( ... RefactoringTool, get_fixers_from_package) >>> rt = RefactoringTool(get_fixers_from_package('lib2to3.fixes')) >>> code2 = r''' ... class Test(object): ... __metaclass__ = MetaTest ... ''' >>> code3 = str(r.refactor_string(code2, '')) >>> print(code3) class Test(object, metaclass=MetaTest): pass From jslozier at gmail.com Wed Apr 17 03:49:03 2013 From: jslozier at gmail.com (Jay Lozier) Date: Tue, 16 Apr 2013 21:49:03 -0400 Subject: [Tutor] How did this decimal error pop up? In-Reply-To: References: Message-ID: <516DFF8F.5020106@gmail.com> On 04/16/2013 01:43 PM, Jim Mooney wrote: > I was doing a simple training prog to figure change, and wanted to > avoid computer inaccuracy by using only two-decimal input and not > using division or mod where it would cause error. Yet, on a simple > subtraction I got a decimal error instead of a two decimal result, as > per below. What gives? > > cost = float(input('How much did the item cost?: ')) > paid = float(input('How much did the customer give you?: ')) > change = paid - cost > > *#using 22.89 as cost and 248.76 as paid* > > twenties = int(change / 20) > if twenties != 0: > twentiesAmount = 20 * twenties > change = change - twentiesAmount > *#change is 5.8700000000000045, not 5.87 - how did I get this decimal > error when simply subtracting an integer from what should be a > #two-decimal amount? > * print(twenties, ' twenties') > print(change) > > #and so forth for the rest of the change > > -- > *Jim Mooney > * This is a common problem with decimal numbers that is discussed in various numerical methods texts and is independent of the programming language. The two numerical texts I have from the 1980's discuss this problem using FORTRAN and Pascal ( I am fairly certain they are out of print). It caused by binary representation of decimal numbers at times will introduce errors in decimal numbers. Many decimal numbers can not be exactly represented by a binary number with some binary representations being a little higher and some a little lower than the actual number. There are recommend algorithms and data encoding techniques to use to minimize these problems. Integers always have an exact binary representation so if it one can change the problem to one that uses integers instead of floats then the rounding problem disappears. Many financial calculations can be converted from dollars to cents to avoid decimals. Unfortunately, many science and engineering calculations will need to address the decimal to binary to decimal representation errors. It can be a nasty problem if one does not address it properly an even larger error could occur. Often it is suitable error because one does not spot that an intermediate calculation is incorrectly implemented. -- Jay Lozier jslozier at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Wed Apr 17 07:11:33 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Tue, 16 Apr 2013 22:11:33 -0700 Subject: [Tutor] regex to promote Py 2 to Py 3? In-Reply-To: References: Message-ID: > Generally the 2to3 script does an OK job. If you're using Windows it's > [Python_Dir]\Tools\Scripts\2to3.py. > > http://docs.python.org/3/library/2to3 ================================ Thanks. I didn't know where to find it and thought I had to install it. I opened a command window in my Python33/progs dir, started Python, and ran it on a tiny test program called loops.py but I get "invalid syntax" Any idea why?: >>> 2to3 loops.py File "", line 1 2to3 loops.py ^ SyntaxError: invalid syntax The loops.py program simply had the old-style print as a single test statement. ie: print 'Machiavelli' Jim From eryksun at gmail.com Wed Apr 17 09:21:24 2013 From: eryksun at gmail.com (eryksun) Date: Wed, 17 Apr 2013 03:21:24 -0400 Subject: [Tutor] regex to promote Py 2 to Py 3? In-Reply-To: References: Message-ID: On Wed, Apr 17, 2013 at 1:11 AM, Jim Mooney wrote: >>>> 2to3 loops.py > File "", line 1 > 2to3 loops.py > ^ > SyntaxError: invalid syntax The script 2to3.py is run from the system's terminal/console shell (e.g. cmd or PowerShell on Windows), not the python shell. If the current directory has the file "loops.py" and Python is installed in C:\Python33, then try running the following in cmd: C:\Python33\Tools\Scripts\2to3.py -w loops.py If that fails, try running 3.3 explicitly: C:\Python33\python.exe C:\Python33\Tools\Scripts\2to3.py -w loops.py The -w option tells 2to3 to write the ported version back to loops.py. The original will be backed up to loops.py.bak. ---- Running Scripts Python 3.3 is distributed on Windows with a "py" launcher that's associated with .py files. This should be set up by the installer as follows: C:\>assoc .py .py=Python.File C:\>ftype Python.File Python.File="C:\Windows\py.exe" "%1" %* The launcher parses a script's shebang line, which is a special comment on the first line. A shebang begins with an exclamation point (i.e. a "bang"), followed by the command used to run the script. The launcher accepts a literal command (e.g. #!C:\Python33\python.exe), a preset virtual command, or an alias you've added to the configuration ini. For example, this shebang runs a script in the default Python version: #!/usr/bin/env python "/usr/bin/env" is a Unix-ism included for portability. You can simply use "#!python3" if you want the script to run in 3.x on Windows. 2.x is the default if it's installed. You can configure the launcher to instead use 3.x as the default. Just edit the configuration ini: >notepad %localappdata%\py.ini to include the following: [defaults] python=3 For convenience, you can add your script directories to the environment PATH. You can also append ;.PY to the environment PATHEXT to be able to run "script.py" as just "script", without the .py extension. From wprins at gmail.com Wed Apr 17 10:40:38 2013 From: wprins at gmail.com (Walter Prins) Date: Wed, 17 Apr 2013 09:40:38 +0100 Subject: [Tutor] regex to promote Py 2 to Py 3? In-Reply-To: References: Message-ID: Hi, On 17 April 2013 06:11, Jim Mooney wrote: > > Generally the 2to3 script does an OK job. If you're using Windows it's > > [Python_Dir]\Tools\Scripts\2to3.py. > > > > http://docs.python.org/3/library/2to3 > ================================ > > Thanks. I didn't know where to find it and thought I had to install it. > > I opened a command window in my Python33/progs dir, started Python, > and ran it on a tiny test program called loops.py but I get "invalid > syntax" Any idea why?: > > >>> 2to3 loops.py > File "", line 1 > 2to3 loops.py > ^ > SyntaxError: invalid syntax As additional background to eryksun's response, please read this: http://www.voidspace.org.uk/python/articles/command_line.shtml Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Wed Apr 17 18:09:59 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Wed, 17 Apr 2013 09:09:59 -0700 Subject: [Tutor] Tutor Digest, Vol 110, Issue 74 In-Reply-To: References: Message-ID: > The script 2to3.py is run from the system's terminal/console shell > (e.g. cmd or PowerShell on Windows), not the python shell. Yay, it worked! A decade of Windows and I'm back to the DOS Command Line ;') Well, it worked the second time.I thought I could do without the -w but nothing happened. Now I'll go edit Path so I'm not typing in all those directories. 2to3 doesn't seem to do anything without the -w, which I find a tad puzzling. Jim From timomlists at gmail.com Wed Apr 17 18:46:05 2013 From: timomlists at gmail.com (Timo) Date: Wed, 17 Apr 2013 18:46:05 +0200 Subject: [Tutor] Tutor Digest, Vol 110, Issue 74 In-Reply-To: References: Message-ID: <516ED1CD.9060705@gmail.com> Op 17-04-13 18:09, Jim Mooney schreef: >> The script 2to3.py is run from the system's terminal/console shell >> (e.g. cmd or PowerShell on Windows), not the python shell. > Yay, it worked! A decade of Windows and I'm back to the DOS Command > Line ;') If you want to program, the command line is your friend. You'll see it alot more. > Well, it worked the second time.I thought I could do without > the -w but nothing happened. Now I'll go edit Path so I'm not typing > in all those directories. 2to3 doesn't seem to do anything without > the -w, which I find a tad puzzling. From the 2to3 --help: -w, --write Write back modified files So it's normal nothing happens to your files without the -w argument. It just prints the changes to stdout. Timo > > Jim > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor From bicofino at gmail.com Wed Apr 17 21:27:50 2013 From: bicofino at gmail.com (Danilo Chilene) Date: Wed, 17 Apr 2013 16:27:50 -0300 Subject: [Tutor] Sys.argv read parameters Message-ID: Dear Python Tutor, I have the code below(file.py): import sys a = 'This is A' b = 'This is B' c = 'This is C' for i in sys.argv[1]: if sys.argv[1] == 'a': print a if sys.argv[1] == 'b': print b if sys.argv[1] == 'c': print c I run python file.py a and returns the var a, so far so good. The problem is that i have a bunch of vars(like a to z), how I can handle this in a pythonic way? Best Regards, Danilo -------------- next part -------------- An HTML attachment was scrubbed... URL: From dyoo at hashcollision.org Wed Apr 17 22:03:49 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 17 Apr 2013 14:03:49 -0600 Subject: [Tutor] Sys.argv read parameters In-Reply-To: References: Message-ID: What's the part that's "changing"? What's the part that stays the same? I would recommend thinking of this in terms of a function. Can you write a function that consumes a letter l and returns the string "This is ..." where "..." is the uppercased l? As an example of a simple function on strings: ########################## ## double: string -> string def double(x): return x + x ## For example, a blast from the past: print "The Noid says: " + double("pizza") ########################## There are functions in Python standard library that know how to do things to strings. See: http://docs.python.org/2/library/stdtypes.html#string-methods From davea at davea.name Wed Apr 17 22:18:24 2013 From: davea at davea.name (Dave Angel) Date: Wed, 17 Apr 2013 16:18:24 -0400 Subject: [Tutor] Sys.argv read parameters In-Reply-To: References: Message-ID: <516F0390.6010903@davea.name> On 04/17/2013 03:27 PM, Danilo Chilene wrote: > Dear Python Tutor, > > I have the code below(file.py): > > import sys > > a = 'This is A' > b = 'This is B' > c = 'This is C' > > for i in sys.argv[1]: > if sys.argv[1] == 'a': > print a > if sys.argv[1] == 'b': > print b > if sys.argv[1] == 'c': > print c Since this is a loop, I'll assume that argv[1] was supposed to permit multiple characters. If so, your loop is buggy. And if not, then you don't want a loop. > > I run python file.py a and returns the var a, so far so good. What do you want to happen if you say python file.py ac > > The problem is that i have a bunch of vars(like a to z), how I can handle > this in a pythonic way? > Use a dictionary (dict). Instead of separate 'variables' use one dict. (With version 2.7) import sys mystrings = { "a" : "This is A", "b" : "This is B", "c" : "This is C", "d" : "This is some special case D", } for parm in sys.argv[1]: if parm in mystrings: print mystrings[parm] else: print "Invalid parm" If this isn't what you wanted, then you'll have to make it clearer. 1) tell us what version of python 2) supply us with a non-buggy program, 3) be much more specific about what change you want. You don't want more vars, you presumably want a way to avoid having more vars. Danny assumed you wanted those exact strings, for a, b, and c, while i assumed that those were just simple examples. -- DaveA From marc.tompkins at gmail.com Wed Apr 17 22:24:52 2013 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 17 Apr 2013 13:24:52 -0700 Subject: [Tutor] Sys.argv read parameters In-Reply-To: References: Message-ID: On Wed, Apr 17, 2013 at 1:03 PM, Danny Yoo wrote: > ########################## > ## double: string -> string > def double(x): > return x + x > > > ## For example, a blast from the past: > print "The Noid says: " + double("pizza") > ########################## > I'm sorry, but this is a bug. The Noid tried to make Domino's pizzas get cold before they arrived; Little Caesar said "Pizza, pizza!" > ## For example, a blast from the past: > print "Caesar says: " + double("pizza") > ########################## > =D -------------- next part -------------- An HTML attachment was scrubbed... URL: From bicofino at gmail.com Wed Apr 17 22:28:00 2013 From: bicofino at gmail.com (Danilo Chilene) Date: Wed, 17 Apr 2013 17:28:00 -0300 Subject: [Tutor] Sys.argv read parameters In-Reply-To: <516F0390.6010903@davea.name> References: <516F0390.6010903@davea.name> Message-ID: Hello Dave, 1) I'm using Python 2.7 2) The program wasn't suppose to really work, was just a example. 3) You assumed correct. That's was what I looking for, worked like charm. Thanks! On Wed, Apr 17, 2013 at 5:18 PM, Dave Angel wrote: > On 04/17/2013 03:27 PM, Danilo Chilene wrote: > >> Dear Python Tutor, >> >> I have the code below(file.py): >> >> import sys >> >> a = 'This is A' >> b = 'This is B' >> c = 'This is C' >> >> for i in sys.argv[1]: >> if sys.argv[1] == 'a': >> print a >> if sys.argv[1] == 'b': >> print b >> if sys.argv[1] == 'c': >> print c >> > > Since this is a loop, I'll assume that argv[1] was supposed to permit > multiple characters. If so, your loop is buggy. And if not, then you > don't want a loop. > > > >> I run python file.py a and returns the var a, so far so good. >> > > What do you want to happen if you say > python file.py ac > > > > >> The problem is that i have a bunch of vars(like a to z), how I can handle >> this in a pythonic way? >> >> > Use a dictionary (dict). Instead of separate 'variables' use one dict. > (With version 2.7) > > import sys > > mystrings = { "a" : "This is A", > "b" : "This is B", > "c" : "This is C", > "d" : "This is some special case D", > } > > for parm in sys.argv[1]: > if parm in mystrings: > print mystrings[parm] > else: > print "Invalid parm" > > If this isn't what you wanted, then you'll have to make it clearer. > > 1) tell us what version of python > 2) supply us with a non-buggy program, > 3) be much more specific about what change you want. You don't want more > vars, you presumably want a way to avoid having more vars. Danny assumed > you wanted those exact strings, for a, b, and c, while i assumed that those > were just simple examples. > > > -- > 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 dyoo at hashcollision.org Wed Apr 17 22:49:07 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 17 Apr 2013 14:49:07 -0600 Subject: [Tutor] Sys.argv read parameters In-Reply-To: References: <516F0390.6010903@davea.name> Message-ID: Wait. If the solution that we're stopping at to use a hashtable here, that's not quite right. A good solution to this should be _much_ shorter, on the order of a one-liner. Hashtables are great, but they're not the answer to everything. If we're doing something like: a -> "This is A" b -> "This is B" ... z -> "This is Z" a good solution to this isn't to make a hashtable with 26 entries, and do a lookup: the approach is more something like this: ############################### def getMessage(letter): return "This is " + letter.upper() ############################### For example: ################# >>> getMessage('a') 'This is A' >>> getMessage('b') 'This is B' >>> getMessage('z') 'This is Z' ################# The size of your program should be proportional to how "differently" it has to act on input. In this case, the program is pretty much the same on all inputs, modulo the very last chunk of the message. That's why thinking about this in terms of functions is crucial: if you don't, the code ends up being larger than it deserves. From davea at davea.name Wed Apr 17 23:02:36 2013 From: davea at davea.name (Dave Angel) Date: Wed, 17 Apr 2013 17:02:36 -0400 Subject: [Tutor] Sys.argv read parameters In-Reply-To: References: <516F0390.6010903@davea.name> Message-ID: <516F0DEC.9020205@davea.name> On 04/17/2013 04:49 PM, Danny Yoo wrote: > Wait. If the solution that we're stopping at to use a hashtable here, > that's not quite right. Nothing wrong with a dict, if a proper specification of the problem were available. Notice that in my solution, the messages were not all trivially related to each other. I made some guesses, and you made some different ones. The OP is happy. Let it rest. -- DaveA From dyoo at hashcollision.org Wed Apr 17 23:15:10 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 17 Apr 2013 15:15:10 -0600 Subject: [Tutor] Sys.argv read parameters In-Reply-To: <516F0DEC.9020205@davea.name> References: <516F0390.6010903@davea.name> <516F0DEC.9020205@davea.name> Message-ID: Yup! Sorry about my tone for its stridency. But I just got concerned that the original poster seemed content about turning the chain of if statements into a table definition. To my mind, they're very closely related, data and control. I'm trying to push the OP to realizing that if they are doing this, they are still enumerating all the decisions. Maybe it's not in the form of a chain of if statements, but it's still reflected in the structure of the table. (It's the same reason I get concerned when I see students not recognize the similarities between if statements and polymorphism: it's all about transmogrifying control flow and data structures.) Let me say that if there's non-uniformity among the choices, then the table lookup approach (a dispatch table) is probably the right tool. If there's uniformity, then a computational approach should be considered. From cbc at unc.edu Wed Apr 17 23:18:55 2013 From: cbc at unc.edu (Chris Calloway) Date: Wed, 17 Apr 2013 17:18:55 -0400 Subject: [Tutor] PyCamp Registration Open for Columbus, Toronto, and Oshkosh Message-ID: <516F11BF.7060404@unc.edu> Registration is open for three upcoming PyCamps produced by the Triangle Python Users Group: - A five-day PyOhio PyCamp hosted by the Ohio State University Open Source Club, July 22-26, 2013 the week prior to the PyOhio regional Python conference weekend. PyCamp is a training program and sponsor of PyOhio: http://trizpug.org/boot-camp/pyohio13/ - A five-day Toronto PyCamp hosted by the University of Toronto Department of Physics, August 12-16, 2013 the week after the PyCon Canada national Python conference weekend. PyCamp is a Diversity Sponsor of PyCon CA: http://trizpug.org/boot-camp/torpy13/ - A three-day Wisconsin Mini-PyCamp hosted at the University of Wisconsin Oshkosh, June 2-4, 2013 as part of the Plone Symposium Midwest training days: http://trizpug.org/boot-camp/wiscpy13/ PyCamp is the original, ultra-low-cost Python Boot Camp created by a user group for user groups. For beginners, PyCamp makes you productive so you can get your work done quickly. PyCamp emphasizes the features which make Python a simpler and more efficient language. Following along with example Python PushUps speeds your learning process. Become a self-sufficient Python developer at PyCamp. PyCamps are conducted in state of the art high technology classrooms on university campuses. Registration will open soon also for two additional Triangle Python User Group boot camp events. An additional announcement will follow when registration opens for these events, but mark your calendars now: - A five-day Seattle PyCamp hosted by the University of Washington Department of Computer Science and Engineering and UW Marketing, September 9-13, 2013. PyCamp is a sponsor of the Seattle Plone Users Group. - A five-day special Python Web Programming boot camp hosted by the University of North Carolina Department of Marine Sciences, August 5-9, 2013. -- Sincerely, Chris Calloway http://nccoos.org/Members/cbc office: 3313 Venable Hall phone: (919) 599-3530 mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599 From davea at davea.name Wed Apr 17 23:24:59 2013 From: davea at davea.name (Dave Angel) Date: Wed, 17 Apr 2013 17:24:59 -0400 Subject: [Tutor] Sys.argv read parameters In-Reply-To: References: <516F0390.6010903@davea.name> <516F0DEC.9020205@davea.name> Message-ID: <516F132B.4090203@davea.name> On 04/17/2013 05:15 PM, Danny Yoo wrote: > Yup! Sorry about my tone for its stridency. But I just got concerned > that the original poster seemed content about turning the chain of if > statements into a table definition. To my mind, they're very closely > related, data and control. I'm trying to push the OP to realizing > that if they are doing this, they are still enumerating all the > decisions. Maybe it's not in the form of a chain of if statements, > but it's still reflected in the structure of the table. > > (It's the same reason I get concerned when I see students not > recognize the similarities between if statements and polymorphism: > it's all about transmogrifying control flow and data structures.) > > Let me say that if there's non-uniformity among the choices, then the > table lookup approach (a dispatch table) is probably the right tool. > If there's uniformity, then a computational approach should be > considered. > > But look at the original question. It was about having many variables. And a dict is the way to take many variables out of the namespace and replacing them with one. And it was unlikely to my mind that the final intent was to produce such a simplistic message for each letter. -- DaveA From dyoo at hashcollision.org Wed Apr 17 23:45:16 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Wed, 17 Apr 2013 15:45:16 -0600 Subject: [Tutor] Fwd: Sys.argv read parameters In-Reply-To: References: Message-ID: Forwarding message to Python-tutor mailing list. I did not realize that your reply didn't show up for the rest of Python tutor. Please use Reply to All in the future. ---------- Forwarded message ---------- From: Danilo Chilene Date: Wed, Apr 17, 2013 at 2:17 PM Subject: Re: [Tutor] Sys.argv read parameters To: Danny Yoo Hello Danny, The part that is changing is just the sys.argv[1] The vars will have always the same content. What I don't want is to have like 255 'ifs' if I have 255 vars. On Wed, Apr 17, 2013 at 5:03 PM, Danny Yoo wrote: > > What's the part that's "changing"? What's the part that stays the same? > > I would recommend thinking of this in terms of a function. > > Can you write a function that consumes a letter l and returns the > string "This is ..." where "..." is the uppercased l? > > As an example of a simple function on strings: > > ########################## > ## double: string -> string > def double(x): > return x + x > > ## For example, a blast from the past: > print "The Noid says: " + double("pizza") > ########################## > > > There are functions in Python standard library that know how to do > things to strings. See: > > http://docs.python.org/2/library/stdtypes.html#string-methods From breamoreboy at yahoo.co.uk Thu Apr 18 00:27:29 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 17 Apr 2013 23:27:29 +0100 Subject: [Tutor] Sys.argv read parameters In-Reply-To: References: Message-ID: On 17/04/2013 20:27, Danilo Chilene wrote: > Dear Python Tutor, > > I have the code below(file.py): > > import sys > > a = 'This is A' > b = 'This is B' > c = 'This is C' > > for i in sys.argv[1]: > if sys.argv[1] == 'a': > print a > if sys.argv[1] == 'b': > print b > if sys.argv[1] == 'c': > print c > > I run python file.py a and returns the var a, so far so good. > > The problem is that i have a bunch of vars(like a to z), how I can > handle this in a pythonic way? > > Best Regards, > > Danilo > Further to earlier answers you might like to look at these modules for parsing items from sys.argv. http://docs.python.org/3/library/argparse.html#module-argparse http://docs.python.org/3/library/getopt.html#module-getopt http://docs.python.org/3/library/optparse.html#module-optparse is available in Python 2.x but is deprecated as of Python 3.2. There is also an awesome third party module here https://github.com/docopt/docopt -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From davea at davea.name Thu Apr 18 01:21:30 2013 From: davea at davea.name (Dave Angel) Date: Wed, 17 Apr 2013 19:21:30 -0400 Subject: [Tutor] Fwd: Sys.argv read parameters In-Reply-To: References: Message-ID: <516F2E7A.2020503@davea.name> > ---------- Forwarded message ---------- > From: Danilo Chilene > Date: Wed, Apr 17, 2013 at 2:17 PM > Subject: Re: [Tutor] Sys.argv read parameters > To: Danny Yoo > > > Hello Danny, > > The part that is changing is just the sys.argv[1] > The vars will have always the same content. > > What I don't want is to have like 255 'ifs' if I have 255 vars. > Please don't top post. Put your response AFTER the part you're quoting. > > On Wed, Apr 17, 2013 at 5:03 PM, Danny Yoo wrote: >> >> What's the part that's "changing"? What's the part that stays the same? >> Are all the strings going to be identical except for the one letter? If so, then read the better responses here, like those from Danny Yoo So far, you haven't provided any useful input as to what you're really looking for. -- DaveA From alan.gauld at btinternet.com Thu Apr 18 02:12:08 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 18 Apr 2013 01:12:08 +0100 Subject: [Tutor] Sys.argv read parameters In-Reply-To: References: Message-ID: On 17/04/13 20:27, Danilo Chilene wrote: > import sys > > a = 'This is A' > b = 'This is B' > c = 'This is C' > > for i in sys.argv[1]: > if sys.argv[1] == 'a': > print a > if sys.argv[1] == 'b': > print b > if sys.argv[1] == 'c': > print c > > I run python file.py a and returns the var a, so far so good. > > The problem is that i have a bunch of vars(like a to z), how I can > handle this in a pythonic way? Use a dictionary. myVars = { 'a':'This is A', 'b':'This is B', 'c':'This is C', # as many more as needed } print myVars.get(sys.argv[1], 'No variable found') Is that what you mean? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From chuck.mayers at gmail.com Thu Apr 18 02:16:38 2013 From: chuck.mayers at gmail.com (Chuck Mayers) Date: Wed, 17 Apr 2013 19:16:38 -0500 Subject: [Tutor] new to threading, Queues Message-ID: Hi! I was having a bit of nostalgia today, and thought I'd try to write a simple, old school BBS. I found the 'paramiko' library, and I've got something I can SSH into that would have impressed my 1990's self. I found some example code of the "threading" library, and I've managed to use it to take multiple incoming connections at once. I've never done any multithreaded programming, and everything I've ever read is essentially "don't do it! It's really hard to get right!" Everything I've read today says to use the Queue library I can't seem to wrap my head around it, though. I've not seen any example code that looks like what I'm trying to do. Some examples of things I'd like to do: Have one thread open a file (that all threads will want to read/write to) and update it Have one thread broadcast to all other threads a "chat message" The only way I can think of, with the Queue library, would be the following (I know this has to be the "wrong way" to do this): 1. create an object MultiTask which will have methods to handle thread sensitive things like "update a file", etc 2. create one instance of it (we'll call it mtask) and add it to the queue 3. each thread, when it needs to, does queue.get() to get that instance 4. the thread then calls whatever it needs to, say mtask.update_users_file() 5. then, call queue.put(mtask) to put it back on the queue so, there is only ever 1 object in the queue. I assume when another thread tries to get() it, they block until the other threads are done with it. Will this work? Is there a better way to do this? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Thu Apr 18 03:07:55 2013 From: davea at davea.name (Dave Angel) Date: Wed, 17 Apr 2013 21:07:55 -0400 Subject: [Tutor] Sys.argv read parameters In-Reply-To: References: Message-ID: <516F476B.3020406@davea.name> On 04/17/2013 08:12 PM, Alan Gauld wrote: > On 17/04/13 20:27, Danilo Chilene wrote: > >> import sys >> >> a = 'This is A' >> b = 'This is B' >> c = 'This is C' >> >> for i in sys.argv[1]: >> if sys.argv[1] == 'a': >> print a >> if sys.argv[1] == 'b': >> print b >> if sys.argv[1] == 'c': >> print c >> >> I run python file.py a and returns the var a, so far so good. >> >> The problem is that i have a bunch of vars(like a to z), how I can >> handle this in a pythonic way? > > Use a dictionary. > > myVars = { > 'a':'This is A', > 'b':'This is B', > 'c':'This is C', > # as many more as needed > } > > print myVars.get(sys.argv[1], 'No variable found') > > Is that what you mean? > What's the point? The OP is not clarifying the "spec." I posited a dict and supplied code several messages ago (about 4.5 hours), and he said "worked like a charm." But since then he has given cryptic responses to others, and still not answered a few of the questions I asked then. -- DaveA From wolfrage8765 at gmail.com Thu Apr 18 11:28:42 2013 From: wolfrage8765 at gmail.com (Jordan) Date: Thu, 18 Apr 2013 11:28:42 +0200 Subject: [Tutor] new to threading, Queues In-Reply-To: References: Message-ID: <516FBCCA.1040608@gmail.com> On 04/18/2013 02:16 AM, Chuck Mayers wrote: > Hi! I was having a bit of nostalgia today, and thought I'd try to > write a simple, old school BBS. I found the 'paramiko' library, and > I've got something I can SSH into that would have impressed my 1990's > self. > > I found some example code of the "threading" library, and I've managed > to use it to take multiple incoming connections at once. > > I've never done any multithreaded programming, and everything I've > ever read is essentially "don't do it! It's really hard to get right!" True it canbe difficult, but how are you supposed to learn if you don't try it, and sometimes you need to do two things at once or at least nearly. > > Everything I've read today says to use the Queue library > I can't seem to wrap my head around it, though. I've not seen any > example code that looks like what I'm trying to do. > > Some examples of things I'd like to do: > Have one thread open a file (that all threads will want to read/write > to) and update it > Have one thread broadcast to all other threads a "chat message" > > > The only way I can think of, with the Queue library, would be the > following (I know this has to be the "wrong way" to do this): > > 1. create an object MultiTask which will have methods to handle thread > sensitive things like "update a file", etc > 2. create one instance of it (we'll call it mtask) and add it to the queue > 3. each thread, when it needs to, does queue.get() to get that instance > 4. the thread then calls whatever it needs to, say > mtask.update_users_file() > 5. then, call queue.put(mtask) to put it back on the queue > Yeah, I am not sure that will work but maybe. What I did was to model the Mediator Pattern kind of, it then controls the queue and assigns the workload to multiple threads creating new threads as needed. Not that my way is the best just how I did it. http://sourcemaking.com/design_patterns/mediator My Mediator does not follow the design pattern very well, it is called dispatcher, and it uses workers to get the Jobs done, jobs are actually defined too. Additionally the code is not as good as it could be, because I have not used in for many months, but the tests should work. It was made with Python3 in mind. It is attached. > so, there is only ever 1 object in the queue. I assume when another > thread tries to get() it, they block until the other threads are done > with it. > > Will this work? Is there a better way to do this? > > Thanks! > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: Workers.py Type: text/x-python Size: 6523 bytes Desc: not available URL: From wayne at waynewerner.com Thu Apr 18 14:42:15 2013 From: wayne at waynewerner.com (Wayne Werner) Date: Thu, 18 Apr 2013 07:42:15 -0500 (CDT) Subject: [Tutor] design question (Django?) In-Reply-To: References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1365937572.26277.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: On Sun, 14 Apr 2013, Don Jennings wrote: > > On Apr 14, 2013, at 7:06 AM, Albert-Jan Roskam wrote: > >> >> >> > Subject: Re: [Tutor] design question (Django?) >>> >>> On 13/04/13 09:48, Albert-Jan Roskam wrote: >>> >>>> I think I have to make a diagram of this. This stuff is quite hard >>> >> Would it also be a good idea to simultaneously make a paper-and-pencil drawing of the UI? > > Absolutely! Test it with three users. See Jakob Nielsen's brief take on the matter: > A recommendation - check out Balsamiq Mockups for UI design. If you plan to make this project open source they'll provide you a free license (with a bit of documentation, e.g. link to project on Bitbucket/Github/etc with a OSI approved license). They also have a free web demo that's pretty powerful and just nags every 5 (or 15?) minutes. http://www.balsamiq.com/ I've not found a better tool for doing quick and rough UI mockps! HTH, Wayne From bicofino at gmail.com Thu Apr 18 15:21:18 2013 From: bicofino at gmail.com (Danilo Chilene) Date: Thu, 18 Apr 2013 10:21:18 -0300 Subject: [Tutor] Fwd: Sys.argv read parameters In-Reply-To: <516F2E7A.2020503@davea.name> References: <516F2E7A.2020503@davea.name> Message-ID: On Wed, Apr 17, 2013 at 8:21 PM, Dave Angel wrote: > > ---------- Forwarded message ---------- >> From: Danilo Chilene >> Date: Wed, Apr 17, 2013 at 2:17 PM >> Subject: Re: [Tutor] Sys.argv read parameters >> To: Danny Yoo >> >> >> Hello Danny, >> >> The part that is changing is just the sys.argv[1] >> The vars will have always the same content. >> >> What I don't want is to have like 255 'ifs' if I have 255 vars. >> >> > Please don't top post. Put your response AFTER the part you're quoting. > > > >> On Wed, Apr 17, 2013 at 5:03 PM, Danny Yoo >> wrote: >> >>> >>> What's the part that's "changing"? What's the part that stays the same? >>> >>> > Are all the strings going to be identical except for the one letter? If > so, then read the better responses here, like those from Danny Yoo > > The strings will always be the same except for the letter. > So far, you haven't provided any useful input as to what you're really > looking for. > > > > > -- > DaveA > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Thu Apr 18 15:31:56 2013 From: davea at davea.name (Dave Angel) Date: Thu, 18 Apr 2013 09:31:56 -0400 Subject: [Tutor] Fwd: Sys.argv read parameters In-Reply-To: References: <516F2E7A.2020503@davea.name> Message-ID: <516FF5CC.3060904@davea.name> On 04/18/2013 09:21 AM, Danilo Chilene wrote: > On Wed, Apr 17, 2013 at 8:21 PM, Dave Angel wrote: > >> >> ---------- Forwarded message ---------- >>> From: Danilo Chilene >>> Date: Wed, Apr 17, 2013 at 2:17 PM >>> Subject: Re: [Tutor] Sys.argv read parameters >>> To: Danny Yoo >>> >>> >>> Hello Danny, >>> >>> The part that is changing is just the sys.argv[1] >>> The vars will have always the same content. >>> >>> What I don't want is to have like 255 'ifs' if I have 255 vars. >>> >>> >> Please don't top post. Put your response AFTER the part you're quoting. >> >> >> >>> On Wed, Apr 17, 2013 at 5:03 PM, Danny Yoo >>> wrote: >>> >>>> >>>> What's the part that's "changing"? What's the part that stays the same? >>>> >>>> >> Are all the strings going to be identical except for the one letter? If >> so, then read the better responses here, like those from Danny Yoo >> >> > The strings will always be the same except for the letter. > Then in that case, why do you use any if-test? Just substitute the letter, as Danny pointed out. You never said whether you accept more than one letter from the command line. I've been assuming you do, since you used a loop. for letter in sys.argv[1].upper(): print "This is uppercase of one of the input letters, %s" % letter -- DaveA From wprins at gmail.com Thu Apr 18 16:16:34 2013 From: wprins at gmail.com (Walter Prins) Date: Thu, 18 Apr 2013 15:16:34 +0100 Subject: [Tutor] design question (Django?) In-Reply-To: References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1365937572.26277.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: Hi, On Sun, 14 Apr 2013, Don Jennings wrote: > > >> On Apr 14, 2013, at 7:06 AM, Albert-Jan Roskam wrote: >> >> >>> >>> > Subject: Re: [Tutor] design question (Django?) >>> >>>> >>>> On 13/04/13 09:48, Albert-Jan Roskam wrote: >>>> >>>> I think I have to make a diagram of this. This stuff is quite hard >>>>> >>>> >>>> Would it also be a good idea to simultaneously make a paper-and-pencil >>> drawing of the UI? >>> >> >> Absolutely! Test it with three users. See Jakob Nielsen's brief take on >> the matter: >> >> You might check out Pencil, which I quite like. http://pencil.evolus.vn/ Walter -------------- next part -------------- An HTML attachment was scrubbed... URL: From cybervigilante at gmail.com Thu Apr 18 18:45:51 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Thu, 18 Apr 2013 09:45:51 -0700 Subject: [Tutor] path directory backslash ending Message-ID: Minor question. I was adding the Py Script directory to the Win 7 Path, and noticed that Python33 ends with a backslash but many directories do not. Is there a difference? Should I use backslash or not preferentially, or doesn't it matter at all? It does seem odd that there's no convention for this. -- Jim Mooney Today is the day that would have been tomorrow if yesterday was today From davea at davea.name Thu Apr 18 18:59:41 2013 From: davea at davea.name (Dave Angel) Date: Thu, 18 Apr 2013 12:59:41 -0400 Subject: [Tutor] path directory backslash ending In-Reply-To: References: Message-ID: <5170267D.9030600@davea.name> On 04/18/2013 12:45 PM, Jim Mooney wrote: > Minor question. I was adding the Py Script directory to the Win 7 > Path, and noticed that Python33 ends with a backslash but many > directories do not. Is there a difference? Should I use backslash or > not preferentially, or doesn't it matter at all? It does seem odd that > there's no convention for this. > There's no Python convention. There may be a Windows convention, but I doubt it. As far as I could tell when I was stuck in Windows, the only time a trailing backslash was significant was when there was nothing in front of it but a colon and/or a drive letter. In Linux, applications are free to make their own use of the trailing backslash, and I know that rsync does something different with it present than without. But in the PATH, it doesn't matter. -- DaveA From bicofino at gmail.com Thu Apr 18 19:14:08 2013 From: bicofino at gmail.com (Danilo Chilene) Date: Thu, 18 Apr 2013 14:14:08 -0300 Subject: [Tutor] Fwd: Sys.argv read parameters In-Reply-To: <516FF5CC.3060904@davea.name> References: <516F2E7A.2020503@davea.name> <516FF5CC.3060904@davea.name> Message-ID: On Thu, Apr 18, 2013 at 10:31 AM, Dave Angel wrote: > On 04/18/2013 09:21 AM, Danilo Chilene wrote: > >> On Wed, Apr 17, 2013 at 8:21 PM, Dave Angel wrote: >> >> >>> ---------- Forwarded message ---------- >>> >>>> From: Danilo Chilene >>>> Date: Wed, Apr 17, 2013 at 2:17 PM >>>> Subject: Re: [Tutor] Sys.argv read parameters >>>> To: Danny Yoo >>>> >>>> >>>> Hello Danny, >>>> >>>> The part that is changing is just the sys.argv[1] >>>> The vars will have always the same content. >>>> >>>> What I don't want is to have like 255 'ifs' if I have 255 vars. >>>> >>>> >>>> Please don't top post. Put your response AFTER the part you're quoting. >>> >>> >>> >>> On Wed, Apr 17, 2013 at 5:03 PM, Danny Yoo >>>> wrote: >>>> >>>> >>>>> What's the part that's "changing"? What's the part that stays the >>>>> same? >>>>> >>>>> >>>>> Are all the strings going to be identical except for the one letter? >>> If >>> so, then read the better responses here, like those from Danny Yoo >>> >>> >>> The strings will always be the same except for the letter. >> >> > Then in that case, why do you use any if-test? Just substitute the > letter, as Danny pointed out. > > You never said whether you accept more than one letter from the command > line. I've been assuming you do, since you used a loop. > > for letter in sys.argv[1].upper(): > print "This is uppercase of one of the input letters, %s" % letter Below is the final code: import requests, json, sys r = requests.get('http://napmongo01.cvc.com.br:28017/_status') j = r.json() arg = sys.argv[1] commands = { 'uptime' : "j['serverStatus']['uptime']" 'globalLock_lockTime' : "j['serverStatus']['globalLock']['lockTime']" 'globalLock_currentQueue_total' = "j['serverStatus']['globalLock']['currentQueue']['total']" 'globalLock_currentQueue_readers' = "j['serverStatus']['globalLock']['currentQueue']['readers']" 'globalLock_currentQueue_writers' = "j['serverStatus']['globalLock']['currentQueue']['writers']" 'mem_bits' = "j['serverStatus']['mem']['bits']" 'mem_resident' = "j['serverStatus']['mem']['resident']" 'mem_virtual' = "j['serverStatus']['mem']['virtual']" 'connections_current' = "j['serverStatus']['connections']['current']" 'connections_available' = "j['serverStatus']['connections']['available']" 'extra_info_heap_usage' = round(("j['serverStatus']['extra_info']['heap_usage_bytes'])/(1024*124), 2)" 'extra_info_page_faults' = "j['serverStatus']['extra_info']['page_faults']" 'indexCounters_btree_accesses' = "j['serverStatus']['indexCounters']['btree']['accesses']" 'indexCounters_btree_hits' = "j['serverStatus']['indexCounters']['btree']['hits']" 'indexCounters_btree_misses' = "j['serverStatus']['indexCounters']['btree']['misses']" 'indexCounters_btree_resets' = "j['serverStatus']['indexCounters']['btree']['resets']" 'indexCounters_btree_missRatio' = "j['serverStatus']['indexCounters']['btree']['missRatio']" 'backgroundFlushing_flushes' = "j['serverStatus']['backgroundFlushing']['flushes']" 'backgroundFlushing_total_ms' = "j['serverStatus']['backgroundFlushing']['total_ms']" 'backgroundFlushing_average_ms' = "j['serverStatus']['backgroundFlushing']['average_ms']" 'backgroundFlushing_last_ms' = "j['serverStatus']['backgroundFlushing']['last_ms']" 'cursors_totalOpen' = "j['serverStatus']['cursors']['totalOpen']" 'cursors_clientCursors_size' = "j['serverStatus']['cursors']['clientCursors_size']" 'cursors_timedOut' = "j['serverStatus']['cursors']['timedOut']" 'opcounters_insert' = "j['serverStatus']['opcounters']['insert']" 'opcounters_query' = "j['serverStatus']['opcounters']['query']" 'opcounters_update' = "j['serverStatus']['opcounters']['update']" 'opcounters_delete' = "j['serverStatus']['opcounters']['delete']" 'opcounters_getmore' = "j['serverStatus']['opcounters']['getmore']" 'opcounters_command' = ['server_status']['opcounters']['command']"" 'asserts_regular' = "j['serverStatus']['asserts']['regular']" 'asserts_warning' = "j['serverStatus']['asserts']['warning']" 'asserts_msg' = "j['serverStatus']['asserts']['msg']" 'asserts_user' = "j['serverStatus']['asserts']['user']" 'asserts_rollovers' = "j['serverStatus']['asserts']['rollovers']" 'network_inbound_traffic_mb' = ("j['serverStatus']['network']['bytesIn'])/(1024*1024)" 'network_outbound_traffic_mb' = ("j['serverStatus']['network']['bytesOut'])/(1024*1024)" 'network_requests' = "j['serverStatus']['network']['numRequests']" 'write_backs_queued' = "j['serverStatus']['writeBacksQueued']" 'logging_commits' = "j['serverStatus']['dur']['commits']" 'logging_journal_writes_mb' = "j['serverStatus']['dur']['journaledMB']" 'logging_datafile_writes_mb' = "j['serverStatus']['dur']['writeToDataFilesMB']" 'logging_commits_in_writelock' = "j['serverStatus']['dur']['commitsInWriteLock']" 'logging_early_commits' = "j['serverStatus']['dur']['earlyCommits']" 'logging_log_buffer_prep_time_ms' = "j['serverStatus']['dur']['timeMs']['prepLogBuffer']" 'logging_journal_write_time_ms' = "j['serverStatus']['dur']['timeMs']['writeToJournal']" 'logging_datafile_write_time_ms' = "j['serverStatus']['dur']['timeMs']['writeToDataFiles']" } for command in commands: if arg in commands: print commands[command] else: print 'Invalid command' Below the output: (danilochilene at notebico - ~/lixo @14:06:56) 2: python mongo-test.py uptime j['serverStatus']['uptime'] (danilochilene at notebico - ~/lixo @14:07:00) 2: python -i mongo-test.py uptime j['serverStatus']['uptime'] >>> j['serverStatus']['uptime'] 27806 >>> My only issue now is commands[command] (as the example above) have the same output as j['serverStatus']['uptime']. Thanks for the help so far! -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Thu Apr 18 19:34:09 2013 From: davea at davea.name (Dave Angel) Date: Thu, 18 Apr 2013 13:34:09 -0400 Subject: [Tutor] Fwd: Sys.argv read parameters In-Reply-To: References: <516F2E7A.2020503@davea.name> <516FF5CC.3060904@davea.name> Message-ID: <51702E91.60807@davea.name> On 04/18/2013 01:14 PM, Danilo Chilene wrote: > > The following code has little to do with anything that happened before. So you should start a new thread for this new project. > > Below is the final code: > > import requests, json, sys > > r = requests.get('http://napmongo01.cvc.com.br:28017/_status') > j = r.json() > > arg = sys.argv[1] > > commands = { > 'uptime' : "j['serverStatus']['uptime']" > 'globalLock_lockTime' : > "j['serverStatus']['globalLock']['lockTime']" A literal string that happens to have j in it has nothing at all to do with the j that you got from json. > 'globalLock_currentQueue_total' = > "j['serverStatus']['globalLock']['currentQueue']['total']" > 'globalLock_currentQueue_readers' = > "j['serverStatus']['globalLock']['currentQueue']['readers']" > 'globalLock_currentQueue_writers' = > "j['serverStatus']['globalLock']['currentQueue']['writers']" > 'mem_bits' = "j['serverStatus']['mem']['bits']" > 'mem_resident' = "j['serverStatus']['mem']['resident']" > 'mem_virtual' = "j['serverStatus']['mem']['virtual']" > 'connections_current' = > "j['serverStatus']['connections']['current']" > 'connections_available' = > "j['serverStatus']['connections']['available']" > 'extra_info_heap_usage' = > round(("j['serverStatus']['extra_info']['heap_usage_bytes'])/(1024*124), 2)" > 'extra_info_page_faults' = > "j['serverStatus']['extra_info']['page_faults']" > 'indexCounters_btree_accesses' = > "j['serverStatus']['indexCounters']['btree']['accesses']" > 'indexCounters_btree_hits' = > "j['serverStatus']['indexCounters']['btree']['hits']" > 'indexCounters_btree_misses' = > "j['serverStatus']['indexCounters']['btree']['misses']" > 'indexCounters_btree_resets' = > "j['serverStatus']['indexCounters']['btree']['resets']" > 'indexCounters_btree_missRatio' = > "j['serverStatus']['indexCounters']['btree']['missRatio']" > 'backgroundFlushing_flushes' = > "j['serverStatus']['backgroundFlushing']['flushes']" > 'backgroundFlushing_total_ms' = > "j['serverStatus']['backgroundFlushing']['total_ms']" > 'backgroundFlushing_average_ms' = > "j['serverStatus']['backgroundFlushing']['average_ms']" > 'backgroundFlushing_last_ms' = > "j['serverStatus']['backgroundFlushing']['last_ms']" > 'cursors_totalOpen' = > "j['serverStatus']['cursors']['totalOpen']" > 'cursors_clientCursors_size' = > "j['serverStatus']['cursors']['clientCursors_size']" > 'cursors_timedOut' = > "j['serverStatus']['cursors']['timedOut']" > 'opcounters_insert' = > "j['serverStatus']['opcounters']['insert']" > 'opcounters_query' = > "j['serverStatus']['opcounters']['query']" > 'opcounters_update' = > "j['serverStatus']['opcounters']['update']" > 'opcounters_delete' = > "j['serverStatus']['opcounters']['delete']" > 'opcounters_getmore' = > "j['serverStatus']['opcounters']['getmore']" > 'opcounters_command' = > ['server_status']['opcounters']['command']"" > 'asserts_regular' = > "j['serverStatus']['asserts']['regular']" > 'asserts_warning' = > "j['serverStatus']['asserts']['warning']" > 'asserts_msg' = "j['serverStatus']['asserts']['msg']" > 'asserts_user' = "j['serverStatus']['asserts']['user']" > 'asserts_rollovers' = > "j['serverStatus']['asserts']['rollovers']" > 'network_inbound_traffic_mb' = > ("j['serverStatus']['network']['bytesIn'])/(1024*1024)" > 'network_outbound_traffic_mb' = > ("j['serverStatus']['network']['bytesOut'])/(1024*1024)" > 'network_requests' = > "j['serverStatus']['network']['numRequests']" > 'write_backs_queued' = > "j['serverStatus']['writeBacksQueued']" > 'logging_commits' = "j['serverStatus']['dur']['commits']" > 'logging_journal_writes_mb' = > "j['serverStatus']['dur']['journaledMB']" > 'logging_datafile_writes_mb' = > "j['serverStatus']['dur']['writeToDataFilesMB']" > 'logging_commits_in_writelock' = > "j['serverStatus']['dur']['commitsInWriteLock']" > 'logging_early_commits' = > "j['serverStatus']['dur']['earlyCommits']" > 'logging_log_buffer_prep_time_ms' = > "j['serverStatus']['dur']['timeMs']['prepLogBuffer']" > 'logging_journal_write_time_ms' = > "j['serverStatus']['dur']['timeMs']['writeToJournal']" > 'logging_datafile_write_time_ms' = > "j['serverStatus']['dur']['timeMs']['writeToDataFiles']" > } > > for command in commands: > if arg in commands: > print commands[command] > else: > print 'Invalid command' The above loop makes no sense at all for several reasons. I'd be amazed if it happens to produce the output you show below. Please use copy/paste to show us the code you're actually running. > > > Below the output: > (danilochilene at notebico - ~/lixo @14:06:56) > 2: python mongo-test.py uptime > j['serverStatus']['uptime'] > > (danilochilene at notebico - ~/lixo @14:07:00) > 2: python -i mongo-test.py uptime > j['serverStatus']['uptime'] >>>> j['serverStatus']['uptime'] > 27806 >>>> > > My only issue now is commands[command] (as the example above) have the same > output as j['serverStatus']['uptime']. > commands[command] is produced from a literal string. If you want it to be an int 27806, you could type that literal instead. commands = { 'uptime' : 27806 Or perhaps you could do commands = { 'uptime' : j['serverStatus']['uptime'] if the values in j are already set up before you initialize the dict commands. > Thanks for the help so far! > -- DaveA From alan.gauld at btinternet.com Thu Apr 18 19:52:01 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 18 Apr 2013 18:52:01 +0100 Subject: [Tutor] Fwd: Sys.argv read parameters In-Reply-To: References: <516F2E7A.2020503@davea.name> <516FF5CC.3060904@davea.name> Message-ID: On 18/04/13 18:14, Danilo Chilene wrote: > for command in commands: > if arg in commands: > print commands[command] > else: > print 'Invalid command' I don't understand what you are doing here? Its almost a random selection mechanism? You print the command for every item in commands if arg is in commands and Invalid Command for every command if its not? Whatever its trying to do its massively inefficient. I thought you'd have wanted something like for command in commands: if arg == command: print commands[command] else: print 'Invalid command' Which is roughly equivalent to: print commands.get(arg, 'Invalid command') but much less efficient! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bicofino at gmail.com Thu Apr 18 20:23:18 2013 From: bicofino at gmail.com (Danilo Chilene) Date: Thu, 18 Apr 2013 15:23:18 -0300 Subject: [Tutor] Fwd: Sys.argv read parameters In-Reply-To: References: <516F2E7A.2020503@davea.name> <516FF5CC.3060904@davea.name> Message-ID: On Thu, Apr 18, 2013 at 2:52 PM, Alan Gauld wrote: > On 18/04/13 18:14, Danilo Chilene wrote: > > for command in commands: >> if arg in commands: >> print commands[command] >> else: >> print 'Invalid command' >> > > I don't understand what you are doing here? Its almost a random selection > mechanism? You print the command for every item in commands if arg is in > commands and Invalid Command for every command if its not? > Whatever its trying to do its massively inefficient. > > I thought you'd have wanted something like > > for command in commands: > if arg == command: > > print commands[command] > else: > print 'Invalid command' > > Which is roughly equivalent to: > > print commands.get(arg, 'Invalid command') > > but much less efficient! Hi Alan, Yes, I was doing it the wrong way. > > > > -- > 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 dyoo at hashcollision.org Thu Apr 18 21:10:02 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 18 Apr 2013 13:10:02 -0600 Subject: [Tutor] Fwd: Sys.argv read parameters In-Reply-To: References: <516F2E7A.2020503@davea.name> <516FF5CC.3060904@davea.name> Message-ID: Ok, good. This is _much_ more realistic code, and demonstrates why seeing context is important. My suggestion to do it computationally is totally invalid here. :P There's a lot of variation here, due to the access paths through the JSON that you're walking. You're essentially defining a very lightweight domain-specific language, technically. The semantics of the commands appear to be: walk the JSON of a certain path. A dispatch table here is _very_ appropriate. The values in your dispatch table, however, should not be literal code that you want to evaluate: rather, they should just hold an inert path. The act of using the dispatch table should take a path and then apply it to the JSON in question. (I am trying _very_ hard not to say the word "eval" here, because it's just dangerous in this context.) Here's what the interpretation part of your language might looks like: ##################################################################### def p(*elts): """Construct a representation of a path. (We'll cheat a little by using a list of strings.)""" return elts commands = { 'uptime' : p('serverStatus', 'uptime'), 'globalLock_lockTime' : p('serverStatus', 'globalLock', 'lockTime') ## Fill me in with more elements. } def lookup(data, cmdName): path = commands[cmdName] for p in path: data = data[p] return data ## For example, let's mock up some sample data and see how this works. sampleData = {'serverStatus' : {'uptime': 3, 'cpu load' : 1.11, 'globalLock' : { 'lockName' : 'sample lock name', 'lockTime' : 42 }}} print lookup(sampleData, 'uptime') print lookup(sampleData, 'globalLock_lockTime') ##################################################################### You should be able to see how to extend this to your realistic example: just add more entries in your command. Note that I'm using a function p() to construct the path: that's just for my own convenience: you might be able to just strip it out and inline the paths directly into the table. (But having p there enables maintenance: we might need to extend the system to do more than path lookup later on, in which case redefining p makes it easy to change the representation of paths by modifying a single place.) From dyoo at hashcollision.org Thu Apr 18 21:16:25 2013 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 18 Apr 2013 13:16:25 -0600 Subject: [Tutor] Fwd: Sys.argv read parameters In-Reply-To: References: <516F2E7A.2020503@davea.name> <516FF5CC.3060904@davea.name> Message-ID: Followup: compare the previous interpreter code with this revision: https://gist.github.com/dyoo/5415464 and you'll see how it becomes easier now to add new command types into the system. From eryksun at gmail.com Thu Apr 18 21:22:19 2013 From: eryksun at gmail.com (eryksun) Date: Thu, 18 Apr 2013 15:22:19 -0400 Subject: [Tutor] path directory backslash ending In-Reply-To: References: Message-ID: On Thu, Apr 18, 2013 at 12:45 PM, Jim Mooney wrote: > Minor question. I was adding the Py Script directory to the Win 7 > Path, and noticed that Python33 ends with a backslash but many > directories do not. Is there a difference? Should I use backslash or > not preferentially, or doesn't it matter at all? It does seem odd that > there's no convention for this. The trailing backslash shouldn't directly matter in the PATH variable, not as far how the system splits the string on ';' and searches the directories. It may be an issue with escaping if "%PATH%" is passed as a quoted argument. We can test this to be sure. Create test.py: import sys print(sys.argv[1:]) Now try an example. First without quotes: C:\>test.py C:\Program Files;C:\Python33\ ['C:\\Program', 'Files;C:\\Python33\\'] Obviously the C runtime (not the shell, as would be the case on a POSIX system) needs a little help parsing the argument string. We'll add some quotes around it: C:\>test.py "C:\Program Files;C:\Python33\" ['C:\\Program Files;C:\\Python33"'] Ack! The trailing backslash was treated as an escape character, so we end up with a trailing double quote. It works fine if you remove the trailing backslash: C:\>test.py "C:\Program Files;C:\Python33" ['C:\\Program Files;C:\\Python33'] OK, so IMHO don't use a trailing backslash. It's also a convention to not use a trailing backslash in directories set as environment variables. For example: C:\>echo %ProgramFiles% C:\Program Files This makes it look more natural as part of another path: C:\>dir /b "%ProgramFiles%\Microsoft SDKs\Windows\v7.0A" bin Include Lib Note that the shell replaces %ProgramFiles% literally with C:\Program Files, so quotes are required. From cybervigilante at gmail.com Fri Apr 19 02:51:01 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Thu, 18 Apr 2013 17:51:01 -0700 Subject: [Tutor] path directory backslash ending In-Reply-To: References: Message-ID: Well, under the principle of least harm, it appears that since the trailing backslash causes no harm if omitted, but sometimes does if allowed, I removed them all. But that's in win 7. Is it okay to always omit them in Linux? Python33 is itself installed with a trailing backslash, so I figured this was a Linux habit. An entirely different question as long as I'm here. I have a local wamp server with mysql and phpadmin for php so I can test web pages locally. What's the equivalent for Python? Jim From sayanchatterjee at gmail.com Fri Apr 19 13:44:17 2013 From: sayanchatterjee at gmail.com (Sayan Chatterjee) Date: Fri, 19 Apr 2013 17:14:17 +0530 Subject: [Tutor] Python Script: Downloading Youtube videos by search result Message-ID: Dear All, I want to download some music from youtube.There are already marvellous python scripts like youtube-dl which downloads videos and playlists from numerous sites,but what I want to do is to download videos from youtube with a search string. The user will give a search string, and the script will download first 20(say) videos from the youtube.The script will use youtube-dl on the backend and avconv tool for video to MP3 conversion etc. How should I proceed to make such a script. I am a newbie in Python but I am sure with your guidance I can pick it up quite fast. :) Cheers, 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 eryksun at gmail.com Fri Apr 19 15:53:48 2013 From: eryksun at gmail.com (eryksun) Date: Fri, 19 Apr 2013 09:53:48 -0400 Subject: [Tutor] path directory backslash ending In-Reply-To: References: Message-ID: On Thu, Apr 18, 2013 at 8:51 PM, Jim Mooney wrote: > > But that's in win 7. Is it okay to always omit them in Linux? Python33 > is itself installed with a trailing backslash, so I figured this was a > Linux habit. POSIX/Linux uses a forward slash instead of a backslash (py: os.sep), and the delimiter in PATH is a colon instead of a semicolon (py: os.pathsep). There's no convention I know of to use trailing slashes. You might also consider using the PEP 405 "venv" module: http://www.python.org/dev/peps/pep-0405 When you "activate" the environment it prepends the "Scripts" (or "bin") directory to PATH. The option "--symlinks" requires an elevated security token on Windows, but just to create the virtual environment. If you'd rather copy over the required DLLs, there's a "--upgrade" option for when you upgrade to Python 3.4, etc. > An entirely different question as long as I'm here. I have a local > wamp server with mysql and phpadmin for php so I can test web pages > locally. What's the equivalent for Python? Here's a sampling of links. Hopefully a web developer will provide a more detailed answer. mod_wsgi http://code.google.com/p/modwsgi http://code.google.com/p/modwsgi/wiki/InstallationOnWindows The wiki has several integration guides for popular frameworks. mod_wsgi Windows binaries: http://www.lfd.uci.edu/~gohlke/pythonlibs/#mod_wsgi Python Web Server Gateway Interface v1.0.1 http://www.python.org/dev/peps/pep-3333 From fahraynk at gmail.com Fri Apr 19 16:49:38 2013 From: fahraynk at gmail.com (Frank Schiro) Date: Fri, 19 Apr 2013 10:49:38 -0400 Subject: [Tutor] hard time importing a module Message-ID: hi I have a question about modules ... Im trying to use a 3rd party module called pywinatuo. It said I had to install 2 other modules. 1 was called sendkeys.py, the other was ctypes. Ctypes was included in the python library I had, but sendkeys was not. After I found SendKeys, I put it in a directory I found in sys.path, and then type import SendKeys. I got an error because sendkeys was trying to import from another file called _sendkeys. After searching I found _sendkeys, but it is .c I know that you can somehow extend python with c from reading this article : http://docs.python.org/2/extending/extending.html But... how do I get the interpreter to recognize the _sendkeys.c file when sendkeys.py trys to import it ? I get errors right away since c uses * to comment so python doesnt recognize it and errors on all of the comments from _sendkeys.c Basically how do I correctly import this module that doesnt have a setup.py ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From oscar.j.benjamin at gmail.com Fri Apr 19 17:12:36 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Fri, 19 Apr 2013 16:12:36 +0100 Subject: [Tutor] hard time importing a module In-Reply-To: References: Message-ID: On 19 April 2013 15:49, Frank Schiro wrote: > hi I have a question about modules ... > > Im trying to use a 3rd party module called pywinatuo. It said I had to > install 2 other modules. 1 was called sendkeys.py, the other was ctypes. > Ctypes was included in the python library I had, but sendkeys was not. > > After I found SendKeys, I put it in a directory I found in sys.path, and > then type import SendKeys. I got an error because sendkeys was trying to > import from another file called _sendkeys. After searching I found > _sendkeys, but it is .c Did these files also come with a file called setup.py? Normally, a Python module is not installed by manually copying the files to the appropriate places but by running 'python setup.py install' in the terminal. This will compile any C code and copy files to the appropriate places. Note that you will need to have separately installed a C compiler to be able to compile C code. > > I know that you can somehow extend python with c from reading this article : > http://docs.python.org/2/extending/extending.html Try reading this one instead: http://docs.python.org/2/install/index.html > > But... how do I get the interpreter to recognize the _sendkeys.c file when > sendkeys.py trys to import it ? I get errors right away since c uses * to > comment so python doesnt recognize it and errors on all of the comments from > _sendkeys.c Yeah, that won't work. C code needs to be compiled by a C compiler, not Python. > > Basically how do I correctly import this module that doesnt have a setup.py > ? Oh okay, no setup.py. Where did you get this from? What does it have? Is there a Makefile or something? Oscar From eryksun at gmail.com Fri Apr 19 17:39:57 2013 From: eryksun at gmail.com (eryksun) Date: Fri, 19 Apr 2013 11:39:57 -0400 Subject: [Tutor] hard time importing a module In-Reply-To: References: Message-ID: On Fri, Apr 19, 2013 at 11:12 AM, Oscar Benjamin wrote: > Did these files also come with a file called setup.py? > > Normally, a Python module is not installed by manually copying the > files to the appropriate places but by running 'python setup.py > install' in the terminal. This will compile any C code and copy files > to the appropriate places. Note that you will need to have separately > installed a C compiler to be able to compile C code. I think this is the SendKeys module in question: http://web.archive.org/web/20121002234104/http://www.rutherfurd.net/python/sendkeys You can get the zipped source from archive.org above, along with binaries for 2.1-2.6. The source has a setup.py, but as Oscar said already you'll need a C compiler. You can use Visual Studio 2008 to compile it for 2.6/2.7. There are direct links for VS 2008 Express edition (free as in beer) in this SO answer: http://stackoverflow.com/a/14979612/205580 Or use MinGW-w64 if you prefer since the source isn't C++: http://mingw-w64.sourceforge.net/ There's also a binary installer for 2.7 here, courtesy of Christoph Gohlke: http://www.lfd.uci.edu/~gohlke/pythonlibs/#sendkeys From mail at timgolden.me.uk Fri Apr 19 17:52:39 2013 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 19 Apr 2013 16:52:39 +0100 Subject: [Tutor] hard time importing a module In-Reply-To: References: Message-ID: <51716847.9070305@timgolden.me.uk> On 19/04/2013 16:39, eryksun wrote: > On Fri, Apr 19, 2013 at 11:12 AM, Oscar Benjamin > wrote: >> Did these files also come with a file called setup.py? >> >> Normally, a Python module is not installed by manually copying the >> files to the appropriate places but by running 'python setup.py >> install' in the terminal. This will compile any C code and copy files >> to the appropriate places. Note that you will need to have separately >> installed a C compiler to be able to compile C code. > > I think this is the SendKeys module in question: > > http://web.archive.org/web/20121002234104/http://www.rutherfurd.net/python/sendkeys > > You can get the zipped source from archive.org above, along with > binaries for 2.1-2.6. The source has a setup.py, but as Oscar said > already you'll need a C compiler. You can use Visual Studio 2008 to > compile it for 2.6/2.7. There are direct links for VS 2008 Express > edition (free as in beer) in this SO answer: As usual, the excellent Christoph Gohlke has provided binaries for a range of targets: http://www.lfd.uci.edu/~gohlke/pythonlibs/ TJG From breamoreboy at yahoo.co.uk Fri Apr 19 18:00:55 2013 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 19 Apr 2013 17:00:55 +0100 Subject: [Tutor] hard time importing a module In-Reply-To: References: Message-ID: On 19/04/2013 16:39, eryksun wrote: > On Fri, Apr 19, 2013 at 11:12 AM, Oscar Benjamin > wrote: >> Did these files also come with a file called setup.py? >> >> Normally, a Python module is not installed by manually copying the >> files to the appropriate places but by running 'python setup.py >> install' in the terminal. This will compile any C code and copy files >> to the appropriate places. Note that you will need to have separately >> installed a C compiler to be able to compile C code. > > I think this is the SendKeys module in question: > > http://web.archive.org/web/20121002234104/http://www.rutherfurd.net/python/sendkeys > > You can get the zipped source from archive.org above, along with > binaries for 2.1-2.6. The source has a setup.py, but as Oscar said > already you'll need a C compiler. You can use Visual Studio 2008 to > compile it for 2.6/2.7. There are direct links for VS 2008 Express > edition (free as in beer) in this SO answer: > > http://stackoverflow.com/a/14979612/205580 > > Or use MinGW-w64 if you prefer since the source isn't C++: > > http://mingw-w64.sourceforge.net/ > > There's also a binary installer for 2.7 here, courtesy of Christoph Gohlke: > > http://www.lfd.uci.edu/~gohlke/pythonlibs/#sendkeys > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > At least two variants on sendkeys are here on stackoverflow if none of the above work out http://tinyurl.com/cuwdhjk -- If you're using GoogleCrap? please read this http://wiki.python.org/moin/GoogleGroupsPython. Mark Lawrence From eryksun at gmail.com Fri Apr 19 18:12:09 2013 From: eryksun at gmail.com (eryksun) Date: Fri, 19 Apr 2013 12:12:09 -0400 Subject: [Tutor] hard time importing a module In-Reply-To: <51716847.9070305@timgolden.me.uk> References: <51716847.9070305@timgolden.me.uk> Message-ID: On Fri, Apr 19, 2013 at 11:52 AM, Tim Golden wrote: > As usual, the excellent Christoph Gohlke has provided binaries for a > range of targets: > > http://www.lfd.uci.edu/~gohlke/pythonlibs/ Maybe you missed the link at the end of my link fest: http://www.lfd.uci.edu/~gohlke/pythonlibs/#sendkeys From mail at timgolden.me.uk Fri Apr 19 18:13:47 2013 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 19 Apr 2013 17:13:47 +0100 Subject: [Tutor] hard time importing a module In-Reply-To: References: <51716847.9070305@timgolden.me.uk> Message-ID: <51716D3B.8070203@timgolden.me.uk> On 19/04/2013 17:12, eryksun wrote: > On Fri, Apr 19, 2013 at 11:52 AM, Tim Golden wrote: >> As usual, the excellent Christoph Gohlke has provided binaries for a >> range of targets: >> >> http://www.lfd.uci.edu/~gohlke/pythonlibs/ > > Maybe you missed the link at the end of my link fest: > > http://www.lfd.uci.edu/~gohlke/pythonlibs/#sendkeys > Whoops. Quite right. Still, better twice than not at all ;) TJG From ramit.prasad at jpmorgan.com Fri Apr 19 18:11:09 2013 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 19 Apr 2013 16:11:09 +0000 Subject: [Tutor] Hello, and a newbie question In-Reply-To: References: <1366156656384.bcbb86a8@Nodemailer> Message-ID: <5B80DD153D7D744689F57F4FB69AF47418335202@SCACMX008.exchad.jpmchase.net> eryksun wrote: > On Tue, Apr 16, 2013 at 7:57 PM, Virgilio Rodriguez Jr > wrote: > > Can someone please do me the favor and remove me from this god forsaken > > email list I am sorry I signed up all it has done is taken over my phone and > > rings all night long with emails I am not interested in any more because it > > is just too many darn emails. I keep trying to log in and nothing it will > > not let me unsubscribe and it is BS already. > > You can get a password reminder here: > http://mail.python.org/mailman/options/tutor > > If you're sure that you have the correct password and still can't > unsubscribe, then email the administrator, tutor-owner at python.org. > Alan Gauld is active in this thread, BTW, in case you happen to have > read the admin page where it says "Tutor list run by wescpy at > gmail.com, alan.gauld at btinternet.com". Or switch to digest mode which will email once a day with all the messages in it. Be glad you are not subscribed to the main Python mailing list as it is far more active than the tutor list. ;) ~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 chetansaip at gmail.com Fri Apr 19 22:56:50 2013 From: chetansaip at gmail.com (Chetan Sai) Date: Fri, 19 Apr 2013 13:56:50 -0700 Subject: [Tutor] How to find reverse pair words in a list of Words that has to be accessed through a URL Message-ID: *Here is my question:* * * *"Two words are a ?reverse pair? if each is the reverse of the other. Write a program that finds all the reverse pairs in the word list. The word list can be downloaded athttp://www.puzzlers.org/pub/wordlists/pocket.txt"* -------------- next part -------------- An HTML attachment was scrubbed... URL: From dfjennings at gmail.com Fri Apr 19 23:05:12 2013 From: dfjennings at gmail.com (Don Jennings) Date: Fri, 19 Apr 2013 17:05:12 -0400 Subject: [Tutor] How to find reverse pair words in a list of Words that has to be accessed through a URL In-Reply-To: References: Message-ID: <6D403979-81A8-48F8-9B6D-E449B3ADD083@gmail.com> On Apr 19, 2013, at 4:56 PM, Chetan Sai wrote: > Here is my question: > > "Two words are a ?reverse pair? if each is the reverse of the other. Write a program that finds all the reverse pairs in the word list. The word list can be downloaded athttp://www.puzzlers.org/pub/wordlists/pocket.txt" Really, that's not a question, but we are happy to answer questions :>) Oh, there's your question in the subject line. What have you tried thus far? Have you given any thought to what steps you might have to take to solve this task? Take care, Don From chetansaip at gmail.com Fri Apr 19 23:19:10 2013 From: chetansaip at gmail.com (Chetan Sai) Date: Fri, 19 Apr 2013 14:19:10 -0700 Subject: [Tutor] How to find reverse pair words in a list of Words that has to be accessed through a URL In-Reply-To: <6D403979-81A8-48F8-9B6D-E449B3ADD083@gmail.com> References: <6D403979-81A8-48F8-9B6D-E449B3ADD083@gmail.com> Message-ID: Hi Don I'm a beginner in Python Programming. I'm using python 3. I wrote a program that checks whether given two words are reverse pair or not and outputs TRUE/FALSE. *def reverse_pair(a,b):* * return list(a)==list(reversed(list(b)))* * * * * But how to write a program that finds all the reverse pairs in the given word list, eg: how to find the reverse pair words in a list of 20 words. And that to how to access those list of words form a URL. Because with the above code we can only find out whether the given 2 words are reverse pair or not, that's it. I'm thinking of using the below code which is written for Python 2.7. Code: def reverse_pair(word_list, word): """Checks whether a reversed word appears in word_list. word_list: list of strings word: string """ rev_word = word[::-1] return in_bisect(word_list, rev_word) if __name__ == '__main__': word_list = make_word_list() for word in word_list: if reverse_pair(word_list, word): print word, word[::-1] On Fri, Apr 19, 2013 at 2:05 PM, Don Jennings wrote: > > On Apr 19, 2013, at 4:56 PM, Chetan Sai wrote: > > > Here is my question: > > > > "Two words are a ?reverse pair? if each is the reverse of the other. > Write a program that finds all the reverse pairs in the word list. The word > list can be downloaded athttp://www.puzzlers.org/pub/wordlists/pocket.txt" > > Really, that's not a question, but we are happy to answer questions :>) > Oh, there's your question in the subject line. What have you tried thus > far? Have you given any thought to what steps you might have to take to > solve this task? > > Take care, > Don > > -- Thanks & Regards Sai Chetan Pothula 408-203-3323 On Fri, Apr 19, 2013 at 2:05 PM, Don Jennings wrote: > > On Apr 19, 2013, at 4:56 PM, Chetan Sai wrote: > > > Here is my question: > > > > "Two words are a ?reverse pair? if each is the reverse of the other. > Write a program that finds all the reverse pairs in the word list. The word > list can be downloaded athttp://www.puzzlers.org/pub/wordlists/pocket.txt" > > Really, that's not a question, but we are happy to answer questions :>) > Oh, there's your question in the subject line. What have you tried thus > far? Have you given any thought to what steps you might have to take to > solve this task? > > Take care, > Don > > -- Thanks & Regards Sai Chetan Pothula 408-203-3323 -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Apr 20 00:07:50 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 19 Apr 2013 23:07:50 +0100 Subject: [Tutor] How to find reverse pair words in a list of Words that has to be accessed through a URL In-Reply-To: References: <6D403979-81A8-48F8-9B6D-E449B3ADD083@gmail.com> Message-ID: On 19/04/13 22:19, Chetan Sai wrote: > I'm a beginner in Python Programming. The language isn't really the issue here the issue is the algorithm. So how would you do it manually with a paper and pen? (forget about fetching the list from the URL for now) One possibility is to use sets (Python has a set data type). create a set of words. Now create a set of reversed words. The intersection of those sets is the set of words which also have a reversed pair. print the intersection set. just one way. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From emile at fenx.com Sat Apr 20 00:16:52 2013 From: emile at fenx.com (emile) Date: Fri, 19 Apr 2013 15:16:52 -0700 Subject: [Tutor] How to find reverse pair words in a list of Words that has to be accessed through a URL In-Reply-To: References: <6D403979-81A8-48F8-9B6D-E449B3ADD083@gmail.com> Message-ID: On 04/19/2013 03:07 PM, Alan Gauld wrote: > On 19/04/13 22:19, Chetan Sai wrote: > >> I'm a beginner in Python Programming. > > The language isn't really the issue here the issue is the algorithm. > So how would you do it manually with a paper and pen? (forget about > fetching the list from the URL for now) > > One possibility is to use sets (Python has a set data type). > create a set of words. > Now create a set of reversed words. > The intersection of those sets is the set of words which > also have a reversed pair. > > print the intersection set. The gotcha with this approach is the border case of self paired words that aren't pairs. (pop,wow,mom,etc) I got 94 distinct pairs. Which is a better result than the 124.5 pairs I got the first pass through. Emile From amitsaha.in at gmail.com Sat Apr 20 00:48:43 2013 From: amitsaha.in at gmail.com (Amit Saha) Date: Sat, 20 Apr 2013 08:48:43 +1000 Subject: [Tutor] Python Script: Downloading Youtube videos by search result In-Reply-To: References: Message-ID: On Fri, Apr 19, 2013 at 9:44 PM, Sayan Chatterjee wrote: > Dear All, > > I want to download some music from youtube.There are already marvellous > python scripts like youtube-dl which downloads videos and playlists from > numerous sites,but what I want to do is to download videos from youtube with > a search string. The user will give a search string, and the script will > download first 20(say) videos from the youtube.The script will use > youtube-dl on the backend and avconv tool for video to MP3 conversion etc. > > How should I proceed to make such a script. I am a newbie in Python but I am > sure with your guidance I can pick it up quite fast. :) May be take a look at the YouTube Data API? [1] Hopefully, the Getting Started section will help you [2]. [1] https://developers.google.com/youtube/1.0/developers_guide_python#SearchingVideos [2] https://developers.google.com/youtube/1.0/developers_guide_python#GettingStarted Best, Amit. -- http://amitsaha.github.com/ From alan.gauld at btinternet.com Sat Apr 20 01:57:07 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 20 Apr 2013 00:57:07 +0100 Subject: [Tutor] How to find reverse pair words in a list of Words that has to be accessed through a URL In-Reply-To: References: <6D403979-81A8-48F8-9B6D-E449B3ADD083@gmail.com> Message-ID: On 19/04/13 23:16, emile wrote: > The gotcha with this approach is the border case of self paired words > that aren't pairs. (pop,wow,mom,etc) yeah, but those exceptions are easy to catch as you generate the reversed list: if reversed(word) == word And its a bit of a moot point whether you should perhaps count a palindromic word as a pair of itself... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From steve at pearwood.info Sat Apr 20 02:48:31 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sat, 20 Apr 2013 10:48:31 +1000 Subject: [Tutor] How to find reverse pair words in a list of Words that has to be accessed through a URL In-Reply-To: References: <6D403979-81A8-48F8-9B6D-E449B3ADD083@gmail.com> Message-ID: <5171E5DF.5000007@pearwood.info> On 20/04/13 09:57, Alan Gauld wrote: > On 19/04/13 23:16, emile wrote: > >> The gotcha with this approach is the border case of self paired words >> that aren't pairs. (pop,wow,mom,etc) > > yeah, but those exceptions are easy to catch as you generate the reversed list: > > if reversed(word) == word An easy mistake to make, but reversed() returns an iterator which will only compare equal to itself: py> reversed("abc") You need to convert the reversed object back into a string: py> "".join(reversed("abc")) 'cba' But the best way to reverse a string is with a slice: py> 'abc'[::-1] 'cba' The syntax is a little obscure, but "slicing" takes between 0 and 3 arguments, written inside square brackets [ ] and separated by colons. The full form of a slice is: string[start:end:step] where start defaults to the beginning of the string, end defaults to the end of the string, and step defaults to 1. If step is 1, you can leave it out: string[start:end] otherwise you need to include colons to mark the missing values: string[2::3] says to return a slice of the string, starting at character 2, going to the end, and taking every third character. (Remember that counting starts at 0 in Python, not 1, so character 2 is the *third* character.) py> "python is cool"[2::3] 'tnso' A negative step goes backwards, so a fast and efficient way to reverse a string or other sequence is to use slice it using [::-1]. > And its a bit of a moot point whether you should > perhaps count a palindromic word as a pair of itself... That word you use, I do not think it means what you think it means, to quote the Spaniard. A moot point is a point which is not relevant. If your house has just been flattened by a hurricane, it is a moot point whether or not you left the front door unlocked. I think it is quite relevant whether or not palindromes should count or not. -- Steven From alan.gauld at btinternet.com Sat Apr 20 03:17:22 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 20 Apr 2013 02:17:22 +0100 Subject: [Tutor] How to find reverse pair words in a list of Words that has to be accessed through a URL In-Reply-To: <5171E5DF.5000007@pearwood.info> References: <6D403979-81A8-48F8-9B6D-E449B3ADD083@gmail.com> <5171E5DF.5000007@pearwood.info> Message-ID: On 20/04/13 01:48, Steven D'Aprano wrote: > A moot point is a point which is not relevant. It most certainly is not. It is a point that is open to debate. Specifically it is a point that would be posted on the agenda for the weekly meetings in the local Moot Hall - the town guild/council's meeting place in medieval times. There are several towns in England where Moot Halls still exist and a few still have ceremonial Moot meetings where topics of local interest are occasionally debated. A fine example of a Moot Hall is in Aldeburgh in Suffolk: http://en.wikipedia.org/wiki/Aldeburgh [ And it must never, ever, be spelled a *mute* point - something that bugs me constantly since it infers almost the opposite of the real meaning! ] PS. On the subject of reversed() you are quite right although I wasn't thinking of python at the time I wrote it I was just indicating the algorithmic fix required to filter the palindromes. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From fomcl at yahoo.com Sat Apr 20 11:00:31 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sat, 20 Apr 2013 02:00:31 -0700 (PDT) Subject: [Tutor] design question (Django?) In-Reply-To: References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1365937572.26277.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: <1366448431.52046.YahooMailNeo@web163801.mail.gq1.yahoo.com> On Sun, 14 Apr 2013, Don Jennings wrote: > > >> >> >>>On Apr 14, 2013, at 7:06 AM, Albert-Jan Roskam wrote: >>> >>> >>> >>>> >>>>> Subject: Re: [Tutor] design question (Django?) >>>> >>>> >>>>>On 13/04/13 09:48, Albert-Jan Roskam wrote: >>>>> >>>>> >>>>>I think I have to make a diagram of this. This stuff is quite hard >>>>>> >>>>> >>>>Would it also be a good idea to simultaneously make a paper-and-pencil drawing of the UI? >>>> >>> >>>Absolutely! Test it with three users. See Jakob Nielsen's brief take on the matter: >>> >>> > > >You might check out Pencil, which I quite like.? > > >http://pencil.evolus.vn/ > >Hi Wayne, Walter, > >Thank you! I checked out both Pencil and Balsamiq. Based on the websites, Pencil seems to work better for me. It can export to html, among others so I could use it as a basis for my Django template. Not sure if Balsamiq can do this (I watched the video demo). The following doesn't apply to my case (as it is just a hobby project), but is there a potential risk that a mock up creates the illusion for clients that the entire job (not just a nonfunctional UI) is "almost done"? > >Regards, >Albert-Jan > >ps: sorry about the formatting. Yahoo's rich text formatting won't turn of anymore > From payo2000 at gmail.com Sat Apr 20 11:38:55 2013 From: payo2000 at gmail.com (pa yo) Date: Sat, 20 Apr 2013 11:38:55 +0200 Subject: [Tutor] design question (Django?) In-Reply-To: <1366448431.52046.YahooMailNeo@web163801.mail.gq1.yahoo.com> References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com> <1365937572.26277.YahooMailNeo@web163801.mail.gq1.yahoo.com> <1366448431.52046.YahooMailNeo@web163801.mail.gq1.yahoo.com> Message-ID: It doesn't do everything you want but you might try using the "Create Map" function on Google maps. You can draw lines and mark points in different colours. You cannot count households - though i am not sure how you plan to do that with python; where will the nHouseholds data come from? On Sat, Apr 20, 2013 at 11:00 AM, Albert-Jan Roskam wrote: > > > On Sun, 14 Apr 2013, Don Jennings wrote: > > > > > >> > >> > >>>On Apr 14, 2013, at 7:06 AM, Albert-Jan Roskam wrote: > >>> > >>> > >>> > >>>> > >>>>> Subject: Re: [Tutor] design question (Django?) > >>>> > >>>> > >>>>>On 13/04/13 09:48, Albert-Jan Roskam wrote: > >>>>> > >>>>> > >>>>>I think I have to make a diagram of this. This stuff is quite hard > >>>>>> > >>>>> > >>>>Would it also be a good idea to simultaneously make a paper-and-pencil > drawing of the UI? > >>>> > >>> > >>>Absolutely! Test it with three users. See Jakob Nielsen's brief take on > the matter: > >>> > >>> > > > > > >You might check out Pencil, which I quite like. > > > > > >http://pencil.evolus.vn/ > > > >Hi Wayne, Walter, > > > >Thank you! I checked out both Pencil and Balsamiq. Based on the websites, > Pencil seems to work better for me. It can export to html, among others so > I could use it as a basis for my Django template. Not sure if Balsamiq can > do this (I watched the video demo). The following doesn't apply to my case > (as it is just a hobby project), but is there a potential risk that a mock > up creates the illusion for clients that the entire job (not just a > nonfunctional UI) is "almost done"? > > > >Regards, > >Albert-Jan > > > >ps: sorry about the formatting. Yahoo's rich text formatting won't turn > of anymore > > > _______________________________________________ > 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 cybervigilante at gmail.com Sat Apr 20 20:32:00 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 20 Apr 2013 11:32:00 -0700 Subject: [Tutor] 3to2? Message-ID: I was looking at google pengine for python and it only supports 2.7. I've installed 3 and would rather not go back (I kept doing Print without the parentheses for awhile and it was really annoying ;') So the question comes up. If there is a 2to3 script, which I got working, is there a 3to2 script?. Or does that even makes sense since 3 has features 2 does not, although I read somewhere that many have been backported? -- *Jim Mooney Today is the day that would have been tomorrow if yesterday was today * -------------- next part -------------- An HTML attachment was scrubbed... URL: From eryksun at gmail.com Sat Apr 20 21:50:51 2013 From: eryksun at gmail.com (eryksun) Date: Sat, 20 Apr 2013 15:50:51 -0400 Subject: [Tutor] 3to2? In-Reply-To: References: Message-ID: On Sat, Apr 20, 2013 at 2:32 PM, Jim Mooney wrote: > I was looking at google pengine for python and it only supports 2.7. I've > installed 3 and would rather not go back Do you mean Google App Engine (GAE)? Django 1.5 supports 3.x (via Six), but GAE is at 1.4. I'm not sure if GAE has other dependencies holding it up, but AFAIK Google hasn't even published a release schedule for 3.x support. See issue 909: https://code.google.com/p/googleappengine/issues/detail?id=909 Six: http://pythonhosted.org/six > So the question comes up. If there is a 2to3 script, which I got working, is > there a 3to2 script?. Or does that even makes sense since 3 has features 2 > does not, although I read somewhere that many have been backported? https://bitbucket.org/amentajo/lib3to2 As you've already guessed, 3to2 can't backport all 3.x code. From cybervigilante at gmail.com Sat Apr 20 22:14:50 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 20 Apr 2013 13:14:50 -0700 Subject: [Tutor] 3to2? In-Reply-To: References: Message-ID: On 20 April 2013 12:50, eryksun wrote: > On Sat, Apr 20, 2013 at 2:32 PM, Jim Mooney > wrote: > > I was looking at google pengine for python and it only supports 2.7. I've > > installed 3 and would rather not go back > > Do you mean Google App Engine (GAE)? > -- Yeah, looks like my fingers got tangled. New keyboard. I'm not used to flat buttons. I picked Python to learn since I'm retired and it seemed like the most fun (although I won't turn down a Python contract now and then if I ever learn it well ;'). I tried Ruby and Python and liked the Py indentations so I chose that. But to me, it really is so much more enjoyable to learn it for fun than I've-got-to-learn-this-to-make-money. That doesn't mean I wan to just dabble, though. This is the first language I want to learn formally and in detail, not just to get it over with so I can hack a website. But still, past a certain point, since I was a webmaster, I would of course want to make web-use of it, if only for a nonprofit site, since I've run a few of those. *Jim Mooney Today is the day that would have been tomorrow if yesterday was today * -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Apr 20 23:31:29 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 20 Apr 2013 22:31:29 +0100 Subject: [Tutor] 3to2? In-Reply-To: References: Message-ID: On 20/04/13 19:32, Jim Mooney wrote: > I was looking at google pengine for python and it only supports 2.7. > I've installed 3 and would rather not go back This is why we tend to recommend 2.7 for anyone doing serious work in Python. Any dependency on a 3rd party library is much more likely to succeed if you stick with 2.x. And as for automated tools - its very unusual to provide tools to port backwards, most folks want to go the other way... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From fahraynk at gmail.com Sun Apr 21 00:07:51 2013 From: fahraynk at gmail.com (Frank Schiro) Date: Sat, 20 Apr 2013 18:07:51 -0400 Subject: [Tutor] does anyone know a good module for automation Message-ID: I once had a friend who built a bot to play a strategy game called Red Alert : Tiberian Sun. I guess it would be similar to warcraft 3. Im wondering, does anyone know a good python module that would help me if I wanted to accomplish something similar? All I have found so far while surfing has been for webgames that you can take a screenshot and program with coordinates from the screenshot. Ive just gotten the hang of pywinauto, and now I realized I need to get another program called selenium just to use Internet Explorer properly. So I figure Ill need another module ontop of that to run other programs such as games like sim city and other programs like that... Unless you think pywinauto would work in a game envoirnment ? I think it might but have not tried it because no games on my pc... I just know it didnt work for internet explorer. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Apr 21 02:28:56 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Apr 2013 01:28:56 +0100 Subject: [Tutor] does anyone know a good module for automation In-Reply-To: References: Message-ID: On 20/04/13 23:07, Frank Schiro wrote: > > Unless you think pywinauto would work in a game envoirnment ? I think it > might but have not tried it because no games on my pc... I just know it > didnt work for internet explorer. I don't know pywinauto but the lowest common denominator on Windows is the Win32 API and the Windows messages. You can use either ctypes or pythonwin to access those and/or create your own to simulate button presses and mouse clicks etc. Doing that you can automate anything in windows, but its a non trivial, error prone and frustrating exercise so its better to get a higher level library if you can. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cybervigilante at gmail.com Sun Apr 21 04:10:23 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sat, 20 Apr 2013 19:10:23 -0700 Subject: [Tutor] Time frame for Py 3 Maturity Message-ID: > This is why we tend to recommend 2.7 for anyone doing serious work in > Python. > Understood. I am in no rush, but what do you think it the time frame when Py 3 will be mature? A year from now? Two years? At some point I might want to use it more practically. Or maybe there will be huge inflation, I'll go broke, and have to use it more practically ;') Also, is there a good syllabus for the best way to progress in this language? One can certainly get sidetracked. -- *Jim Mooney Today is the day that would have been tomorrow if yesterday was today * -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Sun Apr 21 06:02:36 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 21 Apr 2013 14:02:36 +1000 Subject: [Tutor] Time frame for Py 3 Maturity In-Reply-To: References: Message-ID: <517364DC.3080209@pearwood.info> On 21/04/13 12:10, Jim Mooney wrote: >> This is why we tend to recommend 2.7 for anyone doing serious work in >> Python. >> > > Understood. I am in no rush, but what do you think it the time frame when > Py 3 will be mature? A year from now? Two years? At some point I might want > to use it more practically. Or maybe there will be huge inflation, I'll go > broke, and have to use it more practically ;') Define "mature". As a language, Python 3 was fully mature by the time Python 3.1 came out. (Python 3.0 was, alas, seriously broken, and slow, and is no longer supported.) Since 3.1, Python has simply become *better*, with more features, better text handling, the decimal module is now nearly as fast as built-in floats, a few rough edges have been cleaned up. I expect 3.4 will be better still. Likewise for the standard library. All of the standard library is fully compliant with Python 3. Naturally. As for the external ecosystem of Python libraries and applications, I think the answer is, "it depends". There are still people relying on Python 1.5 (!), so from the perspective of "when will everyone migrate to the latest version?", the answer is "Never", and even Python 2 is not fully mature. On the other hand, from the perspective of "When will the *majority* of publicly-available libraries and packages support Python 3, then the answer is "Right now". The Python 3 Wall of Shame turned mostly green some time ago, and is now known as the Python 3 Wall of Superpowers: https://python3wos.appspot.com/ Based on the number of downloads, almost three quarters of the Top 50 Python packages support Python 3: http://py3ksupport.appspot.com/ On the third hand, if *you personally* require one of the packages which has not been updated, then the answer for you will depend on the specific package you care about. When Python 3 was first floated as a backwards-incompatible version, it was expected that the overall migration would take about ten years. We're now half-way through that decade, and uptake is going according to plan, possibly even a little faster than expected. The early adopters have been using 3 for many years now, the majority of libraries and packages have been updated, the Linux distros are starting to plan for the day when Python 3 is the default, and the majority of trolls have given up complaining about Python 3. > Also, is there a good syllabus for the best way to progress in this > language? One can certainly get sidetracked. I don't quite understand that question. Syllabus? As in a list of topics like this? "You must learn A, then B, then C, then D, ... and now you are an expert!" No. -- Steven From steve at pearwood.info Sun Apr 21 07:32:44 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Sun, 21 Apr 2013 15:32:44 +1000 Subject: [Tutor] 3to2? In-Reply-To: References: Message-ID: <517379FC.3050905@pearwood.info> On 21/04/13 04:32, Jim Mooney wrote: > I was looking at google pengine for python and it only supports 2.7. I've > installed 3 and would rather not go back (I kept doing Print without the > parentheses for awhile and it was really annoying ;') > > So the question comes up. If there is a 2to3 script, which I got working, > is there a 3to2 script?. Or does that even makes sense since 3 has features > 2 does not, although I read somewhere that many have been backported? Is google broken in your part of the world? *wink* https://duckduckgo.com/html/?q=python+3to2 https://www.google.com.au/search?q=python+3to2 http://au.search.yahoo.com/search?p=python+3to2 http://www.bing.com/search?q=python+3to2 Some features of Python 3 have already been back-ported, like the with statement. Some can be optionally enabled, e.g.: from __future__ import division, print_function from future_builtins import * In general, provided you only care about Python 2.7, you can write code which behaves the same way in both 2 and 3. But as you go further back, it becomes harder and harder. By the time you're trying to support 2.4 onwards, it becomes very annoying, and I'm speaking from experience. Although I see that CherryPy actually manages to support everything from 2.3 onwards using a single code base, which truly astonishes me! -- Steven From alan.gauld at btinternet.com Sun Apr 21 09:46:34 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 21 Apr 2013 08:46:34 +0100 Subject: [Tutor] Time frame for Py 3 Maturity In-Reply-To: References: Message-ID: On 21/04/13 03:10, Jim Mooney wrote: >> This is why we tend to recommend 2.7 for anyone doing serious work in >> Python. > > Understood. I am in no rush, but what do you think it the time frame > when Py 3 will be mature? As Steven has already pointed out Python 3 itself is mature. The problem is that many of the key 3rd party libraries have not been ported yet or the ports are not stable. (Many others have been so it depends what you need.) But one of the problems in OpenSource is that the developments are all done by volunteers. There is no central corporate program of work to drive the porting process or set its priority level. It just depends on what each project team sees as its priority - adding features to the existing code, fixing bugs, or porting to Python3 (and thereafter maintaining 2 codebases...). -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From cybervigilante at gmail.com Sun Apr 21 18:24:06 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 21 Apr 2013 09:24:06 -0700 Subject: [Tutor] Py 3 package maturity - good links Message-ID: > On the other hand, from the perspective of "When will the *majority* of > publicly-available libraries and packages support Python 3, then the answer > is "Right now". The Python 3 Wall of Shame turned mostly green some time > ago, > and is now known as the Python 3 Wall of Superpowers: > > https://python3wos.appspot.com/ > > Based on the number of downloads, almost three quarters of the Top 50 > Python > packages support Python 3: > > http://py3ksupport.appspot.com/ > Thanks. Very useful links to save that would have taken time for me to find on my own. As for "syllabus," probably a dream for a dynamic language ;') I was thinking of the time my brother, a Lit grad, gave me a syllabus of literature to read - still working on it forty years later. Jim * * -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at davea.name Sun Apr 21 22:05:42 2013 From: davea at davea.name (Dave Angel) Date: Sun, 21 Apr 2013 16:05:42 -0400 Subject: [Tutor] Py 3 package maturity - good links In-Reply-To: References: Message-ID: <51744696.2090903@davea.name> On 04/21/2013 12:24 PM, Jim Mooney wrote: >> On the other hand, from the perspective of "When will the *majority* of >> publicly-available libraries and packages support Python 3, then the answer >> is "Right now". The Python 3 Wall of Shame turned mostly green some time >> ago, >> and is now known as the Python 3 Wall of Superpowers: >> >> https://python3wos.appspot.com/ >> >> Based on the number of downloads, almost three quarters of the Top 50 >> Python >> packages support Python 3: >> >> http://py3ksupport.appspot.com/ >> > > Thanks. Very useful links to save that would have taken time for me to find > on my own. > > As for "syllabus," probably a dream for a dynamic language ;') I was > thinking of the time my brother, a Lit grad, gave me a syllabus of > literature to read - still working on it forty years later. > > > http://pymotw.com/2/ This could be one way to learn about new (to you) Python modules in a systematic way. On the other hand, if you're looking for a syllabus of studying languages (plural), consider 1) a dynamic language 2) a compile one 3) an assembler 4) other (lisp, Forth, ML, Prolog, ...) Each category is enough different that you have to learn all new habits. But knowing each one is valuable when using the other three types. -- DaveA From dime26 at yahoo.com Mon Apr 22 02:49:09 2013 From: dime26 at yahoo.com (Alex Baker) Date: Sun, 21 Apr 2013 17:49:09 -0700 (PDT) Subject: [Tutor] Testing a method in a class with nosetests In-Reply-To: References: Message-ID: <1366591749.43705.YahooMailNeo@web120205.mail.ne1.yahoo.com> Hello, I've been lurking tutor for the last couple months and have quite enjoyed it! I'm having a problem testing a method using nosetests. The assignment (Learn Python the Hard Way) asks that I write tests for a package using assert_equal and assert_raises. I've?conquered the assert_equals but I'm having issues with assert_raises. I can't figure out how am I supposed to test a method in a class with an __init__. I understand the assert_raises works assert_raises("ERROR", callable, parameters), and the parameters get sent to nosetests, but because of the __init__ I have no parameters to send. # main module code class ParserError(Exception): ? ? pass class Parser(object): ? ? def __init__(self, word_list): ? ? ? ? self.word_list = word_list ? ? def parse_object(self): ? ? ? ? skip(self.word_list, 'stop') ? ? ? ? next = peek(self.word_list) ? ? ? ? if next == 'noun': ? ? ? ? ? ? return match(self.word_list, 'noun') ? ? ? ? if next == 'direction': ? ? ? ? ? ? return match(self.word_list, 'direction') ? ? ? ? else: ? ? ? ? ? ? raise ParserError("Expected a noun or direction next.") # test code from nose.tools import * from ex48 import parser from ex48 import lexicon def _test_words(input): ? ? ? ? words = lexicon.scan(input) ? ? test = parser.Parser(words) ? ? return test def test_parse_object(): ? ? ? ? assert_equal(_test_words("the bear").parse_object(),? ? ? ? ? ? ? ? ? ('noun', 'bear')) ? ? assert_equal(_test_words("the the ?princess").parse_object(), ? ? ? ? ? ? ? ? ('noun', 'princess')) ? ? assert_equal(_test_words("the nortH").parse_object(),? ? ? ? ? ? ? ? ? ('direction', 'north')) ? ? assert_raises("ParserError", _test_words("will fail")) # nosetests output ERROR: tests.parser_tests.test_parse_object ---------------------------------------------------------------------- Traceback (most recent call last): ? File "/Library/Python/2.7/site-packages/nose/case.py", line 197, in runTest ? ? self.test(*self.arg) ? File "/Users/robotsmack/hack/python_projects/ex48/tests/parser_tests.py", line 17, in test_parse_object ? ? assert_raises("ParserError", _test_words("will fail")) ? File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 456, in assertRaises ? File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 113, in __exit__ TypeError: issubclass() arg 2 must be a class or tuple of classes Obviously a bunch a code was snipped, but I don't think its relevant to my question. But just in case, I'm currently fumbling my way through putting up the whole package on GitHub. Thanks in advance! _Alex ________________________________ From: "tutor-request at python.org" To: tutor at python.org Sent: Sunday, April 21, 2013 4:00 AM Subject: Tutor Digest, Vol 110, Issue 86 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. Time frame for Py 3 Maturity (Jim Mooney) ? 2. Re: Time frame for Py 3 Maturity (Steven D'Aprano) ? 3. Re: 3to2? (Steven D'Aprano) ? 4. Re: Time frame for Py 3 Maturity (Alan Gauld) ---------------------------------------------------------------------- Message: 1 Date: Sat, 20 Apr 2013 19:10:23 -0700 From: Jim Mooney To: tutor at python.org Subject: [Tutor] Time frame for Py 3 Maturity Message-ID: ??? Content-Type: text/plain; charset="iso-8859-1" > This is why we tend to recommend 2.7 for anyone doing serious work in > Python. > Understood. I am in no rush, but what do you think it the time frame when Py 3 will be mature? A year from now? Two years? At some point I might want to use it more practically. Or maybe there will be huge inflation, I'll go broke, and have to use it more practically ;') Also, is there a good syllabus for the best way to progress in this language? One can certainly get sidetracked. -- *Jim Mooney Today is the day that would have been tomorrow if yesterday was today * -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 2 Date: Sun, 21 Apr 2013 14:02:36 +1000 From: Steven D'Aprano To: tutor at python.org Subject: Re: [Tutor] Time frame for Py 3 Maturity Message-ID: <517364DC.3080209 at pearwood.info> Content-Type: text/plain; charset=UTF-8; format=flowed On 21/04/13 12:10, Jim Mooney wrote: >> This is why we tend to recommend 2.7 for anyone doing serious work in >> Python. >> > > Understood. I am in no rush, but what do you think it the time frame when > Py 3 will be mature? A year from now? Two years? At some point I might want > to use it more practically. Or maybe there will be huge inflation, I'll go > broke, and have to use it more practically ;') Define "mature". As a language, Python 3 was fully mature by the time Python 3.1 came out. (Python 3.0 was, alas, seriously broken, and slow, and is no longer supported.) Since 3.1, Python has simply become *better*, with more features, better text handling, the decimal module is now nearly as fast as built-in floats, a few rough edges have been cleaned up. I expect 3.4 will be better still. Likewise for the standard library. All of the standard library is fully compliant with Python 3. Naturally. As for the external ecosystem of Python libraries and applications, I think the answer is, "it depends". There are still people relying on Python 1.5 (!), so from the perspective of "when will everyone migrate to the latest version?", the answer is "Never", and even Python 2 is not fully mature. On the other hand, from the perspective of "When will the *majority* of publicly-available libraries and packages support Python 3, then the answer is "Right now". The Python 3 Wall of Shame turned mostly green some time ago, and is now known as the Python 3 Wall of Superpowers: https://python3wos.appspot.com/ Based on the number of downloads, almost three quarters of the Top 50 Python packages support Python 3: http://py3ksupport.appspot.com/ On the third hand, if *you personally* require one of the packages which has not been updated, then the answer for you will depend on the specific package you care about. When Python 3 was first floated as a backwards-incompatible version, it was expected that the overall migration would take about ten years. We're now half-way through that decade, and uptake is going according to plan, possibly even a little faster than expected. The early adopters have been using 3 for many years now, the majority of libraries and packages have been updated, the Linux distros are starting to plan for the day when Python 3 is the default, and the majority of trolls have given up complaining about Python 3. > Also, is there a good syllabus for the best way to progress in this > language? One can certainly get sidetracked. I don't quite understand that question. Syllabus? As in a list of topics like this? "You must learn A, then B, then C, then D, ... and now you are an expert!" No. -- Steven ------------------------------ Message: 3 Date: Sun, 21 Apr 2013 15:32:44 +1000 From: Steven D'Aprano To: tutor at python.org Subject: Re: [Tutor] 3to2? Message-ID: <517379FC.3050905 at pearwood.info> Content-Type: text/plain; charset=UTF-8; format=flowed On 21/04/13 04:32, Jim Mooney wrote: > I was looking at google pengine for python and it only supports 2.7. I've > installed 3 and would rather not go back (I kept doing Print without the > parentheses for awhile and it was really annoying ;') > > So the question comes up. If there is a 2to3 script, which I got working, > is there a 3to2 script?. Or does that even makes sense since 3 has features > 2 does not, although I read somewhere that many have been backported? Is google broken in your part of the world? *wink* https://duckduckgo.com/html/?q=python+3to2 https://www.google.com.au/search?q=python+3to2 http://au.search.yahoo.com/search?p=python+3to2 http://www.bing.com/search?q=python+3to2 Some features of Python 3 have already been back-ported, like the with statement. Some can be optionally enabled, e.g.: from __future__ import division, print_function from future_builtins import * In general, provided you only care about Python 2.7, you can write code which behaves the same way in both 2 and 3. But as you go further back, it becomes harder and harder. By the time you're trying to support 2.4 onwards, it becomes very annoying, and I'm speaking from experience. Although I see that CherryPy actually manages to support everything from 2.3 onwards using a single code base, which truly astonishes me! -- Steven ------------------------------ Message: 4 Date: Sun, 21 Apr 2013 08:46:34 +0100 From: Alan Gauld To: tutor at python.org Subject: Re: [Tutor] Time frame for Py 3 Maturity Message-ID: Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 21/04/13 03:10, Jim Mooney wrote: >>? ? This is why we tend to recommend 2.7 for anyone doing serious work in >>? ? Python. > > Understood. I am in no rush, but what do you think it the time frame > when Py 3 will be mature? As Steven has already pointed out Python 3 itself is mature. The problem is that many of the key 3rd party libraries have not been ported yet or the ports are not stable. (Many others have been so it depends what you need.) But one of the problems in OpenSource is that the developments are all done by volunteers. There is no central corporate program of work to drive the porting process or set its priority level. It just depends on what each project team sees as its priority - adding features to the existing code, fixing bugs, or porting to Python3 (and thereafter maintaining 2 codebases...). -- 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 110, Issue 86 ************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From dime26 at yahoo.com Mon Apr 22 03:09:08 2013 From: dime26 at yahoo.com (Alex Baker) Date: Sun, 21 Apr 2013 18:09:08 -0700 (PDT) Subject: [Tutor] Testing a method in a class with nosetests (Alex Baker) In-Reply-To: References: Message-ID: <1366592948.75062.YahooMailNeo@web120204.mail.ne1.yahoo.com> Dang, forgot to send in plain text! Sorry...? Here is the GitHub link?http://github.com/robotsmack/ex48 ________________________________ From: "tutor-request at python.org" To: tutor at python.org Sent: Sunday, April 21, 2013 6:51 PM Subject: Tutor Digest, Vol 110, Issue 87 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. Py 3 package maturity - good links (Jim Mooney) ? 2. Re: Py 3 package maturity - good links (Dave Angel) ? 3. Testing a method in a class with nosetests (Alex Baker) ---------------------------------------------------------------------- Message: 1 Date: Sun, 21 Apr 2013 09:24:06 -0700 From: Jim Mooney To: tutor at python.org Subject: [Tutor] Py 3 package maturity - good links Message-ID: ??? Content-Type: text/plain; charset="iso-8859-1" > On the other hand, from the perspective of "When will the *majority* of > publicly-available libraries and packages support Python 3, then the answer > is "Right now". The Python 3 Wall of Shame turned mostly green some time > ago, > and is now known as the Python 3 Wall of Superpowers: > > https://python3wos.appspot.com/ > > Based on the number of downloads, almost three quarters of the Top 50 > Python > packages support Python 3: > > http://py3ksupport.appspot.com/ > Thanks. Very useful links to save that would have taken time for me to find on my own. As for "syllabus," probably a dream for a dynamic language ;')? I was thinking of the time my brother, a Lit grad, gave me a syllabus of literature to read - still working on it forty years later. Jim * * -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 2 Date: Sun, 21 Apr 2013 16:05:42 -0400 From: Dave Angel To: tutor at python.org Subject: Re: [Tutor] Py 3 package maturity - good links Message-ID: <51744696.2090903 at davea.name> Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 04/21/2013 12:24 PM, Jim Mooney wrote: >> On the other hand, from the perspective of "When will the *majority* of >> publicly-available libraries and packages support Python 3, then the answer >> is "Right now". The Python 3 Wall of Shame turned mostly green some time >> ago, >> and is now known as the Python 3 Wall of Superpowers: >> >> https://python3wos.appspot.com/ >> >> Based on the number of downloads, almost three quarters of the Top 50 >> Python >> packages support Python 3: >> >> http://py3ksupport.appspot.com/ >> > > Thanks. Very useful links to save that would have taken time for me to find > on my own. > > As for "syllabus," probably a dream for a dynamic language ;')? I was > thinking of the time my brother, a Lit grad, gave me a syllabus of > literature to read - still working on it forty years later. > > > http://pymotw.com/2/ ? ? This could be one way to learn about new (to you) Python modules in a systematic way. On the other hand, if you're looking for a syllabus of studying languages (plural), consider ? ? 1) a dynamic language ? ? 2) a compile one ? ? 3) an assembler ? ? 4) other? ? (lisp, Forth, ML, Prolog, ...) Each category is enough different that you have to learn all new habits. ? But knowing each one is valuable when using the other three types. -- DaveA ------------------------------ Message: 3 Date: Sun, 21 Apr 2013 17:49:09 -0700 (PDT) From: Alex Baker To: "tutor at python.org" Subject: [Tutor] Testing a method in a class with nosetests Message-ID: ??? <1366591749.43705.YahooMailNeo at web120205.mail.ne1.yahoo.com> Content-Type: text/plain; charset="iso-8859-1" Hello, I've been lurking tutor for the last couple months and have quite enjoyed it! I'm having a problem testing a method using nosetests. The assignment (Learn Python the Hard Way) asks that I write tests for a package using assert_equal and assert_raises. I've?conquered the assert_equals but I'm having issues with assert_raises. I can't figure out how am I supposed to test a method in a class with an __init__. I understand the assert_raises works assert_raises("ERROR", callable, parameters), and the parameters get sent to nosetests, but because of the __init__ I have no parameters to send. # main module code class ParserError(Exception): ? ? pass class Parser(object): ? ? def __init__(self, word_list): ? ? ? ? self.word_list = word_list ? ? def parse_object(self): ? ? ? ? skip(self.word_list, 'stop') ? ? ? ? next = peek(self.word_list) ? ? ? ? if next == 'noun': ? ? ? ? ? ? return match(self.word_list, 'noun') ? ? ? ? if next == 'direction': ? ? ? ? ? ? return match(self.word_list, 'direction') ? ? ? ? else: ? ? ? ? ? ? raise ParserError("Expected a noun or direction next.") # test code from nose.tools import * from ex48 import parser from ex48 import lexicon def _test_words(input): ? ? ? ? words = lexicon.scan(input) ? ? test = parser.Parser(words) ? ? return test def test_parse_object(): ? ? ? ? assert_equal(_test_words("the bear").parse_object(),? ? ? ? ? ? ? ? ? ('noun', 'bear')) ? ? assert_equal(_test_words("the the ?princess").parse_object(), ? ? ? ? ? ? ? ? ('noun', 'princess')) ? ? assert_equal(_test_words("the nortH").parse_object(),? ? ? ? ? ? ? ? ? ('direction', 'north')) ? ? assert_raises("ParserError", _test_words("will fail")) # nosetests output ERROR: tests.parser_tests.test_parse_object ---------------------------------------------------------------------- Traceback (most recent call last): ? File "/Library/Python/2.7/site-packages/nose/case.py", line 197, in runTest ? ? self.test(*self.arg) ? File "/Users/robotsmack/hack/python_projects/ex48/tests/parser_tests.py", line 17, in test_parse_object ? ? assert_raises("ParserError", _test_words("will fail")) ? File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 456, in assertRaises ? File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 113, in __exit__ TypeError: issubclass() arg 2 must be a class or tuple of classes Obviously a bunch a code was snipped, but I don't think its relevant to my question. But just in case, I'm currently fumbling my way through putting up the whole package on GitHub. Thanks in advance! _Alex ________________________________ From: "tutor-request at python.org" To: tutor at python.org Sent: Sunday, April 21, 2013 4:00 AM Subject: Tutor Digest, Vol 110, Issue 86 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. Time frame for Py 3 Maturity (Jim Mooney) ?? 2. Re: Time frame for Py 3 Maturity (Steven D'Aprano) ?? 3. Re: 3to2? (Steven D'Aprano) ?? 4. Re: Time frame for Py 3 Maturity (Alan Gauld) ---------------------------------------------------------------------- Message: 1 Date: Sat, 20 Apr 2013 19:10:23 -0700 From: Jim Mooney To: tutor at python.org Subject: [Tutor] Time frame for Py 3 Maturity Message-ID: ??? Content-Type: text/plain; charset="iso-8859-1" > This is why we tend to recommend 2.7 for anyone doing serious work in > Python. > Understood. I am in no rush, but what do you think it the time frame when Py 3 will be mature? A year from now? Two years? At some point I might want to use it more practically. Or maybe there will be huge inflation, I'll go broke, and have to use it more practically ;') Also, is there a good syllabus for the best way to progress in this language? One can certainly get sidetracked. -- *Jim Mooney Today is the day that would have been tomorrow if yesterday was today * -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Message: 2 Date: Sun, 21 Apr 2013 14:02:36 +1000 From: Steven D'Aprano To: tutor at python.org Subject: Re: [Tutor] Time frame for Py 3 Maturity Message-ID: <517364DC.3080209 at pearwood.info> Content-Type: text/plain; charset=UTF-8; format=flowed On 21/04/13 12:10, Jim Mooney wrote: >> This is why we tend to recommend 2.7 for anyone doing serious work in >> Python. >> > > Understood. I am in no rush, but what do you think it the time frame when > Py 3 will be mature? A year from now? Two years? At some point I might want > to use it more practically. Or maybe there will be huge inflation, I'll go > broke, and have to use it more practically ;') Define "mature". As a language, Python 3 was fully mature by the time Python 3.1 came out. (Python 3.0 was, alas, seriously broken, and slow, and is no longer supported.) Since 3.1, Python has simply become *better*, with more features, better text handling, the decimal module is now nearly as fast as built-in floats, a few rough edges have been cleaned up. I expect 3.4 will be better still. Likewise for the standard library. All of the standard library is fully compliant with Python 3. Naturally. As for the external ecosystem of Python libraries and applications, I think the answer is, "it depends". There are still people relying on Python 1.5 (!), so from the perspective of "when will everyone migrate to the latest version?", the answer is "Never", and even Python 2 is not fully mature. On the other hand, from the perspective of "When will the *majority* of publicly-available libraries and packages support Python 3, then the answer is "Right now". The Python 3 Wall of Shame turned mostly green some time ago, and is now known as the Python 3 Wall of Superpowers: https://python3wos.appspot.com/ Based on the number of downloads, almost three quarters of the Top 50 Python packages support Python 3: http://py3ksupport.appspot.com/ On the third hand, if *you personally* require one of the packages which has not been updated, then the answer for you will depend on the specific package you care about. When Python 3 was first floated as a backwards-incompatible version, it was expected that the overall migration would take about ten years. We're now half-way through that decade, and uptake is going according to plan, possibly even a little faster than expected. The early adopters have been using 3 for many years now, the majority of libraries and packages have been updated, the Linux distros are starting to plan for the day when Python 3 is the default, and the majority of trolls have given up complaining about Python 3. > Also, is there a good syllabus for the best way to progress in this > language? One can certainly get sidetracked. I don't quite understand that question. Syllabus? As in a list of topics like this? "You must learn A, then B, then C, then D, ... and now you are an expert!" No. -- Steven ------------------------------ Message: 3 Date: Sun, 21 Apr 2013 15:32:44 +1000 From: Steven D'Aprano To: tutor at python.org Subject: Re: [Tutor] 3to2? Message-ID: <517379FC.3050905 at pearwood.info> Content-Type: text/plain; charset=UTF-8; format=flowed On 21/04/13 04:32, Jim Mooney wrote: > I was looking at google pengine for python and it only supports 2.7. I've > installed 3 and would rather not go back (I kept doing Print without the > parentheses for awhile and it was really annoying ;') > > So the question comes up. If there is a 2to3 script, which I got working, > is there a 3to2 script?. Or does that even makes sense since 3 has features > 2 does not, although I read somewhere that many have been backported? Is google broken in your part of the world? *wink* https://duckduckgo.com/html/?q=python+3to2 https://www.google.com.au/search?q=python+3to2 http://au.search.yahoo.com/search?p=python+3to2 http://www.bing.com/search?q=python+3to2 Some features of Python 3 have already been back-ported, like the with statement. Some can be optionally enabled, e.g.: from __future__ import division, print_function from future_builtins import * In general, provided you only care about Python 2.7, you can write code which behaves the same way in both 2 and 3. But as you go further back, it becomes harder and harder. By the time you're trying to support 2.4 onwards, it becomes very annoying, and I'm speaking from experience. Although I see that CherryPy actually manages to support everything from 2.3 onwards using a single code base, which truly astonishes me! -- Steven ------------------------------ Message: 4 Date: Sun, 21 Apr 2013 08:46:34 +0100 From: Alan Gauld To: tutor at python.org Subject: Re: [Tutor] Time frame for Py 3 Maturity Message-ID: Content-Type: text/plain; charset=ISO-8859-1; format=flowed On 21/04/13 03:10, Jim Mooney wrote: >>? ?? This is why we tend to recommend 2.7 for anyone doing serious work in >>? ?? Python. > > Understood. I am in no rush, but what do you think it the time frame > when Py 3 will be mature? As Steven has already pointed out Python 3 itself is mature. The problem is that many of the key 3rd party libraries have not been ported yet or the ports are not stable. (Many others have been so it depends what you need.) But one of the problems in OpenSource is that the developments are all done by volunteers. There is no central corporate program of work to drive the porting process or set its priority level. It just depends on what each project team sees as its priority - adding features to the existing code, fixing bugs, or porting to Python3 (and thereafter maintaining 2 codebases...). -- 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 110, Issue 86 ************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: ------------------------------ Subject: Digest Footer _______________________________________________ Tutor maillist? -? Tutor at python.org http://mail.python.org/mailman/listinfo/tutor ------------------------------ End of Tutor Digest, Vol 110, Issue 87 ************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Apr 22 03:33:33 2013 From: steve at pearwood.info (Steven D'Aprano) Date: Mon, 22 Apr 2013 11:33:33 +1000 Subject: [Tutor] Testing a method in a class with nosetests In-Reply-To: <1366591749.43705.YahooMailNeo@web120205.mail.ne1.yahoo.com> References: <1366591749.43705.YahooMailNeo@web120205.mail.ne1.yahoo.com> Message-ID: <5174936D.5020300@pearwood.info> On 22/04/13 10:49, Alex Baker wrote: > Hello, > I've been lurking tutor for the last couple months and have quite enjoyed it! Welcome, and congratulations on your first post! Unfortunately I have to start with a complaint :-( but it's NOT because you failed to post plain text, since you actually did. When starting a new thread, please create a new, blank email, don't reply to an existing email. Especially not when that email is a digest containing four complete emails completely unrelated to your post! The end result is that at the bottom of your post is a copy of a complete digest, nearly 200 lines worth of unrelated, irrelevant stuff. (And we're lucky it was only 200 lines, during a busy week, digests could potentially be thousands of lines!) And then you compounded it by replying to the first email, and so ended up with those 200 lines quoted TWICE. > I'm having a problem testing a method using nosetests. The assignment (Learn Python the Hard Way) asks that I write tests for a package using assert_equal and assert_raises. I've conquered the assert_equals but I'm having issues with assert_raises. I can't figure out how am I supposed to test a method in a class with an __init__. I understand the assert_raises works assert_raises("ERROR", callable, parameters), and the parameters get sent to nosetests, but because of the __init__ I have no parameters to send. Unfortunately, I'm not familiar with nose, and so I'm guessing, but I would say replace this call: assert_raises("ParserError", _test_words("will fail")) with this: assert_raises("ParserError", _test_words, "will fail") or possibly this: assert_raises("ParserError", _test_words, ["will fail"]) I expect that the first version fails because the call to _test_words() function raises an exception before nose gets to handle it. This is why assert_raises takes a function argument, followed by its argument. -- Steven From cybervigilante at gmail.com Mon Apr 22 03:35:00 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 21 Apr 2013 18:35:00 -0700 Subject: [Tutor] is there an explicit eof to test in Py 3? Message-ID: I'm reading a book that suggests finding EOF when the readLine == "" But wouldn't that end erroneously on blank lines, that really contain '\n', in which case more lines might follow? What 'empties' are considered equal in Python? I'm coming from javascript which has a cluster of rules for that. Yes, I know the easy way is a for loop, which automatically breaks on eof, but at times I want to use a while loop and break out of it explicitly on eof. But I can't seem to find an explicit eof marker in python. Is there one? -- Jim Mooney Today is the day that would have been tomorrow if yesterday was today From cybervigilante at gmail.com Mon Apr 22 04:50:00 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 21 Apr 2013 19:50:00 -0700 Subject: [Tutor] multiple versions of python on windows? Message-ID: My plan for starting on Py 3 may need some adjustment. I doiwnloaded an irc client that needs Py 2.6 and I think Plone wants 2.7. Is it possible to install multiple versions of python on the same machine or will windows choke? -- Jim Mooney Today is the day that would have been tomorrow if yesterday was today From davea at davea.name Mon Apr 22 06:32:12 2013 From: davea at davea.name (Dave Angel) Date: Mon, 22 Apr 2013 00:32:12 -0400 Subject: [Tutor] is there an explicit eof to test in Py 3? In-Reply-To: References: Message-ID: <5174BD4C.5050502@davea.name> On 04/21/2013 09:35 PM, Jim Mooney wrote: > I'm reading a book that suggests finding EOF when the readLine == "" > > But wouldn't that end erroneously on blank lines, that really contain > '\n', in which case more lines might follow? What 'empties' are > considered equal in Python? I'm coming from javascript which has a > cluster of rules for that. > > Yes, I know the easy way is a for loop, which automatically breaks on > eof, but at times I want to use a while loop and break out of it > explicitly on eof. But I can't seem to find an explicit eof marker in > python. Is there one? > A little experimenting could have told you the answer. readline() returns a newline character for a blank line, and an empty string for end of file. -- DaveA From eryksun at gmail.com Mon Apr 22 07:25:46 2013 From: eryksun at gmail.com (eryksun) Date: Mon, 22 Apr 2013 01:25:46 -0400 Subject: [Tutor] is there an explicit eof to test in Py 3? In-Reply-To: References: Message-ID: On Sun, Apr 21, 2013 at 9:35 PM, Jim Mooney wrote: > I'm reading a book that suggests finding EOF when the readLine == "" > > But wouldn't that end erroneously on blank lines, that really contain > '\n', in which case more lines might follow? What 'empties' are > considered equal in Python? I'm coming from javascript which has a > cluster of rules for that. The newline (os.linesep) isn't stripped, though depending on the "newline" option for open() it may be translated. You shouldn't be testing equality. You know that reading from a file returns either bytes or a string, so just rely on the boolean value. Any type that implements __len_ (collections.abc.Sized) has an implicit boolean value: http://docs.python.org/3/reference/datamodel.html#object.__bool__ For example: while True: line = file.readline() if not line: break process(line) From eryksun at gmail.com Mon Apr 22 07:46:01 2013 From: eryksun at gmail.com (eryksun) Date: Mon, 22 Apr 2013 01:46:01 -0400 Subject: [Tutor] multiple versions of python on windows? In-Reply-To: References: Message-ID: On Sun, Apr 21, 2013 at 10:50 PM, Jim Mooney wrote: > My plan for starting on Py 3 may need some adjustment. I doiwnloaded > an irc client that needs Py 2.6 and I think Plone wants 2.7. > > Is it possible to install multiple versions of python on the same > machine or will windows choke? Installing multiple versions is fine. Just disable the option to update file type associations. When you installed Python 3, .py files were associated with py.exe. This allows you to use a shebang to run a script with a specific interpreter. Or in the console you can run a specific version like this: C:\>py -2.5 -c "import __hello__" &:: -c runs a command Hello world... From cybervigilante at gmail.com Mon Apr 22 08:42:50 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Sun, 21 Apr 2013 23:42:50 -0700 Subject: [Tutor] multiple versions of python on windows? In-Reply-To: <747FF00B-976E-4367-BA7E-4A99998ADE0A@s.dcsdk12.org> References: <747FF00B-976E-4367-BA7E-4A99998ADE0A@s.dcsdk12.org> Message-ID: On 21 April 2013 22:47, School wrote: > You can install multiple versions. The programs use the version they were assigned to, so there shouldn't be any conflict. This brings up the question of installing multiple versions of Wing 101 IDE. I forget the install but even if I can install in a different directory for Py 2.7, Windows awful Registry might trip me up. I've grown to love portables since they bypass Windows Worst Idea, but Wing isn't one of them. If anyone knows, does the paid version of wing allow to switch between multipe installs? I know, this is probably a Wing discuss question, but I'm burned out on joining discussion groups to ask one question, since otherwise Wing is very easy to grasp. -- Jim Mooney Today is the day that would have been tomorrow if yesterday was today From eryksun at gmail.com Mon Apr 22 08:51:58 2013 From: eryksun at gmail.com (eryksun) Date: Mon, 22 Apr 2013 02:51:58 -0400 Subject: [Tutor] Testing a method in a class with nosetests In-Reply-To: <5174936D.5020300@pearwood.info> References: <1366591749.43705.YahooMailNeo@web120205.mail.ne1.yahoo.com> <5174936D.5020300@pearwood.info> Message-ID: On Sun, Apr 21, 2013 at 9:33 PM, Steven D'Aprano wrote: > > it's NOT because you failed to post plain text, since you actually did. Actually it's a multipart message with both plain text and HTML, with the digest quoted in each version. It helps that the HTML is using " " and
that map directly to "=A0" and "=0A". The and
tags are used for color and font styling, rather than layout. From oscar.j.benjamin at gmail.com Mon Apr 22 17:25:09 2013 From: oscar.j.benjamin at gmail.com (Oscar Benjamin) Date: Mon, 22 Apr 2013 16:25:09 +0100 Subject: [Tutor] is there an explicit eof to test in Py 3? In-Reply-To: References: Message-ID: On 22 April 2013 02:35, Jim Mooney wrote: > I'm reading a book that suggests finding EOF when the readLine == "" > > But wouldn't that end erroneously on blank lines, that really contain > '\n', in which case more lines might follow? What 'empties' are > considered equal in Python? I'm coming from javascript which has a > cluster of rules for that. In Python the rules for this are very simple. Strings compare equal if they have exactly the same sequence of characters. Otherwise they compare unequal. > Yes, I know the easy way is a for loop, which automatically breaks on > eof, but at times I want to use a while loop and break out of it > explicitly on eof. But I can't seem to find an explicit eof marker in > python. Is there one? Why do you want to do this? The only reason I can think of is to avoif buffering. Generally, the for loop is not just easier and clearer but also more efficient (because of the buffering). It also allows you to write code that can work just as easily with anything that is iterable such as a list of strings. Oscar From amckenzie4 at gmail.com Mon Apr 22 18:26:56 2013 From: amckenzie4 at gmail.com (Andy McKenzie) Date: Mon, 22 Apr 2013 12:26:56 -0400 Subject: [Tutor] multiple versions of python on windows? In-Reply-To: References: <747FF00B-976E-4367-BA7E-4A99998ADE0A@s.dcsdk12.org> Message-ID: I have no idea on Wing, but I'm using Eclipse with the PyDev plugin, and I'm able to associate projects with either Python 2.7 or 3.2 in Windows. It checks for correct grammar in each, and if I tell it to run as a Python script, it uses the correct executable. So if you're not tied to Wing, you might give Eclipse/PyDev a try. -Andy On Mon, Apr 22, 2013 at 2:42 AM, Jim Mooney wrote: > On 21 April 2013 22:47, School wrote: > > You can install multiple versions. The programs use the version they > were assigned to, so there shouldn't be any conflict. > > This brings up the question of installing multiple versions of Wing > 101 IDE. I forget the install but even if I can install in a different > directory for Py 2.7, Windows awful Registry might trip me up. I've > grown to love portables since they bypass Windows Worst Idea, but Wing > isn't one of them. > > If anyone knows, does the paid version of wing allow to switch between > multipe installs? I know, this is probably a Wing discuss question, > but I'm burned out on joining discussion groups to ask one question, > since otherwise Wing is very easy to grasp. > > -- > Jim Mooney > > Today is the day that would have been tomorrow if yesterday was today > _______________________________________________ > 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 wayne at waynewerner.com Mon Apr 22 18:55:34 2013 From: wayne at waynewerner.com (Wayne Werner) Date: Mon, 22 Apr 2013 11:55:34 -0500 (CDT) Subject: [Tutor] 3to2? In-Reply-To: <517379FC.3050905@pearwood.info> References: <517379FC.3050905@pearwood.info> Message-ID: On Sun, 21 Apr 2013, Steven D'Aprano wrote: > On 21/04/13 04:32, Jim Mooney wrote: >> I was looking at google pengine for python and it only supports 2.7. I've >> installed 3 and would rather not go back (I kept doing Print without the >> parentheses for awhile and it was really annoying ;') >> >> So the question comes up. If there is a 2to3 script, which I got working, >> is there a 3to2 script?. Or does that even makes sense since 3 has features >> 2 does not, although I read somewhere that many have been backported? > > from __future__ import division, print_function > > from future_builtins import * This is the route I recommend, and take myself. Usually I'll do: from __future__ import print_function, division, unicode_literals try: input = raw_input range = xrange except NameError: pass #using python 3 already, whee! which makes you able to write code that mostly looks to Python3. You could also look at how Django does their 2/3 support: https://www.djangoproject.com/weblog/2012/aug/19/experimental-python-3-support/ Looks like they use the `six` library: http://pythonhosted.org/six/ HTH, -W From cybervigilante at gmail.com Tue Apr 23 03:47:41 2013 From: cybervigilante at gmail.com (Jim Mooney) Date: Mon, 22 Apr 2013 18:47:41 -0700 Subject: [Tutor] Why is my list index going out of range Message-ID: Okay, what am I doing wrong here? I'm generating primes from a list and getting "list index out of range," but since the for loops controls the indexes I don't see how that's happening. I thought it was the list append, but I commented that out and put in a print statement, and I still got the line 5 error: primeList = [1] numList = list(range(2,101)) for e in numList: for f in primeList: if numList[e] % primeList[f] != 0: #list index out of range primeList.append(numList[e]) print(primeList) -- Jim Mooney The Real Reason Things Keep Going Wrong: At the beginning of time, God set a Magic Top Spinning... and spinning... and spinning... and spinning... and spinning... and spinning... and spinning... After a few hundred million years God got bored and gave the top a good kick; so it went rebounding away, flinging off planets and stars and dinosaurs, and later, people who wrote about dinosaurs. Then God realized that although Order and Regularity are virtuous, if you want interesting stories, now and then you have to give things a good Kick! This explains a lot. From msirenef at lightbird.net Tue Apr 23 04:02:42 2013 From: msirenef at lightbird.net (Mitya Sirenef) Date: Mon, 22 Apr 2013 22:02:42 -0400 Subject: [Tutor] Why is my list index going out of range In-Reply-To: References: Message-ID: <5175EBC2.8010706@lightbird.net> On 04/22/2013 09:47 PM, Jim Mooney wrote: > Okay, what am I doing wrong here? I'm generating primes from a list > and getting "list index out of range," but since the for loops > controls the indexes I don't see how that's happening. I thought it > was the list append, but I commented that out and put in a print > statement, and I still got the line 5 error: > > primeList = [1] > numList = list(range(2,101)) > for e in numList: > for f in primeList: > if numList[e] % primeList[f] != 0: #list index out of range > primeList.append(numList[e]) > > print(primeList) You are doing, basically: x = [1] for f in x: x[f] x[1] is out of range, because x is length=1, and the last valid index is 0. -m > > -- > Jim Mooney > > The Real Reason Things Keep Going Wrong: > > At the beginning of time, God set a Magic Top Spinning... and spinning... > and spinning... and spinning... and spinning... and spinning... and > spinning... > > After a few hundred million years God got bored and gave the top a good > kick; so it went rebounding away, flinging off planets and stars and > dinosaurs, and later, people who wrote about dinosaurs. > > Then God realized that although Order and Regularity are virtuous, if you > want interesting stories, now and then you have to give things a good Kick! > > This explains a lot. > _______________________________________________ > 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 davea at davea.name Tue Apr 23 04:03:18 2013 From: davea at davea.name (Dave Angel) Date: Mon, 22 Apr 2013 22:03:18 -0400 Subject: [Tutor] Why is my list index going out of range In-Reply-To: References: Message-ID: <5175EBE6.1090307@davea.name> On 04/22/2013 09:47 PM, Jim Mooney wrote: > Okay, what am I doing wrong here? I'm generating primes from a list > and getting "list index out of range," but since the for loops > controls the indexes I don't see how that's happening. I thought it > was the list append, but I commented that out and put in a print > statement, and I still got the line 5 error: > > primeList = [1] > numList = list(range(2,101)) > for e in numList: > for f in primeList: e and f are now values from the lists; they are *not* indexes into the list. > if numList[e] % primeList[f] != 0: #list index out of range if e % f != 0: #will get rid of the exception > primeList.append(numList[e]) > Unfortunately, you still have an algorithm bug. But now that you shouldn't get exceptions, I'll leave you to find the bug. -- DaveA From alan.gauld at btinternet.com Tue Apr 23 10:42:07 2013 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 23 Apr 2013 09:42:07 +0100 Subject: [Tutor] Why is my list index going out of range In-Reply-To: References: Message-ID: On 23/04/13 02:47, Jim Mooney wrote: > Okay, what am I doing wrong here? > primeList = [1] > numList = list(range(2,101)) > for e in numList: > for f in primeList: > if numList[e] % primeList[f] != 0: #list index out of range for lops in Python do not generate indexes they return the actual entries in the list. They are like a foreach loop in other languages. What you are doing is like pets = ['cat', 'dog','mouse'] for animal in pets: if pets[animal] == 'rabbit': print 'thats weird' You cannot use the animal string as an index. You use it directly like so: pets = ['cat', 'dog','mouse'] for animal in pets: if animal == 'rabbit': print 'thats better' Once you get used to this style of loop it is much easier than trying do do things with indexes. In your case its doubly confusing because the contents of your lists are numbers that could be used as indexes but would not give the result you expect. You were lucky that you started with a list of one element which was not zero. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From fomcl at yahoo.com Tue Apr 23 16:14:06 2013 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Tue, 23 Apr 2013 07:14:06 -0700 (PDT) Subject: [Tutor] string.Template Message-ID: <1366726446.81624.YahooMailNeo@web163805.mail.gq1.yahoo.com> Hello, Is there a better, *built-in* alternative for the code below? The recursion works, but it feels like reinventing the wheel. import string def translate(template, *args): ??? """Recursively $-substitute