Re: [Tutor] using a function as a dictionary value?
Hey Justin, Tricky one this.. as far as I know, and I'm a beginner myself, a dictionary stores a reference to the function, not the actual function. So - > command = {'1': spam(), > '2': breakfast(), > '3': bridgekeeper() > } Try this instead - command = {'1': spam, '2':breakfast, '3': bridgekeeper} and > select = raw_input('Chose an option [1|2|3]: ') > > options = ['1', '2', '3'] > > if select in options: > command[select] change this to - select = raw_input('Chose an option [1|2|3]: ') if select in command.keys(): command[select]() That one had me going round in circles when I first met it. AFAIK, everything is stored in dictionaries apparently. If you have a function called 'dude()' you could probably call it as a dictionary of 'dude' from the namespace... Standard disclaimer - Someone more knowledgable would probably be along shortly to point out a simpler, elegant way to do it, but my way works. Mostly. HTH Liam Clarke > # > def spam(): > print 'Hello world' > > def breakfast(): > print 'Spam, Spam, Chips, and Spam' > > def bridgekeeper(): > print 'Ask me your questions, Bridgekeeper. I am not afraid.' > > select = raw_input('Chose an option [1|2|3]: ') > > options = ['1', '2', '3'] > > if select in options: > command[select] > > else: > print 'Selection not recognized.' > # > 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Difference between for i in range(len(object)) andfor i in object
Good luck trying to find a decent Python book for beginners. I haven't been able to source Alan Gauld's book yet, (I'm saving for Amazon's shipping... I live in the Antipodes.), but afaik that's about the best one out, if his online tutorial (which I highly recommend Kumar, link at end.) is indicative. I have the O'Reilly Python in a Nutshell beside me, but it's a reference only, and sometimes a confusing reference. Took me ages to figure out what exactly serialization/deserialization meant in reference to pickling. For my intents, tunring it into a saved thing. Sure, maybe in binary format or something. But yeah, once I'd worked my way through 80% of Alan's tutorial, I found this list, and I'd attribute 75% of my progress since the tutorial to the amazing help I've received here, and the other 25% to messing around in the interpreter or writing code and trying to make it work. Thing is, for people like me, you generally either don't know that a question is a dumb one until someone tells you the answer, (the 'of course' moment), or until 5 minutes after you emailed your query, you find the answer you were looking for... Kumar, if I may, I have some recommendations for resources to check out. http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/index.htm In my opinion, the best way to familiarise one's self with the fundamentals of Python. http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor A searchable archive of the Tutor group http://www.ibiblio.org/obp/thinkCSpy/index.htm A good tutorial on writing code, which happens to use Python Good luck, Liam Clarke On Sun, 12 Dec 2004 09:31:15 -0700, Bob Gailer <[EMAIL PROTECTED]> wrote: > At 08:27 AM 12/12/2004, kumar s wrote: > >Thank you for clearing up some mist here. In fact I was depressed by that > >e-mail > > I appreciate Alan's response and yours. I forgot that this was the Tutor > list, as I see so many Python e-mails it is easy to get confused. Please > resume seeing this list and me as resources. I regret my comments that led > to your depression. > > >because there are not many tutorials that clearly explains the issues that > >one faces while trying to code in python. > > So what can we do as a community to provide tutorials that help students > like you to more easily "get it". Can you give us some ideas as to what is > missing? Also I 'd be interested in knowing a bit about your academic > background and field of study. Would you give us a brief CV? > > I taught programming for the Boeing Company. I always wondered "what are > these students doing here? Why don't they just read the book?" That's how I > learned almost everything I know about programming. So it can be hard for > me to understand your struggle. > > Nuf said for now... > [snip] > > Bob Gailer > [EMAIL PROTECTED] > 303 442 2625 home > 720 938 2625 cell > > > > ___ > Tutor maillist - [EMAIL PROTECTED] > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
[Tutor] using a function as a dictionary value?
When I run this, regardless of which option I select all three functions are called. Is there a way I can do this where only the option selcted is called? Im using 2.3.3 if that matters any. Thanks. # def spam(): print 'Hello world' def breakfast(): print 'Spam, Spam, Chips, and Spam' def bridgekeeper(): print 'Ask me your questions, Bridgekeeper. I am not afraid.' select = raw_input('Chose an option [1|2|3]: ') options = ['1', '2', '3'] command = {'1': spam(), '2': breakfast(), '3': bridgekeeper() } if select in options: command[select] else: print 'Selection not recognized.' # >>> chose an option [1|2|3]: 3 Hello world Spam, Spam, Chips, and Spam Ask me your questions, Bridgekeeper. I am not afraid. >>> regards, Justin --- ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] using a function as a dictionary value?
Liam Clarke wrote: Hey Justin, Tricky one this.. as far as I know, and I'm a beginner myself, a dictionary stores a reference to the function, not the actual function. Yes. In fact this is a good way to think about all variables in Python. A variable stores a reference to a value, not the value itself. I think of variables as somehow pointing at the value. Some people like to think of the variable as a sticky note stuck on the value with its name. Pythonistas say that the name is 'bound' to the value; the assignment 'x = 2' binds the name 'x' to the value '2'. The *wrong* way to think about variables in Python is to think of them as containers that hold a value. This is appropriate for some languages but it is not a helpful model for Python. So - command = {'1': spam(), '2': breakfast(), '3': bridgekeeper() } Try this instead - command = {'1': spam, '2':breakfast, '3': bridgekeeper} Yes. The difference is, you are storing a reference to the actual function object, rather than the result of calling the function. >>> def foo(): ... return 3 ... The function name is actually a variable which is bound to a function object. When you use the bare variable name, you are referring to this object: >>> foo On the other hand when you use the function name with parentheses, you call the function. The value of this expression is the return value of the function. >>> foo() 3 Here is a dictionary with both usages: >>> d = { 'foo':foo, 'value':foo() } >>> d {'foo': , 'value': 3} If you put foo in the dict, you have access to the function. If you put foo() in the dict, you have access to the result of calling the function. If I store a reference to the function, I can retrieve it and call it like this: >>> d['foo']() 3 Kent if select in options: command[select] change this to - select = raw_input('Chose an option [1|2|3]: ') if select in command.keys(): command[select]() That one had me going round in circles when I first met it. AFAIK, everything is stored in dictionaries apparently. If you have a function called 'dude()' you could probably call it as a dictionary of 'dude' from the namespace... Yes, under the hood, binding a name to a value turns into adding a mapping to a special dictionary. For variables with global scope, you can access this dictionary with the globals function. Both the dict d and the function foo are in my globals: >>> globals() {'__builtins__': , '__name__': '__main__', 'foo': , '__doc__': None, 'd': {'foo': on foo at 0x008D6670>, 'value': 3}} >>> globals()['d'] {'foo': , 'value': 3} Standard disclaimer - Someone more knowledgable would probably be along shortly to point out a simpler, elegant way to do it, but my way works. Mostly. Actually you got the code right :-) I just thought the explanation needed a little fleshing out. Kent ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] OT?: how to google just the 2.4 tutorial?
> I know how to limit google search results to a single site, but is it > possible to google just one section of a site? Can't speak for Google but... > I'd like to be able to search just the 2.4 tutorial, > http://www.python.org/doc/2.4/tut/tut.html > Possible? And if so, how to? Have you tried using the Python site search tool, it covers the whole of python.org but thats much narrower than a general web search on Google... By typing: tutorial lists I got the first 5 hits from the tutor... OTOH By just typing: python tutorial lists into Google the first two hits were both from the official tutorial so plain google works pretty well too. Alan G. ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] listing all combinations of elements of a list
> def combination(items) > list = [] > for i in range(0,len(items)): >for j in range(0,len(items)): for i in items: for j in items: Is both shorter and faster - no len() function calls. Or if you want to use indices: size = len(items) # only calculate once, it won't change! lst = []# don't use builtin function names for variables for i in range(0,size) for j in range(i+1,size) lst.append() return lst That saves a lot of len() calls and a comparison. Also it avoids iterating over the whole list each time. > My problems with this code being that a) code I write is usually pretty > inefficient, b) it doesn't extend to subsets of size > 2, and c) it uses > nested loops, which I have gathered from some previous discussions on > this list to be less than ideal. I've tidied up a little but I think nested loops are a necessary evil in this case - although somebody is sure to prove me wrong! :-) HTH, Alan G. ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: [ANN] RUR: a Python Learning Environment (alpha)
This looks like a very nice effort -- I am trying to get it running, since I am working with some other newbies to learn more Python. I wish there were a link from http://rur-ple.sourceforge.net/index.html to the download page! I will fix that; thanks. And I am not sure which of the downloaded files to run. I thought maybe WorldDisplay.py, or RURmain.py? Oops! RURmain.py Anyway, I really like the concept, and the screenshots look intriguing. You have a nice writing style in English, by the way -- I think kids will pick right up on the "fix the robot" metaphor. Thanks! Andre ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
[Tutor] Problems with unsigned integers
Hello everyone! I'm having problems with signed/unsigned (32bit) integers in python. Example code: seq = 0L seq = socket.ntohl(struct.unpack("L", data[38:42])[0]) print seq This sometimes produces a negative output, how is that possible since I booth initialized seq with "0L" and also specified "L" in unpack()? -L.C ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problems with unsigned integers
On Mon, 13 Dec 2004 12:43:17 -0500, QoD SEC <[EMAIL PROTECTED]> wrote: > I do not believe that python has anything like signed and unsigned > integers. The 'L' after an integer makes the number a type long (which > is not the same as C's long). Also in your code you do this seq = > socket.ntohl(struct.unpack("L", data[38:42])[0]) which overwrites > whatever you assigned it before and returns an integer, in your case a > -1 which might be that the functions is returning an error. > Thanks for the reply. I forgot to say that I have also tried without the socket.ntohl(), making sure that it's not what messes things up. Python clearly has _some_ kind of sense for signed vs unsigned if you check the list* of available fmt-characters. And the values I get are mixed high ["correct"] values and negative values, so error return codes does not seem to be an option. * http://docs.python.org/lib/module-struct.html -L.C ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: [ANN] RUR: a Python Learning Environment (alpha)
Can't get it running -- it keeps saying: Traceback (most recent call last): File "C:/source/RUR/RURmain.py", line 28, in ? messenger.loadImages() # load them up here after initialising Handlers File "C:\source\RUR\messenger.py", line 27, in loadImages HIT_WALL_IMAGE = wxImage('ouch2.png').ConvertToBitmap() File "C:\Python23\Lib\site-packages\wx\_core.py", line 2282, in ConvertToBitmap return _core_.Image_ConvertToBitmap(*args, **kwargs)wx._core.PyNoAppError: The wx.App object must be created first! Ron ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] using a function as a dictionary value?
Thanks Liam and Kent! Regards, Justin On Mon, 13 Dec 2004 07:57:45 -0500, you wrote: > >Liam Clarke wrote: >> Hey Justin, >> >> Tricky one this.. >> >> as far as I know, and I'm a beginner myself, a dictionary stores a >> reference to the function, not the actual function. > >Yes. In fact this is a good way to think about all variables in Python. A variable stores a >reference to a value, not the value itself. I think of variables as somehow pointing at the value. >Some people like to think of the variable as a sticky note stuck on the value with its name. >Pythonistas say that the name is 'bound' to the value; the assignment 'x = 2' binds the name 'x' to >the value '2'. > >The *wrong* way to think about variables in Python is to think of them as containers that hold a >value. This is appropriate for some languages but it is not a helpful model for Python. > >> So - >> >> >>>command = {'1': spam(), >>>'2': breakfast(), >>>'3': bridgekeeper() >>>} >> >> >> Try this instead - >> >> command = {'1': spam, '2':breakfast, '3': bridgekeeper} > >Yes. The difference is, you are storing a reference to the actual function object, rather than the >result of calling the function. > > >>> def foo(): >... return 3 >... > >The function name is actually a variable which is bound to a function object. When you use the bare >variable name, you are referring to this object: > >>> foo > > >On the other hand when you use the function name with parentheses, you call the function. The value >of this expression is the return value of the function. > > >>> foo() >3 > >Here is a dictionary with both usages: > >>> d = { 'foo':foo, 'value':foo() } > >>> d >{'foo': , 'value': 3} > >If you put foo in the dict, you have access to the function. If you put foo() in the dict, you have >access to the result of calling the function. If I store a reference to the function, I can retrieve >it and call it like this: > >>> d['foo']() >3 > >Kent > >>>if select in options: >>>command[select] >> >> >> change this to - >> >> select = raw_input('Chose an option [1|2|3]: ') >> >> if select in command.keys(): >> command[select]() >> >> >> >> That one had me going round in circles when I first met it. >> AFAIK, everything is stored in dictionaries apparently. If you have a >> function called 'dude()' you could probably call it as a dictionary of >> 'dude' from the namespace... > >Yes, under the hood, binding a name to a value turns into adding a mapping to a special dictionary. >For variables with global scope, you can access this dictionary with the globals function. Both the >dict d and the function foo are in my globals: > > >>> globals() >{'__builtins__': , '__name__': '__main__', 'foo': 0x008D6670>, '__doc__': None, 'd': {'foo': on foo at 0x008D6670>, 'value': 3}} > >>> globals()['d'] >{'foo': , 'value': 3} > >> >> Standard disclaimer - >> >> Someone more knowledgable would probably be along shortly to point out >> a simpler, elegant way to do it, but my way works. Mostly. > >Actually you got the code right :-) I just thought the explanation needed a little fleshing out. > >Kent >___ >Tutor maillist - [EMAIL PROTECTED] >http://mail.python.org/mailman/listinfo/tutor regards, Justin --- You may have noticed, Im not all there myself. -Cheshire Cat ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problems with unsigned integers
It seems that ntohl doesn't understand about unsigned values, at least on Win32: Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from struct import pack, unpack >>> pack('L', -1) '\xff\xff\xff\xff' >>> unpack('L', '\xff\xff\xff\xff') (4294967295L,) >>> from socket import ntohl >>> ntohl(4294967295L) -1 Kent Loptr Chaote wrote: Hello everyone! I'm having problems with signed/unsigned (32bit) integers in python. Example code: seq = 0L seq = socket.ntohl(struct.unpack("L", data[38:42])[0]) print seq This sometimes produces a negative output, how is that possible since I booth initialized seq with "0L" and also specified "L" in unpack()? -L.C ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problems with unsigned integers
On Mon, 13 Dec 2004 13:27:25 -0500, Kent Johnson <[EMAIL PROTECTED]> wrote: > It seems that ntohl doesn't understand about unsigned values, at least on > Win32: > Wow, I've never actually considered using the interpreter/CLI like that. Thank you! I'm writing my own u_ntohl() now which checks to see if the socket-module ntohl()-function does something with the value, and if so reorders 0xAABBCCDD to 0xDDCCBBAA and if not it returns same value as the one sent as argument. This should be enough, right? -L.C PS. Obviously I was wrong regarding ntohl() not being the source of the error, and I'm not sure any longer how I came to the conclusion that it wasn't. ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: [ANN] RUR: a Python Learning Environment (alpha)
This is weird (to me, anyways) as it works well on my computer. However, I remember that I had to create "loadImages()" to initialize the handlers early on, otherwise it was complaining that it couldn't "ConvertToBitmap". I'll have to see if I can move this statement elsewhere; I will reply privately when I do it (so as not to clutter the list) and will report to the list when the problem is solved. Just to clarify: are you using wxpython 2.4.x under Windows? Andre == Can't get it running -- it keeps saying: Traceback (most recent call last): File "C:/source/RUR/RURmain.py", line 28, in ? messenger.loadImages()# load them up here after initialising Handlers File "C:\source\RUR\messenger.py", line 27, in loadImages HIT_WALL_IMAGE = wxImage('ouch2.png').ConvertToBitmap() File "C:\Python23\Lib\site-packages\wx\_core.py", line 2282, in ConvertToBitmap return _core_.Image_ConvertToBitmap(*args, **kwargs) wx._core.PyNoAppError: The wx.App object must be created first! Ron -- next part --- ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] cgi with system calls
Nik wrote: hi, I'm trying to write a python cgi script that can control certain processes on my server, but I'm having some trouble. The script is; #!/usr/bin/python import cgitb; cgitb.enable() print "Content-type: text/plain\n\n" You may need explicit \r\n here, I'm not sure: print "Content-type: text/plain\r\n\r\n" Kent import os cmd = "/bin/ps" status = os.system(cmd) print status which seems straight forward, but I get a server error, and malformed header from script. Bad header= PID TTY TIME CMD: appears in the apache logs. The PID TTY etc indicates it's getting the ps response, but why won't it display (even with text/plain)? Ultimately I'll have the content type as html, and I'm going to preprocess the output of ps so it probably won't cause any problems, but I just don't understand why this isn't working in its simple form? btw, the final idea is to list the processes corresponding to a certain name, and allow users to stop them or create new ones. I'm assuming this should be do-able? nik ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
[Tutor] Opening and reading .cvs files in Python
Hi, I want to find out how to open a .cvs file on a remote Windows machine and get file to my local linux folder. Any help would be appreciated. -- Johan -- This E-Mail has been scanned Enjoy your day ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] cgi with system calls
no luck I'm afraid. Also, to make it even more annoying, omitting the os call and going for #!/usr/bin/python import cgitb; cgitb.enable() print "Content-type: text/plain\n\n" import os status = """PID TTY TIME CMD 3649 pts0 00:00:00 su 3652 pts0 00:00:00 bash 5197 pts0 00:00:00 ps """ print status works fine. I've already half a dozen other scripts happily querying a database but this is the first one to have an error outside the usual brain fart stuff. nik Kent Johnson wrote: Nik wrote: hi, I'm trying to write a python cgi script that can control certain processes on my server, but I'm having some trouble. The script is; #!/usr/bin/python import cgitb; cgitb.enable() print "Content-type: text/plain\n\n" You may need explicit \r\n here, I'm not sure: print "Content-type: text/plain\r\n\r\n" Kent import os cmd = "/bin/ps" status = os.system(cmd) print status which seems straight forward, but I get a server error, and malformed header from script. Bad header= PID TTY TIME CMD: appears in the apache logs. The PID TTY etc indicates it's getting the ps response, but why won't it display (even with text/plain)? Ultimately I'll have the content type as html, and I'm going to preprocess the output of ps so it probably won't cause any problems, but I just don't understand why this isn't working in its simple form? btw, the final idea is to list the processes corresponding to a certain name, and allow users to stop them or create new ones. I'm assuming this should be do-able? nik ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: [ANN] RUR: a Python Learning Environment (alpha)
This looks like a very nice effort -- I am trying to get it running, since I am working with some other newbies to learn more Python. I wish there were a link from http://rur-ple.sourceforge.net/index.html to the download page! And I am not sure which of the downloaded files to run. I thought maybe WorldDisplay.py, or RURmain.py? Anyway, I really like the concept, and the screenshots look intriguing. You have a nice writing style in English, by the way -- I think kids will pick right up on the "fix the robot" metaphor. Which program do I start? Ron ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
[Tutor] Non-escaped utf-8 rendering in the interactive shell under XP?
Hi folks, Being a Linux guy, I don't know my way around Windows software too well. I've been trying to help some friends learn a bit of Python, and they use OSX and XP. OSX is close enough to Linux that I've not run into many barriers, but I'm having a specific problem with the XP users: Is there an IDE out there that supports Unicode (utf-8) text? I've set sitecustomize.py to 'utf-8', such that sys.getdefaultencoding() will return 'utf-8', and everything seems to be working ok interms of reading, writing, and processing data in utf-8. The problem is that the text itself is escaped in the interactive shell, rather than being rendered. It's not a font thing, since if they write out the data to a file and open it in a browser, the text is readable. The Gnome terminal under Linux seems to do this fine once I've made that change in sitecustomize.py, and OSX seems to behave similarly. I've suggested my friends try SciTE, Idle, and Activestate's PythonWin, and as far as I can tell none of these IDEs solve the problem. The people I'm trying aren't going to be interested in wading into something like any flavor of Emacs or vim. After all, they want to learn Python because it's friendly, and those editors are great, but they're not friendly. Am I missing any options or misunderstanding any of these IDEs? Thanks kindly, Patrick ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor
[Tutor] Re: How to launch multiple processes from script?
> I'm working my way through the sockets module. To test my simple > server and clients, I'd like a way to launch the server and multiple > clients from one script or batch file,all running simultaneously. Each > server/client should run as it's own process and have a console > window. I've briefly played with spawn and forkpty with no success. > Running WinXP right now. > > I am hoping that there is something as simple as this psuedo code: > > for i in range(1..10): > run_with_console("client.py " + arg0[i] +" " +arg1[i]) > > My question is what is pythonese for run_with_console? > > Thanks, > Mike There is a Windows command called 'start' which will start an application and then exit. So you can do the required thing this way: for i in range(10): os.system("start python client.py " + arg0[i] + " " + arg1[i]) On my system it works just the way you want. ___ Tutor maillist - [EMAIL PROTECTED] http://mail.python.org/mailman/listinfo/tutor