Re: [Tutor] still not getting 'it'
On Wed, 5 Oct 2005, Rosalee Dubberly wrote: > I am having problems with changing the parameters in my second function. > I want the second function to run the same as the first, but take > different parameters. What am I doing wrong Hi Rosalee, [First, make sure you're subscribed to Tutor; it appears that you're still not subscribed, so every post that you've made to the list so far has been manually moderated. See: http://mail.python.org/mailman/listinfo/tutor for details on how to subscribe.] It sounds like you might be a little confused about how to write functions that take arguments. Let's go through a few examples and see where you get stuck. First, let's try a simpler problem: let's say that we'd like to make function that "doubles" whatever we give it. For example, if we imagine that we have this function already, we might be able to use it like this: ## >>> double(5) 10 >>> double(75) 150 ## Would you be able to write a function to do this? If the question seems simple, please forgive me: I'm just trying to trace where exactly you start getting stuck,. It does feel like you're missing something fundamental, so we have to start somewhere. *grin* Best of wishes to you! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Console output
> Hmm, just have to say something about the old days when > 'carriage return' and 'line feed' really meant something :-) Yep, and on a teleype were two physically separate keys! Alan G ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Shell Not Saved Problem
Steve Haley wrote: > A > couple of folks also mentioned a book, Beginning Python: From Novice to > Professional. I think I might try that. There are many good beginner's resources, both on-line and print. Here are a couple of good lists: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers?highlight=%28BeginnersGuide%2F%29 http://wiki.python.org/moin/IntroductoryBooks > Again, thanks everyone for all the help. I was very impressed with the > response to my cry for help. You're welcome. The Python community is a pretty friendly bunch and the tutor list is for newbie questions so come back next time you are stumped. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 20, Issue 11
Please take me off of your mailing list.[EMAIL PROTECTED] wrote: Send Tutor mailing list submissions totutor@python.orgTo subscribe or unsubscribe via the World Wide Web, visithttp://mail.python.org/mailman/listinfo/tutoror, via email, send a message with subject or body 'help' to[EMAIL PROTECTED]You can reach the person managing the list at[EMAIL PROTECTED]When replying, please edit your Subject line so it is more specificthan "Re: Contents of Tutor digest..."Today's Topics:1. Re: need help to understand terms for desinging a program(paul brian)2. Re: FW: Help Needed (Alan Gauld)3. How to strip both single and double quotes (Dick Moores)--Message: 1Date: Wed, 5 Oct 2005 10:22:48 +0100From: paul brian <[EMAIL PROTECTED]>Subject: Re: [Tutor] need he! lp to understand terms for desinging aprogramTo: "Hameed U. Khan" <[EMAIL PROTECTED]>Cc: tutor@python.orgMessage-ID:<[EMAIL PROTECTED]>Content-Type: text/plain; charset=ISO-8859-1This is a pretty big question, and it would be easier to answer if youcan give us more details about what you want to do.It seems you want to inspect outgoing mails (possibly rewrite theiraddresses?) before the mails are sent out.If you are looking to send out emails to a list then I suggest lookingat mailman - a python mailing list manager.If you want to use python to examine mail messages and do not carewhat mailserver (MTA) you use you could try exim instead of qmail andthen try exim-python. http://botanicus.net/dw/exim-python/exim-4.32py1.htmlOn 10/5/05, Hameed U. Khan <[EMAIL PROTECTED]>wrote:> Hi,> I need to make a program which ! will accomplish following. I dont> need the code. I want to make it myself. But I need guidance from you> people because I am not a good programmer. I need help in> understanding following terms.>> " qmail-queue reads a mail message from descriptor 0. It> then reads envelope information from descriptor 1. It> places the message into the outgoing queue for future> delivery by qmail-send.>> The envelope information is an envelope sender address> followed by a list of envelope recipient addresses. The> sender address is preceded by the letter F and terminated> by a 0 byte. Each recipient address is preceded by the> letter T and terminated by a 0 byte. The list of recipi-> ent addresses is terminated by an extra 0 byte. If qmail-> queue sees end-of-file before the extra 0 byte, it aborts> without placing the message into the queue.">> I want to inspect! messages before passing them to actuall qmail-queue> program.> Thanks in advance for your help.> --> Regards,> Hameed U. Khan> Registered Linux User #: 354374> ___> Tutor maillist - Tutor@python.org> http://mail.python.org/mailman/listinfo/tutor>Paul Brianm. 07875 074 534t. 0208 352 1741--Message: 2Date: Wed, 5 Oct 2005 10:44:09 +0100From: "Alan Gauld" <[EMAIL PROTECTED]>Subject: Re: [Tutor] FW: Help NeededTo: "Daniel Watkins" <[EMAIL PROTECTED]>, Message-ID: <[EMAIL PROTECTED]>Content-Type: text/plain; format=flowed; charset="UTF-8";reply-type=original> When I am in Python Shell of the IDLE GUI, when I click Edit/RunYou shouldn't be running scripts when in the shell, it executes them immediately.You use edit/run when working in a script file window.HTH,Alan G --Message: 3Date: Wed, 05 Oct 2005 02:43:47 -0700From: Dick Moores <[EMAIL PROTECTED]>Subject: [Tutor] How to strip both single and double quotesTo: tutor@python.orgMessage-ID: <[EMAIL PROTECTED]>Content-Type: text/plain; charset="iso-8859-1"; format=flowedI'm writing a script that takes any text and outputs to a file a list of duples (k, word) where k is the number of occurrences of word in the text.The text will contain "words" beginning or ending with non-alphabetic characters. To strip them off I use string.strip([chars]). My question is how to use strip just once to get rid of both kinds of quotes, single and double. It seems necessary to do it something like this:# L is the original list of "words" in the text.newL = []for word in L:word = lower(word)newWord = word.strip(".,!?;:&*'=-> newWord2 = newWord.strip('.,!?;:&*"=-> word = newWord2newL.append(word)But is it? Have I missed something?Thanks,Dick Moores--___Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutorEnd of Tutor Digest, Vol 20, Issue 11* Yahoo! for Good Click here to donate to the Hurricane Katrina relief effort. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] class and methods/functions
I have a class I am defining and then I call a function within that class. Getting error that function call is not defined. Does the function have to be created anywhere within a class or does it have to be defined before the call within the class. -- Eric Walker EDA/CAD Engineer Work: 208-368-2573 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class and methods/functions
Eric Walker wrote: > I have a class I am defining and then I call a function within that class. > Getting error that function call is not defined. Does the function have to be > created anywhere within a class or does it have to be defined before the call > within the class. Actual code and the error message (including the traceback) would be helpful here. Generally functions (usually called methods in this context) are defined within the body of a class and then called from outside the class. Functions have to be defined before they are called but not before they are referenced. Very simple example: >>> class B: ... def foo(self): ... print 'foo' ... self.bar() ... def bar(self): ... print 'bar' ... >>> b=B() >>> b.foo() foo bar Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class and methods/functions
Kent, Where I think my problem maybe in how I am running this. I want to eventually run from the command line. I started python idle from my linux command line and I was cut and pasting from my text file and seeing things work. Now i want to run it from the command line and its complaining. in my file I have something of the following. class yes: def func1 temp = re.match # return str(tempREG != 'None' def display(self): print all the class attributes def __init__(self,value): name = func1(value) other stuff def func2(): a = yes() try: func2() except: print "error" On Thursday 06 October 2005 11:33 am, Kent Johnson wrote: > Eric Walker wrote: > > I have a class I am defining and then I call a function within that > > class. Getting error that function call is not defined. Does the function > > have to be created anywhere within a class or does it have to be defined > > before the call within the class. > > Actual code and the error message (including the traceback) would be > helpful here. > > Generally functions (usually called methods in this context) are defined > within the body of a class and then called from outside the class. > Functions have to be defined before they are called but not before they > are referenced. > > Very simple example: > >>> class B: > > ... def foo(self): > ... print 'foo' > ... self.bar() > ... def bar(self): > ... print 'bar' > ... > > >>> b=B() > >>> b.foo() > > foo > bar > > Kent > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class and methods/functions
Its working now. the moving of the function outside of the class allows me to run it from the command line. Thanks On Thursday 06 October 2005 11:56 am, Eric Walker wrote: > Kent, > I made a correction the func1 I moved out of the class definition since it > wasn't really a method. so it should look like this. > > > class yes: > > def display(self): > > print all the class attributes > > def __init__(self,value): > > name = func1(value) > > other stuff > > > > def func1 > >temp = re.match # > >return str(tempREG != 'None' > > > > def func2(): > > a = yes() > > > > try: > > func2() > > except: > > print "error" > > On Thursday 06 October 2005 11:47 am, Eric Walker wrote: > > Kent, > > Where I think my problem maybe in how I am running this. I want to > > eventually run from the command line. I started python idle from my linux > > command line and I was cut and pasting from my text file and seeing > > things work. Now i want to run it from the command line and its > > complaining. in my file I have something of the following. > > > > class yes: > > def func1 > > temp = re.match # > > return str(tempREG != 'None' > > def display(self): > > print all the class attributes > > def __init__(self,value): > > name = func1(value) > > other stuff > > > > def func2(): > > a = yes() > > > > try: > > func2() > > except: > > print "error" > > > > On Thursday 06 October 2005 11:33 am, Kent Johnson wrote: > > > Eric Walker wrote: > > > > I have a class I am defining and then I call a function within that > > > > class. Getting error that function call is not defined. Does the > > > > function have to be created anywhere within a class or does it have > > > > to be defined before the call within the class. > > > > > > Actual code and the error message (including the traceback) would be > > > helpful here. > > > > > > Generally functions (usually called methods in this context) are > > > defined within the body of a class and then called from outside the > > > class. Functions have to be defined before they are called but not > > > before they are referenced. > > > > > > Very simple example: > > > >>> class B: > > > > > > ... def foo(self): > > > ... print 'foo' > > > ... self.bar() > > > ... def bar(self): > > > ... print 'bar' > > > ... > > > > > > >>> b=B() > > > >>> b.foo() > > > > > > foo > > > bar > > > > > > Kent > > > > > > ___ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class and methods/functions
Eric Walker wrote: > Kent, > Where I think my problem maybe in how I am running this. I want to eventually > run from the command line. I started python idle from my linux command line > and I was cut and pasting from my text file and seeing things work. Now i > want to run it from the command line and its complaining. in my file I have > something of the following. This is full of syntax errors... > > class yes: > def func1 should be def func1(self): > temp = re.match # OK but not used for anything > return str(tempREG != 'None' Missing close paren and tempREG is not defined so you will get a NameError at runtime > def display(self): This should have the same indentation as def func1; indentation is significant! > print all the class attributes > def __init__(self,value): > name = func1(value) probably you want self.func1(value) - to call a member function from inside another member function you have to prefix the name with self. > other stuff > > def func2(): > a = yes() > > try: > func2() > except: > print "error" Generic except: blocks like this are a bad idea, it hides useful information without providing any benefit. The traceback that Python prints on an uncaught exception may look like a lot of gibberish at first but it contains a wealth of useful information that is thrown away by this handler. HTH, Kent > > > On Thursday 06 October 2005 11:33 am, Kent Johnson wrote: > >>Eric Walker wrote: >> >>>I have a class I am defining and then I call a function within that >>>class. Getting error that function call is not defined. Does the function >>>have to be created anywhere within a class or does it have to be defined >>>before the call within the class. >> >>Actual code and the error message (including the traceback) would be >>helpful here. >> >>Generally functions (usually called methods in this context) are defined >>within the body of a class and then called from outside the class. >>Functions have to be defined before they are called but not before they >>are referenced. >> >>Very simple example: >> >>> class B: >> >> ... def foo(self): >> ... print 'foo' >> ... self.bar() >> ... def bar(self): >> ... print 'bar' >> ... >> >> >>> b=B() >> >>> b.foo() >> >>foo >>bar >> >>Kent >> >>___ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class and methods/functions
Sorry Kent, In my haste to just simulate I did make the example with syntax errors. Let me try this again and I guess your teaching me how to use this mailing list the correct way also. Ok this is the actual code. I am able to get it to run from the command line. Thanks kent for your patience with this Python Newbie class TPROJ: import re import string def display(self):#display method print self.BASENAME print self.PROJECT print self.REV print self.DESIGNATOR print self.TYPE def __init__(self,value):#createMethod auto executes since it has __ name = nameCheck(value) if name: self.BASENAME = value self.PROJECT = value.split(':')[0] self.REV = value.split(':')[1] self.DESIGNATOR = "NOVALUE" self.TYPE = ('SW','TMOD','SWA','TMODA')#constant tuple if not name: print "found a bad name: %s" % value def nameCheck(value):#checks to see if filename is valid. Has a colon for split import re tempREG = re.match('.*:.*',value) return str(tempREG) != 'None' def getProjectNames(): import os currentDir=os.getcwd() nameTable = {} temp=currentDir + '/TEMP' print temp os.chdir(temp) baseList=os.listdir(".") baseObjectList = [] for name in baseList: baseObjectList.append(TPROJ(name)) os.chdir(currentDir) for item in baseObjectList: print item.BASENAME try: getProjectNames() except: print "Got an Error" On Thursday 06 October 2005 12:05 pm, Kent Johnson wrote: > Eric Walker wrote: > > Kent, > > Where I think my problem maybe in how I am running this. I want to > > eventually run from the command line. I started python idle from my linux > > command line and I was cut and pasting from my text file and seeing > > things work. Now i want to run it from the command line and its > > complaining. in my file I have something of the following. > > This is full of syntax errors... > > > class yes: > > def func1 > > should be > > def func1(self): > > temp = re.match # > > OK but not used for anything > > > return str(tempREG != 'None' > > Missing close paren and tempREG is not defined so you will get a NameError > at runtime > > > def display(self): > > This should have the same indentation as def func1; indentation is > significant! > > > print all the class attributes > > def __init__(self,value): > > name = func1(value) > > probably you want self.func1(value) - to call a member function from inside > another member function you have to prefix the name with self. > > > other stuff > > > > def func2(): > > a = yes() > > > > try: > > func2() > > except: > > print "error" > > Generic except: blocks like this are a bad idea, it hides useful > information without providing any benefit. The traceback that Python prints > on an uncaught exception may look like a lot of gibberish at first but it > contains a wealth of useful information that is thrown away by this > handler. > > HTH, > Kent > > > On Thursday 06 October 2005 11:33 am, Kent Johnson wrote: > >>Eric Walker wrote: > >>>I have a class I am defining and then I call a function within that > >>>class. Getting error that function call is not defined. Does the > >>> function have to be created anywhere within a class or does it have to > >>> be defined before the call within the class. > >> > >>Actual code and the error message (including the traceback) would be > >>helpful here. > >> > >>Generally functions (usually called methods in this context) are defined > >>within the body of a class and then called from outside the class. > >>Functions have to be defined before they are called but not before they > >>are referenced. > >> > >>Very simple example: > >> >>> class B: > >> > >> ... def foo(self): > >> ... print 'foo' > >> ... self.bar() > >> ... def bar(self): > >> ... print 'bar' > >> ... > >> > >> >>> b=B() > >> >>> b.foo() > >> > >>foo > >>bar > >> > >>Kent > >> > >>___ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > > > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Eric Walker EDA/CAD Engineer Work: 208-368-2573 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class and methods/functions
Hi Eric, Quick comment on the last part of your program: > try: > getProjectNames() > except: > print "Got an Error" Don't do that. *grin* This is considered a misuse of exceptions. As a concrete example, say that we have a buggy program like this: ## >>> def showDivisions(n): ... for x in range(n): ... print n / x ... ## If we run this on a few arguments, we can see good error messages: ## >>> showDivisions(0) >>> showDivisions(1) Traceback (most recent call last): File "", line 1, in ? File "", line 3, in showDivisions ZeroDivisionError: integer division or modulo by zero ## So here, the error message is very clear that we're doing something silly with a division. The error message itself looks a little scary at first, but it's chock full of information. But contrast this with what happens if we use an exception handler: ## >>> try: ... showDivisions(1) ... except: ... print "error" ... error ## The word 'error' might be less intimidating than a full stack trace, but it's also useless in terms of helping us figure out the real reason why showDivisions is broken. The lesson from this is: don't use exception handlers to hide errors like that, at least, not without a strong overriding reason. Once you've dropped the exception handler, try rerunning your program again: you should get much better error messages, and we can start from there. One other comment: module import is usually done at toplevel. You're importing modules within classes: ## class TPROJ: import re ... ## and although this works, idiomatically, it's unusual enough that you may want to avoid doing that. Your code uses the 're' module a lot anyway, so it makes sense to let 're' live at the toplevel, like this: ## import re class TPROJ: ... ## Best of wishes to you! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class and methods/functions
Eric Walker wrote: > Sorry Kent, > In my haste to just simulate I did make the example with syntax errors. Let > me > try this again and I guess your teaching me how to use this mailing list the > correct way also. Yes. > Ok this is the actual code. I am able to get it to run > from the command line. > > Thanks kent for your patience with this Python Newbie You're welcome. A few notes below. > > class TPROJ: > import re > import string Common usage is to put all the imports at the top of the module. There are circumstances where you will put them inside a function but not in this case. > def display(self):#display method > print self.BASENAME > print self.PROJECT > print self.REV > print self.DESIGNATOR > print self.TYPE It's your choice, but all caps for attribute values is unusual in Python. > > def __init__(self,value):#createMethod auto executes since it has __ > name = nameCheck(value) My guess is that nameCheck is the function that you moved out of the class. If you want it to be part of the class, you have to call it with self.nameCheck(value) > if name: > self.BASENAME = value > self.PROJECT = value.split(':')[0] > self.REV = value.split(':')[1] > self.DESIGNATOR = "NOVALUE" > self.TYPE = ('SW','TMOD','SWA','TMODA')#constant tuple > if not name: could be else: > print "found a bad name: %s" % value > > > > def nameCheck(value):#checks to see if filename is valid. Has a colon for > split To put this in the class you would declare it as def nameCheck(self, value): > import re > tempREG = re.match('.*:.*',value) > return str(tempREG) != 'None' Still a syntax error here! > > def getProjectNames(): > import os > currentDir=os.getcwd() > nameTable = {} > temp=currentDir + '/TEMP' > print temp > os.chdir(temp) > baseList=os.listdir(".") > baseObjectList = [] > for name in baseList: > baseObjectList.append(TPROJ(name)) > > os.chdir(currentDir) > for item in baseObjectList: > print item.BASENAME > > > try: > getProjectNames() > except: > print "Got an Error" Still recommend removing this try / except. Or you could wait until you actually get an exception and ask here for help ;-) cuz we will ask you for the traceback. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] still not getting 'it' (fwd)
Hi Rosalee, [Keeping tutor in the conversation. Please make sure you're using the "Reply-to-All" feature of your email client.] I'll respond to the message once it reaches the mailing list. -- Forwarded message -- Date: Thu, 06 Oct 2005 11:49:44 -0700 From: Rosalee Dubberly <[EMAIL PROTECTED]> To: [EMAIL PROTECTED] Subject: Re: [Tutor] still not getting 'it' No the question doesn't seem to simple at all, I appreciate your help. I have totally confused myself and I need to start from the beginning to sort things out. Thanks for you time and help. >>>double = 2 * 5 >>>print 'The sum of 2 times 5 equals', double The sum of 2 times 5 equals 10 >>> ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class and methods/functions
On Thursday 06 October 2005 12:48 pm, Kent Johnson wrote > > class TPROJ: > > import re > > import string > > Common usage is to put all the imports at the top of the module. There are > circumstances where you will put them inside a function but not in this > case. I moved them all to the top before the class definition > > > def display(self):#display method > > print self.BASENAME > > print self.PROJECT > > print self.REV > > print self.DESIGNATOR > > print self.TYPE > > It's your choice, but all caps for attribute values is unusual in Python. > Ok, I want to follow normal python protocol. I changed them to lower case. > > def __init__(self,value):#createMethod auto executes since it has __ > > name = nameCheck(value) > > My guess is that nameCheck is the function that you moved out of the class. > If you want it to be part of the class, you have to call it with > self.nameCheck(value) > > > if name: > > self.BASENAME = value > > self.PROJECT = value.split(':')[0] > > self.REV = value.split(':')[1] > > self.DESIGNATOR = "NOVALUE" > > self.TYPE = ('SW','TMOD','SWA','TMODA')#constant tuple > > if not name: > > could be else: > > print "found a bad name: %s" % value > > yes, I did remove this from the class. I really didn't need it in there. I moved the check outside under the main running function. To check the name before I even create the object. The way I had it before it would create an object regardless if the name had a colon or not. > def nameCheck(self, value): > > import re > > tempREG = re.match('.*:.*',value) > > return str(tempREG) != 'None' > > Still a syntax error here! > Code is working as I thought it would. What syntax error do I have? > Still recommend removing this try / except. Or you could wait until you > actually get an exception and ask here for help ;-) cuz we will ask you for > the traceback. yes, I did remove the try except. Man this group is great. I am going to be a python coder yet. current code sample follows: import re import string import os class TPROJ: def display(self):#display method print self.basename print self.project print self.rev print self.designator print self.type def __init__(self,value):#createMethod auto executes since it has __ self.basename = value self.project = value.split(':')[0] self.rev = value.split(':')[1] self.designator = "NOVALUE" self.type = ('SW','TMOD','SWA','TMODA')#constant tuple def nameCheck(value): tempREG = re.match('.*:.*',value) return str(tempREG) != 'None' def getProjectNames(): currentDir=os.getcwd() nameTable = {} temp=currentDir + '/TEMP' print temp os.chdir(temp) baseList=os.listdir(".") baseObjectList = [] for name in baseList: if nameCheck(name): baseObjectList.append(TPROJ(name)) Python Newbie... ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] still not getting 'it' (fwd)
> No the question doesn't seem to simple at all, I appreciate your help. I > have totally confused myself and I need to start from the beginning to > sort things out. Thanks for you time and help. > > >>>double = 2 * 5 > >>>print 'The sum of 2 times 5 equals', double > The sum of 2 times 5 equals 10 Hi Rosalee, Ok, that's probably the problem then: it sounds like you might not be familiar with writing and using functions. Let's do a quick primer. For the purposes of trying to connecting to things that you should know about, I'll borrow a math example, but if you want, we can make examples using different domains besides math. In algebra math classes, we may have seen things like: f(x) = 2 * x We might write on a blackboard such things like: f(2) = 2 * 2 = 4 f(8) = 2 * 8 = 16 In a math function definition like "f(x) = 2 * x", we're trying to capture the concept of doubling something, and we give that particular concept the name 'f', just so we can talk about it later. A "function" in Python is sorta like a "function" in mathematics. (It's not quite the same, and we'll can talk about this in more detail later.) But anyway, the doubling function above can be written in Python like this: ## def f(x): return 2 * x ## In a Python function definition like "def f(x): return 2 * x", we're trying to capture the process of doubling something, and we give that particular process the name 'f', just so we can use it later on. Let's play with this 'f' function that we've defined. From the interactive interpreter, we can enter in the function, and then test it out on a few inputs: ## >>> def f(x): ... return 2 * x ... >>> >>> f ## When we say 'f', Python knows that we're talking about some function. (Um... ignore the weird '0x403a6ae4' thing for now. *grin*) The main concept here is that 'f' is now a name for some thing that we can hold and use, just like a number or a string. Let's try using 'f': ## >>> f(2) 4 >>> f(3) 6 >>> f(8) 16 ## We can use 'f' with different inputs, and we get back different outputs. And we can even use f() like this: ## >>> f(f(2)) 8 ## Usually, programmers like to give their functions nicer names than 'f': mathematicians like brevity, but programmers often like to be able to read their programs. We can name 'f' as 'double': ## >>> def double(x): ... return 2 * x ... >>> double(double(2)) 8 ## And we can follow this naming idea a bit further, and rename 'x' to something else, like 'something': ## >>> def double(something): ... return 2 * something ... >>> double(42) 84 ## "To double something, just multiply 2 to that something." Does this make sense so far? Please feel free to ask questions on this: this is very fundamental stuff, and if you're getting stuck here, we need to figure out what we can to do help get you unstuck. Good luck! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class and methods/functions
Eric Walker wrote: > On Thursday 06 October 2005 12:48 pm, Kent Johnson wrote > yes, I did remove this from the class. I really didn't need it in there. I > moved the check outside under the main running function. To check the name > before I even create the object. The way I had it before it would create an > object regardless if the name had a colon or not. That makes sense. > > >> def nameCheck(self, value): >> >>>import re >>>tempREG = re.match('.*:.*',value) >>>return str(tempREG) != 'None' >> >>Still a syntax error here! >> > > Code is working as I thought it would. What syntax error do I have? Oops, I was still *reading* a syntax error :-) > > Man this group is great. I am going to be a > python coder yet. Yep :-) > current code sample follows: A few more advanced notes for you below, just in case your brain hasn't exploded yet :-) Kent > > > import re > import string > import os > > class TPROJ: Tproj or TProj would be a more idiomatic name... > > def display(self):#display method > print self.basename > print self.project > print self.rev > print self.designator > print self.type > > def __init__(self,value):#createMethod auto executes since it has __ > self.basename = value > self.project = value.split(':')[0] > self.rev = value.split(':')[1] If you are sure there will be just one colon this can be written as self.project, self.rev = value.split(':') Tuple assignment rocks! If you try this with more than one colon you will get an error. > self.designator = "NOVALUE" > self.type = ('SW','TMOD','SWA','TMODA')#constant tuple > > > > def nameCheck(value): > tempREG = re.match('.*:.*',value) > return str(tempREG) != 'None' > > def getProjectNames(): > currentDir=os.getcwd() > nameTable = {} > temp=currentDir + '/TEMP' > print temp > os.chdir(temp) > baseList=os.listdir(".") > baseObjectList = [] > for name in baseList: > if nameCheck(name): > baseObjectList.append(TPROJ(name)) The above four lines could be replaced with a single list comprehension if you like: baseObjectList = [ TPROJ(name) for name in baseList if nameCheck(name) ] http://www.amk.ca/python/2.0/index.html#SECTION00060 Kent > > Python Newbie... > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] still not getting 'it' (fwd)
I am going to 'play' with this in IDLE. I have used your tutorial posted on the Net. Good stuff!! Thanks for breaking this down into different examples. You are a great instructor. From: Danny Yoo <[EMAIL PROTECTED]> To: Tutor CC: [EMAIL PROTECTED] Subject: Re: [Tutor] still not getting 'it' (fwd) Date: Thu, 6 Oct 2005 12:27:16 -0700 (PDT) > No the question doesn't seem to simple at all, I appreciate your help. I > have totally confused myself and I need to start from the beginning to > sort things out. Thanks for you time and help. > > >>>double = 2 * 5 > >>>print 'The sum of 2 times 5 equals', double > The sum of 2 times 5 equals 10 Hi Rosalee, Ok, that's probably the problem then: it sounds like you might not be familiar with writing and using functions. Let's do a quick primer. For the purposes of trying to connecting to things that you should know about, I'll borrow a math example, but if you want, we can make examples using different domains besides math. In algebra math classes, we may have seen things like: f(x) = 2 * x We might write on a blackboard such things like: f(2) = 2 * 2 = 4 f(8) = 2 * 8 = 16 In a math function definition like "f(x) = 2 * x", we're trying to capture the concept of doubling something, and we give that particular concept the name 'f', just so we can talk about it later. A "function" in Python is sorta like a "function" in mathematics. (It's not quite the same, and we'll can talk about this in more detail later.) But anyway, the doubling function above can be written in Python like this: ## def f(x): return 2 * x ## In a Python function definition like "def f(x): return 2 * x", we're trying to capture the process of doubling something, and we give that particular process the name 'f', just so we can use it later on. Let's play with this 'f' function that we've defined. From the interactive interpreter, we can enter in the function, and then test it out on a few inputs: ## >>> def f(x): ... return 2 * x ... >>> >>> f ## When we say 'f', Python knows that we're talking about some function. (Um... ignore the weird '0x403a6ae4' thing for now. *grin*) The main concept here is that 'f' is now a name for some thing that we can hold and use, just like a number or a string. Let's try using 'f': ## >>> f(2) 4 >>> f(3) 6 >>> f(8) 16 ## We can use 'f' with different inputs, and we get back different outputs. And we can even use f() like this: ## >>> f(f(2)) 8 ## Usually, programmers like to give their functions nicer names than 'f': mathematicians like brevity, but programmers often like to be able to read their programs. We can name 'f' as 'double': ## >>> def double(x): ... return 2 * x ... >>> double(double(2)) 8 ## And we can follow this naming idea a bit further, and rename 'x' to something else, like 'something': ## >>> def double(something): ... return 2 * something ... >>> double(42) 84 ## "To double something, just multiply 2 to that something." Does this make sense so far? Please feel free to ask questions on this: this is very fundamental stuff, and if you're getting stuck here, we need to figure out what we can to do help get you unstuck. Good luck! _ Is your PC infected? Get a FREE online computer virus scan from McAfee® Security. http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] unsubcribe
___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to write this to a file?
print outputs the string to the std output (sys.stdout). You could redirect the std output to a file instead of the screen as follows, but it's a bit clumsy. fptr = open("hans.log", "a+") import sys sys.stdout = fptr print "Hi there" This will output the string into the file hans.log. However, to get it to print to the screen again, u will need to have stored the original contents of sys.stdout somewhere and then redirected sys.stdout to that again. TCL provides a more handy way of doing this: print $fptr "Hi there" Cheers Hans -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Dick Moores Sent: Thursday, 6 October 2005 12:18 p.m. To: tutor@python.org Subject: [Tutor] How to write this to a file? I have a script that writes it's output to a file. I also print the time with print "Time was %.4g seconds" % (timeEnd - timeStart) How could I also have the same output of the print expression, written to the file? Thanks, Dick Moores ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class and methods/functions
> The above four lines could be replaced with a single list comprehension if > you like: baseObjectList = [ TPROJ(name) for name in baseList if > nameCheck(name) ] > http://www.amk.ca/python/2.0/index.html#SECTION00060 > > Kent > BOOOM Let me pick up my skull fragments Ok I understand all but one. Having trouble understanding list comprehension. I thought I understood but its barking at me. I would think that this would make mytest the same values as test? >>> test ['a', 'b', 'c', 'd'] >>> mytest[name for name in test:] File "", line 1 mytest[name for name in test:] ^ SyntaxError: invalid syntax >>> > > > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Eric Walker EDA/CAD Engineer Work: 208-368-2573 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class and methods/functions
DUH.. I found the answer mytest = [name for name in test] Thanks again.. > > The above four lines could be replaced with a single list comprehension > > if you like: baseObjectList = [ TPROJ(name) for name in baseList if > > nameCheck(name) ] > > http://www.amk.ca/python/2.0/index.html#SECTION00060 > > > > Kent > > BOOOM > Let me pick up my skull fragments > Ok I understand all but one. Having trouble understanding list > comprehension. I thought I understood but its barking at me. I would think > that this would make mytest the same values as test? > > >>> test > > ['a', 'b', 'c', 'd'] > > >>> mytest[name for name in test:] > > File "", line 1 > mytest[name for name in test:] > ^ > SyntaxError: invalid syntax > > > > ___ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > ___ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to write this to a file?
Hans Dushanthakumar wrote: > print outputs the string to the std output (sys.stdout). You could > redirect the std output to a file instead of the screen as follows, but > it's a bit clumsy. > > TCL provides a more handy way of doing this: > print $fptr "Hi there" In Python you can say print >>fptr, "Hi there" Kent > > Cheers > Hans > > > -Original Message- > From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On > Behalf Of Dick Moores > Sent: Thursday, 6 October 2005 12:18 p.m. > To: tutor@python.org > Subject: [Tutor] How to write this to a file? > > I have a script that writes it's output to a file. I also print the time > with > > print "Time was %.4g seconds" % (timeEnd - timeStart) > > How could I also have the same output of the print expression, written > to the file? > > Thanks, > > Dick Moores > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Did anyone get the Kamaelia "Conversing" chapter 5 to work?
I was working through their tutorial: > * http://kamaelia.sourceforge.net/MiniAxon/ Chapter 5 claims the output should be: Hello World 2 Hello World 3 ... Hello World 97 Hello World 98 But mine outputs only: Hello World 2 (no further output) I can see in Pythonwin's debugger that p.boxes['outbox'] fills up with the hundred or so messages intended for display, but they never get displayed. I suspect an indentation problem, but I can't spot it, even stepping through in the debugger. Alan#= class microprocess(object): def __init__(self): super(microprocess, self).__init__() def main(self): yield 1 #= class scheduler(microprocess): def __init__(self): super(scheduler, self).__init__() self.active = [] self.newqueue = [] def main(self): for x in xrange(100): for current in self.active: yield 1 try: result = current.next() if result is not -1: self.newqueue.append(current) except StopIteration: pass self.active = self.newqueue self.newqueue = [] def activateMicroprocess(self, someprocess): microthread = someprocess.main() self.newqueue.append(microthread) #= class postman(microprocess): def __init__(self, source, sourcebox, sink, sinkbox): super(postman, self).__init__() self.source = source self.sourcebox = sourcebox self.sink = sink self.sinkbox = sinkbox def main(self): yield 1 if self.source.dataReady(self.sourcebox): postdata = self.source.recv(self.sourcebox) self.sink.send(postdata, self.sinkbox) #= class component(microprocess): def __init__(self): super(component, self).__init__() self.boxes = { 'inbox': [], 'outbox': [] } def send(self, value, boxname): self.boxes[boxname].append(value) def recv(self, boxname): return self.boxes[boxname].pop(0) def dataReady(self, boxname): return len( self.boxes[boxname] ) #= class Producer(component): def __init__(self, message): super(Producer, self).__init__() self.message = message def main(self): while 1: yield 1 self.send(self.message, "outbox") #= class Consumer(component): #~ def __init__(self, tag): #~ super(Consumer, self).__init__() def main(self): count = 0 while 1: yield 1 count += 1 if self.dataReady("inbox"): data = self.recv("inbox") print data, count p = Producer("Hello World") c = Consumer() postie = postman(p, "outbox", c, "inbox") myscheduler = scheduler() myscheduler.activateMicroprocess(p) myscheduler.activateMicroprocess(c) myscheduler.activateMicroprocess(postie) for _ in myscheduler.main(): pass ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Did anyone get the Kamaelia "Conversing" chapter 5 to work?
R. Alan Monroe wrote: > I was working through their tutorial: > > >>* http://kamaelia.sourceforge.net/MiniAxon/ > > > Chapter 5 claims the output should be: > Hello World 2 > Hello World 3 > ... > Hello World 97 > Hello World 98 > > But mine outputs only: > Hello World 2 > (no further output) > > I can see in Pythonwin's debugger that p.boxes['outbox'] fills up with > the hundred or so messages intended for display, but they never get > displayed. I suspect an indentation problem, but I can't spot it, even > stepping through in the debugger. I made exactly the same mistake! You have to put an infinite loop in postman.main(). It's in the directions but I guess it's easy to miss. Kent > > Alan > > > > > #= > class microprocess(object): > > def __init__(self): > super(microprocess, self).__init__() > > def main(self): > yield 1 > > #= > class scheduler(microprocess): > > def __init__(self): > super(scheduler, self).__init__() > self.active = [] > self.newqueue = [] > > def main(self): > for x in xrange(100): > for current in self.active: > yield 1 > try: > result = current.next() > if result is not -1: > self.newqueue.append(current) > except StopIteration: > pass > self.active = self.newqueue > self.newqueue = [] > > def activateMicroprocess(self, someprocess): > microthread = someprocess.main() > self.newqueue.append(microthread) > > #= > class postman(microprocess): > > def __init__(self, source, sourcebox, sink, sinkbox): > super(postman, self).__init__() > self.source = source > self.sourcebox = sourcebox > self.sink = sink > self.sinkbox = sinkbox > > def main(self): > yield 1 > if self.source.dataReady(self.sourcebox): > postdata = self.source.recv(self.sourcebox) > self.sink.send(postdata, self.sinkbox) > > #= > class component(microprocess): > > def __init__(self): > super(component, self).__init__() > self.boxes = { 'inbox': [], 'outbox': [] } > > def send(self, value, boxname): > self.boxes[boxname].append(value) > > def recv(self, boxname): > return self.boxes[boxname].pop(0) > > def dataReady(self, boxname): > return len( self.boxes[boxname] ) > > #= > class Producer(component): > > def __init__(self, message): > super(Producer, self).__init__() > self.message = message > > def main(self): > while 1: > yield 1 > self.send(self.message, "outbox") > > #= > class Consumer(component): > > #~ def __init__(self, tag): > #~ super(Consumer, self).__init__() > > def main(self): > count = 0 > while 1: > yield 1 > count += 1 > if self.dataReady("inbox"): > data = self.recv("inbox") > print data, count > > > p = Producer("Hello World") > c = Consumer() > postie = postman(p, "outbox", c, "inbox") > > myscheduler = scheduler() > myscheduler.activateMicroprocess(p) > myscheduler.activateMicroprocess(c) > myscheduler.activateMicroprocess(postie) > > for _ in myscheduler.main(): > pass > > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Did anyone get the Kamaelia "Conversing" chapter 5 to work?
>> I can see in Pythonwin's debugger that p.boxes['outbox'] fills up with >> the hundred or so messages intended for display, but they never get >> displayed. I suspect an indentation problem, but I can't spot it, even >> stepping through in the debugger. > I made exactly the same mistake! You have to put an infinite loop in > postman.main(). It's in the directions but I guess it's easy to > miss. Bingo, you da man. Alan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Importing Modules Within Classes
Recently, there has been an example of someone importing modules within a class definition. eg: class Exemplar: import re ...use re... It seems obvious to me that this is incorrect, though more through training than actual observation on my part, and it should be: import re class Exemplar: ...use re... However, someone (I don't recall who) said that there were occasions when it would be appropriate to import modules the former way. I was just wondering under what circumstances importing should be done this way? Cheers, Dan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Did anyone get the Kamaelia "Conversing" chapter 5 to work?
On Friday 07 October 2005 00:13, R. Alan Monroe wrote: ... > I can see in Pythonwin's debugger that p.boxes['outbox'] fills up with > the hundred or so messages intended for display, but they never get > displayed. I suspect an indentation problem, but I can't spot it, even > stepping through in the debugger. Hi! First of all thanks for trying the tutorial - hope it's been interesting. I'm sorry you hit a problem with it - it looks like the HTML formatting has caused some issues :-( All the code and examples used were tested before the being placed into the "tabbed" version of the tutorial. In this case it looks like the whitespace has gone horribly horribly wrong on that tab :-((( I'll sort it out. In the meantime though, In case of precisely this problem occuring, I also placed that source for all 4 main sections (Standing, Walking, Talking, Conversing) in the following page here: http://kamaelia.sourceforge.net/MiniAxonFull.html I've just double checked what happens when running the contents of that page, and it works as expected (here at least), so I suspect the problems you're seeing are simply due to "code being in HTML" issues. Also, the entire tutorial is available as a single page here, rather than tabbed: * http://kamaelia.sourceforge.net/MiniAxon.html But that has the answers inline, which is why I didn't mention it before. That *does* appear to have formatting preserved correctly in firefox, and I've also just double checked that when copying and pasting that the stated results were the ones stated. Hoping this helps, and thanks! If you're willing to spare a few sentances of how you found the tutorial (on or off list), I'd be really interested in hearing. If it's difficult, what was difficult (naff HTML for example...), if it was clear/unclear, that sort of thing. That said, this query is useful feedback in itself :) Best Regards, (and apologies for the HTML formatting ... :-( Michael. -- Michael Sparks, Senior R&D Engineer, Digital Media Group [EMAIL PROTECTED], http://kamaelia.sourceforge.net/ British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This e-mail may contain personal views which are not the views of the BBC. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Did anyone get the Kamaelia "Conversing" chapter 5 to work?
> I've just double checked what happens when running the contents of that > page, and it works as expected (here at least), so I suspect the problems > you're seeing are simply due to "code being in HTML" issues. Yeah I was writing as much as I was able on my own rather than copying/pasting the code, so it was mainly an oversight in my own work. Alan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Matching dictionary entries by partial key
I'm trying to traverse a dictionary looking for partial matches of the key, and I'm not sure how. Here's a sample dictionary: dict = {1234 : value1, 20051234 : value2, 20071234 : value3} Here's what I'm trying to do: for key in dict: if key == or key == 2005: do something with dict[key] The challenge is that I only care about the first four digits of the key for the purpose of this match - is there a way to express this? I could probably create a wrapper dictionary using just the first four digits of the key as they key, and containing the original key:value pair as a list within it, but that seems cumbersome. Any one have a suggestion? Thanks. -- yours, William signature.asc Description: Digital signature ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Importing Modules Within Classes
Daniel Watkins wrote: > Recently, there has been an example of someone importing modules within > a class definition. eg: > > class Exemplar: > import re > ...use re... > > It seems obvious to me that this is incorrect, though more through > training than actual observation on my part, and it should be: > > import re > > class Exemplar: > ...use re... It's not really incorrect, it is legal syntax and it will do what you expect. It is not idiomatic and in general it is simpler to just put all the imports at the top. > However, someone (I don't recall who) said that there were occasions > when it would be appropriate to import modules the former way. I was > just wondering under what circumstances importing should be done this > way? That was me. I nest imports quite frequently in Jython code where the first import of a module is fairly expensive in time. Putting the import in the function that needs it delays the import and perhaps the module won't be imported at all. import is an executable statement. When it runs, the interpreter first looks to see if the module has already been imported. If so, the existing module is bound to the import name in the current namespace. If the module has not yet been imported, it is loaded *and executed*, then bound to the name in the current namespace. So if module A imports B which imports C and D, then importing A will also load and execute B, C and D. If any of these are time-consuming you may want to defer them. I found with my Jython programs that I could shorten start-up time quite a bit by deferring some imports until they were needed. Another reason for the nested style of imports is to resolve problems with circular imports. There are some subtle problems that can occur when A imports B and B imports A. By nesting one of the imports you can defer it and sometimes avoid the problem. In this case I think removing the circular import is a much better solution - circular dependencies are evil! Kent > > Cheers, > Dan > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Matching dictionary entries by partial key
William O'Higgins Witteman wrote: > I'm trying to traverse a dictionary looking for partial matches of the > key, and I'm not sure how. Here's a sample dictionary: > > dict = {1234 : value1, 20051234 : value2, 20071234 : value3} > > Here's what I'm trying to do: > > for key in dict: > if key == or key == 2005: if key.startswith('') or key.startswith('2005'): or with a regular expresion: if re.match('|2005', key): > do something with dict[key] > > The challenge is that I only care about the first four digits of the key > for the purpose of this match - is there a way to express this? I could > probably create a wrapper dictionary using just the first four digits of > the key as they key, and containing the original key:value pair as a > list within it, but that seems cumbersome. Any one have a suggestion? If you have a *lot* of keys and need more speed, that might be a good optimization. For a small dict, just use startswith(). Kent > Thanks. > > > > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Simple Tkinter question
I'm trying to update an Entry's textvariable several times within my Button handler, like so: from Tkinter import * from time import * def my_update(): for i in range(3): tv.set("Now it's %d"%i) sleep(1) root=Tk() tv=StringVar() Entry(textvariable=tv).pack() tv.set("Initial Value of StringVar") Button(text="Update", command=my_update).pack() root.mainloop() What happens when I hit the Update button is a 3-second pause, then "Now it's 2" is displayed. What I expected to see in the Entry was: "Now it's 0" (right away) "Now it's 1" (after 1 second pause) "Now it's 2" (after another 1 second pause) Any idea what's going on here? Why doesn't "tv.set("") happen immediately? Thanks, -Mike ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Matching dictionary entries by partial key
On Thu, 6 Oct 2005, William O'Higgins Witteman wrote: > I'm trying to traverse a dictionary looking for partial matches of the > key, and I'm not sure how. Here's a sample dictionary: > > dict = {1234 : value1, 20051234 : value2, 20071234 : value3} > > Here's what I'm trying to do: > > for key in dict: > if key == or key == 2005: > do something with dict[key] > > The challenge is that I only care about the first four digits of the key > for the purpose of this match - is there a way to express this? I could > probably create a wrapper dictionary using just the first four digits of > the key as they key, and containing the original key:value pair as a > list within it, but that seems cumbersome. Hi William, The dictionary (hashtable) data structure is really meant for exact key match: it does not do partial keyword match well at all, and trying to bend it to do so is going against its grain. But using the first four digits as the key sounds right for your application: from what you've told us so far, you're trying to express a quick dictionary lookup using the first four digits as the key. If we do take this route, doing this is not too bad, especially if we take advantage of a dictionary's setdefault() method: ### >>> words = 'this is a test of the emergency broadcast system'.split() >>> words ['this', 'is', 'a', 'test', 'of', 'the', 'emergency', 'broadcast', 'system'] >>> >>> d = {} >>> for word in words: ... d.setdefault(word[0], []).append(word) ... >>> >>> d {'a': ['a'], 'b': ['broadcast'], 'e': ['emergency'], 'i': ['is'], 'o': ['of'], 's': ['system'], 't': ['this', 'test', 'the']} ### But as Kent mentioned, though, perhaps the easiest thing to implement is a simple linear scan across all your key-values, and not worry until we know this is a performance hotspot. *grin* It really depends on how many entries we're searching against. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple Tkinter question
On Thu, 6 Oct 2005, Mike Cheponis wrote: > I'm trying to update an Entry's textvariable several times within my > Button handler, like so: > > from Tkinter import * > from time import * > > def my_update(): >for i in range(3): > tv.set("Now it's %d"%i) > sleep(1) > > root=Tk() > tv=StringVar() > Entry(textvariable=tv).pack() > tv.set("Initial Value of StringVar") > Button(text="Update", command=my_update).pack() > root.mainloop() Hi Mike, The problem is that the GUI needs control back to be able to update the GUI display. At the moment, there's only one thread of execution, and the call to time.sleep() deprives the GUI of the control it needs to draw things. Tkinter has a particular way of doing sleep()-like behavior that interacts better with the GUI. We can use the "after()" method to tell the GUI to do some action after some period of time. Here's a quick-and-dirty example: ## import Tkinter root = Tkinter.Tk() label = Tkinter.Label(root, text="hello") label.pack() def doCountUpdate(n): label['text'] = n label.after(1000, doCountUpdate, n + 1) doCountUpdate(0) root.mainloop() ## The initial call to doCountUpdate() updates the label text, and then tells the label: "after 1000 milliseconds (one second), call doCountUpdate again, and with n+1 as its argument." After we schedule this next update, we give control back to the GUI, and trust that the GUI will keep its promise to call our function after the timeout period. For reference information on this, see: http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm This isn't the only way to handle this sort of problem: another possible approach involves the use of threads. But you may want to try using 'after()' first, since I think it has an easier learning curve than threads. Best of wishes to you! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Simple Tkinter question (fwd)
-- Forwarded message -- Date: Thu, 6 Oct 2005 22:07:50 -0700 (PDT) From: Mike Cheponis <[EMAIL PROTECTED]> To: Danny Yoo <[EMAIL PROTECTED]> Subject: Re: [Tutor] Simple Tkinter question On Thu, 6 Oct 2005, Danny Yoo wrote: >> from Tkinter import * >> from time import * >> >> def my_update(): >>for i in range(3): >> tv.set("Now it's %d"%i) >> sleep(1) >> >> root=Tk() >> tv=StringVar() >> Entry(textvariable=tv).pack() >> tv.set("Initial Value of StringVar") >> Button(text="Update", command=my_update).pack() >> root.mainloop() > > > Hi Mike, > > The problem is that the GUI needs control back to be able to update the > GUI display. Thanks, but what I don't understand is: Why doesn't the call tv.set("string") update what's on the screen. Clearly, Tkinter has control at that point, and there's no reason to delay updating the screen, is there? What I'm really trying to do is: I have a bunch of lines selected on the screen. I'm using Pmw. This returned tuple has a number of items I need to play. While the sound is playing, I want to display the name of the sound on the GUI. (The playing is done by a routine that writes to the serial port - that is, I call a function with the filename of the sound, and it plays it). I'll see if I can get something from the URL you mention, perhaps calling after_idle(). Thanks again! -Mike > Tkinter has a particular way of doing sleep()-like behavior that interacts > better with the GUI. We can use the "after()" method to tell the GUI to > do some action after some period of time. > > Here's a quick-and-dirty example: > > ## > import Tkinter > root = Tkinter.Tk() > label = Tkinter.Label(root, text="hello") > label.pack() > > def doCountUpdate(n): >label['text'] = n >label.after(1000, doCountUpdate, n + 1) > > doCountUpdate(0) > root.mainloop() > ## > > > The initial call to doCountUpdate() updates the label text, and then tells > the label: "after 1000 milliseconds (one second), call doCountUpdate > again, and with n+1 as its argument." After we schedule this next update, > we give control back to the GUI, and trust that the GUI will keep its > promise to call our function after the timeout period. > > For reference information on this, see: > > http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm > > This isn't the only way to handle this sort of problem: another possible > approach involves the use of threads. But you may want to try using > 'after()' first, since I think it has an easier learning curve than > threads. > > > Best of wishes to you! > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [Fwd: Re: Consistant Overhead Byte Stuffing (COBS)algorithm help]
> ... is the decoding code, it does what you > describe below. It is adding the zeros back in, that > is the dst.append('\0') > > Kent Really??? I am a noob, but it looks like it only puts a \0 at the end if code (the length) is less than 255, as the if statement is out of the for loop? this would be part of the coding algorithm, no? In that theme of writing, here is what I would do to make it decode: def UnStuffData(src,dst,len): if code == 0xFF: pass else: x = src(0) for code in src: for i in range(1,code): if i == x: dst.append('\0') x = src(i) else: dst.append(i) dst.pop(0) #remove first byte # if code < 0xff # dst.append('\0') -mike --- Kent Johnson <[EMAIL PROTECTED]> wrote: > Michael Cotherman wrote: > > def UnStuffData(src,dst,len): > > > >for code in src: > > for i in range(1,code): > > dst.append(i) > > > > if code < 0xff > > dst.append('\0') > > > > the above is the below code uncommented... > > it(and the original code) just seem to find the > end > > and puts a zero there... > > > > I do not see the existing zeroes replaced. > this is > > kinda why I wanted to start from the > specification... > > The above is the decoding code, it does what you > describe below. It is adding the zeros back in, that > is the dst.append('\0') > > Kent > > > decoding is: > > pop the first byte of the packet off and place > > subsequent bytes into the output until you get to > the > > byte pointed to by the popped byte. When you reach > > that byte, read its value as the new 'relative' > > pointer, and copy x00 to the output. Proceed as > above, > > placing bytes to the output until the relative > pointer > > is reached or the end of the packet occurrs. > > > > I guess I need to look if I wish for this part of > the > > program to handle the input as one big existing > > string, or work on it a byte at a time as it comes > in. > > > > > > -mike c > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 20, Issue 22
t), I'd be really interested in hearing. If it's difficult, what was difficult (naff HTML for example...), if it was clear/unclear, that sort of thing. That said, this query is useful feedback in itself :)Best Regards, (and apologies for the HTML formatting ... :-(Michael.-- Michael Sparks, Senior R&D Engineer, Digital Media Group[EMAIL PROTECTED], http://kamaelia.sourceforge.net/British Broadcasting Corporation, Research and DevelopmentKingswood Warren, Surrey KT20 6NPThis e-mail may contain personal views which are not the views of the BBC.--Message: 4Date: Thu, 6 Oct 2005 22:04:43 -0400From: "R. Alan Monroe" <[EMAIL PROTECTED]>Subject: Re: [Tutor] Did anyone get the Kamaelia "Conversing" chapter5 to work?To: tutor@python.orgMessage-ID: <[EMAIL PROTECTED]>Content-Type: text/plain; charset=us-ascii> I've just double checked what happens when running the contents of that> page, and it works as expected (here at least), so I suspect the problems> you're seeing are simply due to "code being in HTML" issues.Yeah I was writing as much as I was able on my own rather thancopying/pasting the code, so it was mainly an oversight in my ownwork.Alan--Message: 5Date: Thu, 6 Oct 2005 22:08:02 -0400From: William O'Higgins ! Witteman <[EMAIL PROTECTED]>Subject: [Tutor] Matching dictionary entries by partial keyTo: tutor@python.orgMessage-ID: <[EMAIL PROTECTED]>Content-Type: text/plain; charset="us-ascii"I'm trying to traverse a dictionary looking for partial matches of thekey, and I'm not sure how. Here's a sample dictionary:dict = {1234 : value1, 20051234 : value2, 20071234 : value3}Here's what I'm trying to do:for key in dict:if key == or key == 2005:do something with dict[key]The challenge is that I only care about the first four digits of the keyfor the purpose of this match - is there a way to express this? I couldprobably create a wrapper dictionary using just the first four digits ofthe key as they key, and containing the original key:value pair as alist within it, but that seems cumbersome. Any one have a suggestion?Thanks.-- yours,William-- next part --A non-text attachment was scrubbed...Name: not availableType: application/pgp-signatureSize: 189 bytesDesc: Digital signatureUrl : http://mail.python.org/pipermail/tutor/attachments/20051006/7007a205/attachment-0001.pgp--Message: 6Date: Thu, 06 Oct 2005 22:21:21 -0400From: Kent Johnson <[EMAIL PROTECTED]>Subject: Re: [Tutor] Importing Modules Within ClassesCc: tutor@python.orgMessage-ID: <[EMAIL PROTECTED]>Content-Type: text/plain; charset=ISO-8859-1; format=flowedDaniel Watkins wrote:> Recently, there has been an example of someone importing modules within> a class definition. eg:> > class Exemplar:> import re> ...use re...> > It seems obvious to me that this is incorrect, though more through> training than actual observation on! my part, and it should be:> > import re> > class Exemplar:> ...use re...It's not really incorrect, it is legal syntax and it will do what you expect. It is not idiomatic and in general it is simpler to just put all the imports at the top.> However, someone (I don't recall who) said that there were occasions> when it would be appropriate to import modules the former way. I was> just wondering under what circumstances importing should be done this> way?That was me. I nest imports quite frequently in Jython code where the first import of a module is fairly expensive in time. Putting the import in the function that needs it delays the import and perhaps the module won't be imported at all.import is an executable statement. When it runs, the interpreter first looks to see if the module has already been imported. If so, the existing module is bound to the import name in the current namespace. If the! module has not yet been imported, it is loaded *and executed*, then bound to the name in the current namespace.So if module A imports B which imports C and D, then importing A will also load and execute B, C and D. If any of these are time-consuming you may want to defer them.I found with my Jython programs that I could shorten start-up time quite a bit by deferring some imports until they were needed.Another reason for the nested style of imports is to resolve problems with circular imports. There are some subtle problems that can occur when A imports B and B imports A. By nesting one of the imports you can defer it and sometimes avoid the problem. In this case I think removing the circular import is a much better solution - circular dependencies are evil!Kent> > Cheers,> Dan> > ___> Tutor maillist - Tutor@python.org> http://mail.python.org/mailman/
[Tutor] pylibpcap
Hello List I need to use pylibpcap. I am looking for any documentation at all, tutorial would be nice. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor