[Tutor] Displaying picture and Text
Hi - I am running Python 2.6.6 on my HP netbook with Windows 7. The default picture viewer is set to HP Photo Viewer. I am working on a part of my python program where a picture is supposed to display with a few lines of text below it. Ideally, I would like this to stay on the screen for a short period of time (2 minutes?) but I am using raw_input() for now. I imported the Image library and when I run the program below, it brings up a window (stdout or python?) with cursor flashing for a few seconds and then the HP Photo Viewer comes up with the picture, I close this window and then my text comes up in a python window. import Image fhdl = Image.open("C:\Users\StarShip\PyProgs\\bbsparkle.gif") fhdl.show() print "here is some test text test text test text" print "here is some more test text test text test text" print "here is even more of some test text test text test text" raw_input("press any key to continue") How do I get any picture to display on half a screen then my print text display below that and stay on screen for 2 or 3 minutes before I call another function that will redraw the screen anyway - it will be interactive text responses with the user. Also this is a test .gif file, I may want to just edit the source file and change this to a .jpg. I don't want to change the system defaults for this, maybe for the picture itself if that is necessary. Thanks Patty ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Displaying picture and Text
Thank you for all the replies - I think I will want to use Tkinter since it also has the timer I am looking for and I do have one book that has a big chapter on using Tkinter. If I find that I am having trouble understanding Python GUI programming. I may be able to copy some code from the book or I will use a workaround of skipping the picture part temporarily, I am sure with time it will all come together. I am liking Python programming! I pretty much consider myself a C programmer plus know several other programming and database querying languages. Patty ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Displaying picture and Text & Downloads
I just realized I did the same thing - must have hit reply to one instead of reply to all :} I had a followup question for you all - and would like to know the answer to Alan's question about print quality - below - Patty - Original Message - From: "Patty" To: "Alan Gauld" Sent: Thursday, November 04, 2010 11:14 AM Subject: Re: [Tutor] Displaying picture and Text Yes, I would like to know this, I want this function to be really modular and I thought of something else. If my solution turns out to be using Tkinter functions only then wouldn't that mean I downloaded and am 'import'ing the Image library for nothing? This might mean the second addon library I download the source and documentation for. So how are people keeping their customized system organized? I could come up with all sorts of scenarios of losing track of libraries, having too many you never use, and doc you never use, etc. Patty - Original Message - From: "Alan Gauld" To: Sent: Thursday, November 04, 2010 10:39 AM Subject: Re: [Tutor] Displaying picture and Text "Alan Gauld" wrote fhdl = Image.open("C:\Users\StarShip\PyProgs\\bbsparkle.gif") fhdl.show() The Tkinter PhotoImage object can display jpg. I can't recall if it does gifs. Sorry I got that wrong, it can display gifs but not jpgs (despite the fact that jpgs are used more often for photos than gifs!) So you will need to convert the jpg to a gif - which might lose a lot of quality! Anyone know of a way to get decent quality in a Tkinter image? Is there any support in PIL itself? Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Displaying Pictures & Text
Hi Alan - I tried using ImageTk from the PIL library to display jpegs (and hopefully any picture type) instead of just gif as you suggested below. I read online that these these types of programs should be run from executables not in the interpreter but it crashes and I can't read the error. Here is the program: import Image import ImageTk fhdl = Image.open("C:\Users\StarShip\PyProgs\SuitGirl.jpg") ImageTk.PhotoImage(fhdl) Tested in interpreter and get the following error. I included Image.show() to be sure pic could be displayed and it did come up in HP Photo Viewer just like the gif file did and I tried the PhotoImage() after I got the cursor back Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import Image >>> import ImageTk >>> fhdl = Image.open("C:\Users\StarShip\PyProgs\SuitGirl.jpg") >>> fhdl.show() >>> ImageTk.PhotoImage(fhdl) Traceback (most recent call last): File "", line 1, in File "C:\Python26\lib\site-packages\PIL\ImageTk.py", line 113, in __init__ self.__photo = apply(Tkinter.PhotoImage, (), kw) File "C:\Python26\lib\lib-tk\Tkinter.py", line 3285, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "C:\Python26\lib\lib-tk\Tkinter.py", line 3226, in __init__ raise RuntimeError, 'Too early to create image' RuntimeError: Too early to create image >>> >> > "Alan Gauld" wrote in message news:ib270l$p3...@dough.gmane.org... > > "Patty" wrote > >> I had a followup question for you all - and would like to know the >> answer to Alan's question about print quality - below - > > > A Google search led me to this page which seems to offer a solution > using PIL anmd a module called ImageTk: > > http://codeidol.com/python/python3/A-Tkinter-Tour,-Part-1/Viewing-and-Processing-Images-with-PIL/ > > I've never tried it so I'll be interested to hear if it works for > you... > > Alan G., > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Displaying Pictures & Text
Thank you! I was getting confused, I thought I wouldn't need Tkinter. I thought Tkinter is yet another addon library besides PIL. Am I right or wrong? So I actually need both? And this brings me back to my _other_ question which is that as individuals go about downloading these addon libraries and their doc, how do you organize this on your computer system? I can imagine that in corporations there are guidelines for this, but I am wondering what you all do? You could end up with addon libraries, doc and Readmes all over your hard disk Patty - Original Message - From: Wayne Werner To: Patty Cc: tutor@python.org Sent: Saturday, November 06, 2010 7:16 AM Subject: Re: [Tutor] Displaying Pictures & Text On Fri, Nov 5, 2010 at 11:53 PM, Patty wrote: Hi Alan - I tried using ImageTk from the PIL library to display jpegs (and hopefully any picture type) instead of just gif as you suggested below. I read online that these these types of programs should be run from executables not in the interpreter but it crashes and I can't read the error. Here is the program: import Image import ImageTk fhdl = Image.open("C:\Users\StarShip\PyProgs\SuitGirl.jpg") ImageTk.PhotoImage(fhdl) Before you convert to an ImageTk, you need to first create a toplevel window: import Image import ImageTk import Tkinter as tk root = tk.Tk() #put your code here And that should work. You'll still have to add the widgets and what-nots so you can present your image, but in order to create an image with ImageTk, you need to have a toplevel window created. That's what this is telling you Traceback (most recent call last): File "", line 1, in File "C:\Python26\lib\site-packages\PIL\ImageTk.py", line 113, in __init__ self.__photo = apply(Tkinter.PhotoImage, (), kw) File "C:\Python26\lib\lib-tk\Tkinter.py", line 3285, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "C:\Python26\lib\lib-tk\Tkinter.py", line 3226, in __init__ raise RuntimeError, 'Too early to create image' RuntimeError: Too early to create image HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Programs for Newbies?
For my first program, I liked creating a number game, simple and where the user made a choice. That was good for learning how to interact with the user. The raw_input() function. Patty - Original Message - From: "Steven D'Aprano" To: Sent: Friday, November 05, 2010 10:55 PM Subject: Re: [Tutor] Programs for Newbies? Danyelle Davis wrote: Hi all, Any suggestions for a newbie to program while learning python? I am new to programming and python. Here's a few suggestions: Write a program that asks the user to enter a word, then counts how many vowels and consonants are in the word. Write a program that asks the user for a list of numbers, separated by spaces or commas, and then calculated the average. A program that prints the time. A program that prints how many days to go until their next birthday. A program that counts how many palindrome numbers there are between two other numbers. (A palindrome number is one like 12321, or 473374.) A program that sings (well, prints) the "There were ten in the bed" song. If you don't know it, it is a children's song. You start off by holding up ten fingers, or you can use actual children. You don't have to start with ten. Then you sing: There were ten in the bed, and the little one said, Roll over! Roll over! And they all rolled over and ONE FELL OUT! There were nine in the bed, and the little one said, Roll over! Roll over! And they all rolled over and ONE FELL OUT! There were eight in the bed, and the little one said, ... Well you get the idea. Eventually you've left with only the little one left, and the song ends: There was one in a bed, and the little one said Good night! -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Displaying Pictures & Text
Thanks for the explanation. I will go ahead and trying using these functions in my program. Patty - Original Message - From: "Alan Gauld" To: Sent: Saturday, November 06, 2010 10:55 AM Subject: Re: [Tutor] Displaying Pictures & Text "Patty" wrote I thought I wouldn't need Tkinter. I thought Tkinter is yet another addon library Tkinter is the standfard GUI toolkit for Python and as such comes as part of the standard library. (Although you do have to compile Python with that option enabled in some Linux distros) So I actually need both? Yes PUIL is for transforming the graphics and creatnf the image object. Tkinter can then displaty that image object in a GUI. And this brings me back to my _other_ question which is that as individuals go about downloading these addon libraries and their doc, how do you organize this on your computer system? Most common add-on libraries will install themselves in the site-packages dirtectory structure under your Python root folder So they remain fairly well organized. Some thoird party tools are kist a single python module and you have to decide where to put it yourselfd. In my case thats usually in site-packages too. This does mean that when you upgrade you have to decide which, if any, of your site-package files to migrate to the new version and which to re-download. I usually opt for the re-download route just to be safe. Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 81, Issue 35
Hi - I just wanted to comment that my Windows XP system hasn't found any threats like this coming from the Python list emails. I also have a netbook with Windows 7 Starter and no problems there either. I am using AVG 9.0.869 on both systems which is *Great* for security and if a threat is found, it will give you the email with just the header and a note in the body that AVG didn't allow the message through because it detected a virus or malicious something or other. Patty - Original Message - From: To: "tutor" Sent: Friday, November 12, 2010 7:05 AM Subject: Re: [Tutor] Tutor Digest, Vol 81, Issue 35 Hi Joel, To start with, I sincerely appreciate your concern and I am deeply sorry your computer is so infected. Having said that, I think it is unfair to pile all the blames and as a matter of fact, any at all, on this group. That is very unfair to say the least. I don't have an idea of how long you have been on this mailing list but I am quite sure you are not the first to subscribe and you can't be the last. It therefore bothers me that you are the onlt person I have heard say such a terrible thing about this group despite all measures in place to avoid sending malicious elements. I hope you are aware this group doesn't allow attachments except you are suggesting the viruses you are talking about are the letters and numerals in the mails. That then underscores your knowledge as an IT person. Second, you had an option to stick with your PDF and google stuff before coming on this mailing list. If you are all of a sudden attached to your PDF again, it ia matured enough to unsubscribe and be thankful for the things you have learnt in here. While I hope you would have a change of mind and apologise for your very harsh and false accusations, I hope you would also understand that everybody here despite our different backgrounds have gone thus far because we play by the rules and we are interested in not only learning python but teaching too and making everyone smile. Have a great day. Regards Sent from my BlackBerry wireless device from MTN -Original Message- From: Wangolo Joel Sender: tutor-bounces+delegbede=dudupay@python.org Date: Fri, 12 Nov 2010 14:45:21 To: Subject: Re: [Tutor] Tutor Digest, Vol 81, Issue 35 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] program hangs in while loop using wx.yield
Hi Terry - I am an alumni of UCSC (University of California, Santa Cruz) and live really close so I can request books throughout the UC system just like you describe and there is no limit - or maybe an extremely high limit - to the number of books I can check out from McHenry Library. It is so worth paying alumni dues! There is no way they would transport books to the public library to make it easier for people though - not with the way the city and the university feel about each other :} And discounts on courses through the University Extension program. That is how I found out about - and took - the online Python for Programmers course. Though I wasn't really happy with it and went on to listen to the Google website video - that guy was very clear and helpful I forgot his name. And then I went through Alan Gauld's tutorial which also helped. By coincidence I am still working on my own function where I want to display a picture and some text and have a timer so that it stays on screen for a specific amount of time and then I go on to close that out and redraw the screen. I am working with the Tkinter documentation and trying to understand. I tried a couple tests just adding a few lines to my own program that didn't accomplish exactly what I want, so planning to type in very simple examples from the doc, observe that and then go back to my own code. If I just can't figure out how to do this with Tkinter and the Python Imaging Library, is 'wxPython' the additional software I would want to install and try with? Is its purpose to make GUI event programming easier (that would mean the defaults provided are difficult, right? So I shouldn't feel bad about being confused?) If so, can someone explain these additional software packages out there? I mean are they coming from some third companies? And why? If the software is free. I'm not understanding the history or business part of these Python modules and libraries. Isn't there one organization who is discussing or approving standards for this language? Regards, Patty - Original Message - From: "Terry Carroll" To: Sent: Monday, November 15, 2010 11:37 PM Subject: Re: [Tutor] program hangs in while loop using wx.yield On Sun, 14 Nov 2010, Alex Hall wrote: Is there a basic tutorial for this sort of thing? Chapter 3 ("Working in an event-driven environment") of the book "wxPython in Action" is a pretty good tutorial on event-driven GUI programming in wxPython. The book in general is pretty good; I no longer buy many computer books, but this one was worth it. If you don't want to buy it, if you're in the U.S., you can go to http://www.worldcat.org/oclc/67122432 and plug in your zip code to see if a library near you[1] has it. [1] or a library that has inter-library loan arrangements with a library near you. I'm currently reading "Essential SQLAlchemy," courtesy of the San Diego State University library. My local library (San Jose Public Library) borrowed it from SDSU and then lent it to me. It's kind of cool that one library will send a book 400 miles to another, just because I'm too cheap to buy a copy and asked for it. Apologies to anyone at SDSU who's learning SQLAlchemy and wondering why they can't find this book in their library. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] mod_python & mysqldb problem
Hi! I'm new to python and MySQl and have problems trying to figure out what is wrong with my code. I have two files: ***control.py*** #!/usr/bin/python import MySQLdb def addpercent(mp, lp): conn = MySQLdb.connect(host = "localhost", user = "root", passwd = "",db ="my_db") cursor = conn.cursor() cursor.execute (""" UPDATE targets SET mario_percent = %d, lizard_percent = %d WHERE target_name = 'anyname' """, (mp, lp)) db.commit() cursor.close() db.close() ***controlcenter.html** Ants Control Center mario: lizard: ** This is what i found in error_log [Thu Feb 23 13:08:07 2006] [notice] mod_python: (Re)importing module 'mod_python.publisher' [Thu Feb 23 13:08:07 2006] [notice] mod_python: (Re)importing module 'control' with path set to '['/var/www/html/mptest']' [Thu Feb 23 13:08:08 2006] [notice] child pid 6405 exit signal Segmentation fault (11) There is no reference to php in the httpd.conf file. Someone had told me that that could be the problem. I'd appreciate your help. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] mod_python & mysqldb problem
Hi Danny, I downloaded the latest version of mysqldb and my code worked. btw, I changed it to %s instead of %d. Thanks! Patty ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] mod_python & mysqldb problem
> > That's great news! Does the whole thing work now, including the > integration with mod_python? Hi Danny, Yes, everything works now. The problem was the mysqldb copy I had. I also noticed that i had made a mistake by writting > db.commit() > db.close() instead of: conn.commit() and conn.close() Thanks again! Patty ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] html and mod_python
Hi! I created a form in a python file that takes values selected from 6 different drop down boxes: for target in all_targets: s = s + "" s = s + "" % target s = s + "" for host in hosts: if target in ants_map[host]: s = s + printbox() else: s = s + printemptybox() s = s + """""" s = s + "" My printbox method contains the following: def printbox(): tag = """ - 0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100% """ return tag When the values are entered, my program stores them into a database. Everything worked well, but now I have been asked to retain the values selected in the drop down boxes. This means that when I open the web page, the drop down boxes should display the recent values entered. I'm not sure how to do it, and I'm really hoping that someone can point me to the right direction. Thanks, Patty ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] html and mod_python
Hi again! result[0] is the value i got from the database. I tried the following piece of code and got : "TypeError: not enough arguments for format string" if result [0] in range(0, 101, 10): selected_value = result[0] else: selected_value = '-' tag = """ %s - 0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100% """ % (selected_value,selected_value) return tag What am I doing wrong? Thanks, Patty ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] html and mod_python
> So, replace all the 10%, 20% etc in your string > with 10%% and 20%%. > Thanks That fixed it all. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] html and mod_python
Hi, Can you please give me a quick example of how to do this: > Then change printbox() to create the > tag using a loop over the value. For each value, check to see if it is > the same as the value passed in and generate the appropriate option tag. The way i have it right now is: tag = """ %s - 0%% 10%% 20%% 30%% 40%% 50%% 60%% 70%% 80%% 90%% 100%% """ % (selected_value, selected_value) Although it does what i want, I don't like the way the value is display. Thanks, Patty ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] html and mod_python
> Can you please give me a quick example of how to do this: Nevermind. I figured it out. Thanks anyway :-) Patty ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Problems when displaying numbers
Hi: >it would be really helpful to see an example of 'result' before and >after the call to calc_numbers() as well as the code for calc_numbers if >possible. An example of result before the call to calc_numbers is: [50L, -1, 1, -1] an example after the call is: [50L, 25, ' ', 25] the code: def calc_numbers(alist): sum = 0 count = 0 for li in alist: # in the database, -1 is unspecified and 1 is null if li >= 0 and li != 1: sum = sum + int(li) if li == -1: count = count + 1 temp = 100 - sum if count != 0: number = temp/count else: number = temp for li, pos in enumerate(alist): if pos == -1: alist[li] = number elif pos == 1: alist[li] = '' return alist Thanks, Patricia ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] MySQLdb question
Hi, I have a data structure in a python file that looks something like this: my_map= { "host1": {"target1", "target2", "target3" }, "host2": {"target4", "target5", "target6" }, } I have a method that has two parameteres (ahost, atarget), which I want to use to retrieve data from the database. In my database each host has a column and each target has a row. The way I have it now is something like this: cursor.execute("""SELECT host1, host2, host3, host4, host5, host6 FROM targets WHERE target_name = %s """, (target)) This is very inefficient because I'm retrieving data that I don't need. Instead, I want to use the parameters in my method, but I'm not sure how to do it cursor.execute("""SELECT %s FROM targets WHERE target_name = %s """, (ahost, target)) # I tried this, but it didn't work. I also tried this, but got a error: cursor.execute("""SELECT %s FROM targets WHERE target_name = %s """ % (ahost, target)) Can anybody show me the right way to do it? Thanks, Patty ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] MySQLdb question
> > for ahost,target in my_map: > cursor.execute("""SELECT %s FROM targets > WHERE target_name in (%s) """ % (ahost, ",".join(target))) > Hi again, I'm confused :-( I'm using an old version of python (2.3.4). In my database, target_name is the name of a column, not the name of a target. Patty ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python urllib (linux)
Hi all, I'm doing some failure testing for a python script that uses urllib and urllib2 to open a web page and post data. If the server's apache is down or if I change the ip address the script is trying to contact to be a bogus address, the script handles it prefectly. When I unplug the ethernet cable from my machine (client), the script hangs. Is there a way I can implement a timeout to handle this problem? I'd appreciate any suggestions because I'm clueless. Thanks, Patty ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python urllib (linux)
Hi again, > > problem? > import socket > if not socket.getdefaulttimeout(): > socket.setdefaulttimeout(25.0) > I'm sorry I forgot to mention that I'm using python 2.2.3, and this version doesn't have those methods. Patty ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python Exercise
Hi - I just wanted to add to Mac's comment. I don't have Google mail/gmail and don't want to create a mail account with them. I was also wondering if I should just try clicking on links anyway and changed my mind and exited. Regards, Patty > On Sat, 27 Nov 2010 22:00:03 +0800 > Kok Cheng Tan wrote: > >> I created this website for practising python online: >> http://www.pyschools.com. Hope to gather feedback from people here >> who are interesting in teaching and learning python. > > Here you go with the first suggestion: remove the need to log in! > (Haven't really watched at the site content, given that I - like 99% of > the Internet users - wouldn't bother to login just to roam around a > site). > > Mac. > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to handle exceptions raised inside a function?
This is very interesting to me - the below excerpt is something I was trying to do for one of my programs and gave up on it: A fifth approach, common in some other languages, is to return some arbitrary value, and set an error flag. The caller then has to write code like this: result = function(arguments) if not last_result_error: # no error occurred print "result is", result If you do this, I will *personally* track you down and beat you to death with a rather large fish. *wink* I think I was trying to do something like thius at the end of a function I wrote- return 2 or return my_special_integer_mvar and then do something or other depending on this value once it passes back to calling function or main(). I think I used similar code as you have above. It didn't go well and also there seemed to be a problem related to where I was returning this value _to_ (where I actually placed this snippet of code like you wrote above) - a function or module I wrote or main(). So, could you expand on this for me? I would have to dig around to find the actual program I was working on. Thanks, Patty - Original Message - From: "Steven D'Aprano" To: Sent: Tuesday, November 30, 2010 1:23 PM Subject: Re: [Tutor] How to handle exceptions raised inside a function? Richard D. Moores wrote: Please take a look at 2 functions I just wrote to calculate the harmonic and geometric means of lists of positive numbers: <http://tutoree7.pastebin.com/VhUnZcma>. Both Hlist and Glist must contain only positive numbers, so I really need to test for this inside each function. But is there a good way to do this? What should the functions return should a non-positive number be detected? Is there a conventional Pythonic way to do this? There are two basic approaches to handling errors in Python: (1) Don't do any error checking at all. If the input is bad, an exception will (hopefully!) be raised. Provided you know that bad input *will* lead to an exception, and not just plausible-looking but incorrect result, this is often the simplest way. (2) If you don't trust that a sensible exception will be raised, then do your own error checking, and raise an exception. For numeric work, another approach is to return a floating point NAN ("Not A Number"). Unfortunately Python doesn't give any standard way to specify *which* NAN is returned, but you can return float("nan") to return one of them. A fourth approach, rare in Python, is to return some sort of magic value to indicate an exceptional case. Just about the only example of this I can think of is string.find(), which returns -1 to indicate "not found". A fifth approach, common in some other languages, is to return some arbitrary value, and set an error flag. The caller then has to write code like this: result = function(arguments) if not last_result_error: # no error occurred print "result is", result If you do this, I will *personally* track you down and beat you to death with a rather large fish. *wink* For what it's worth, I have a module of statistics functions (shameless plug: http://pypi.python.org/pypi/stats and http://code.google.com/p/pycalcstats -- feedback and bug reports welcome) that includes the harmonic and geometric mean. My harmonic mean looks like this: def harmonic_mean(data): try: m = mean(1.0/x for x in data) except ZeroDivisionError: return 0.0 if m == 0.0: return math.copysign(float('inf'), m) return 1/m Notice that if the data includes one or more zeroes, the harmonic mean itself will be zero: limit as x->0 of 1/x -> infinity, and 1/infinity -> 0. If the sum of reciprocals itself cancels to zero, I return the infinity with the appropriate sign. The only exceptions that could occur are: * mean will raise ValueError if the data is empty; * if an argument is non-numeric, TypeError will occur when I take the reciprocal of it. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to handle exceptions raised inside a function?
I think I understand, I will have to reread this a couple times! But I do consider myself a C programmer so that probably explains why I was trying to write code that way. And you are right 'you must inspect the global > after each call, before making the next call'. I *was* setting up the function to check on and muck with this mvar before the end where I 'return' my own thing. So for Python programming you are advising us to use one of the other four approaches to error handling and not try to do something like: call custom function, something is returned to a mvar while processing each statement, which is then examined for content and if one of three 'bad' or 'good' things are in the mvar, trying to avoid return values of [0 1 -1 2 -2] because off-the-top-of-my-head these are meaningful in various languages, so come up with 3 way-out-there-numbers-of-my-own, such as your '42'example. Then try and 'return' this from the function back to the calling function, possibly main(). Then examine return value integer and have ' if statements' doing something depending... So does this mean I am thinking through this like a C programmer? And I don't think I would be checking a variable at all using the other four ways, I would just let an error happen and let the return value be whatever it is and let the exception come up (or my custom exception handler) and handle it, instead I was trying to get right in the middle of it and force things. Also I was trying to use the return value for purposes other than error. I think what I was trying to do would be like a Case Statement really if that were supported in Python. return my_special_integer_mvar So the above will not work? If you were to try this, do you have to return digits? You can't return an mvar (and hope it doesn't change on you while going back to calling program)? Thanks for confirming my understanding or confusion as the case may be!! Patty > Patty wrote: >> This is very interesting to me - the below excerpt is something I was >> trying to do for one of my programs and gave up on it: >> >>> A fifth approach, common in some other languages, is to return some >>> arbitrary value, and set an error flag. The caller then has to write >>> code like this: >>> >>> result = function(arguments) >>> if not last_result_error: >>> # no error occurred >>> print "result is", result >>> >>> >>> If you do this, I will *personally* track you down and beat you to >>> death with a rather large fish. >>> >>> *wink* >> >> I think I was trying to do something like thius at the end of a function >> I wrote- >> >> return 2 or return my_special_integer_mvar > > That syntax won't work. However, the basic idea is (moderately) sound: > your function has a special value that means "something funny happened". > Python very occasionally uses this: > > >>> "hello world".find("z") # not found > -1 > > which you then use like this: > > result = string.find(target) > if result == -1: # special value > print("not found") > else: > print("found at position %d" % result) > > In general, this idiom is mildly disparaged in Python circles, but not > forbidden. Exceptions are usually considered better. > > However, what I'm talking about is quite different. Here's how I might > write the string find method using this (horrible) implementation: > > > # Global status flag. > find_succeeded = 0 > > def find(string, target): > global find_succeeded > if target in string: > find_succeeded = 1 > return string.find(target) > else: > find_succeeded = 0 > # I never know what number to return... > return 42 # that'll do... > > (In low-level languages like C, the number returned on failure (where I > choose 42) is often whatever value happens to be in some piece of memory > -- essentially a random number.) > > > result = find("hello world", "z") > if find_succeeded == 1: > print("found at position %d" % result) > else: > print("not found") > > > This is even more inconvenient and difficult than earlier. Consider what > happens if you want to do two or more searches. Because they all report > their status via the one global variable, you must inspect the global > after each call, before making the next call, or the status will be > lost. In Python you can do this: > > results = [s.find(target) for s in list_of_strings] > > and then, later, inspect each individual result to see if it was -1 or > not. But with the global status idiom, you can't do that, because the > status flag is lost once you call find() again. > > > > -- > Steven > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question on tkinter event binding
Hello Albert-Jan: I am glad you made the comment below. I was fascinated with the fact that your code was partly in English/Python and also in Dutch. I am a linguist so have great interest in bilingualism. How does this work in practice? I mean as a programmer, with native language other than English, do you download or buy English language software programs and work with them as-is? Do you have translated tutorials to help you learn? If you had a Dutch language software program and created your own program so that everything is totally in Dutch, and you wanted to communicate with English language email group :) How would you do that? Or would you try and find a Dutch language resource? Besides that, I am definitely saving your code segments for the future. Thanks for sharing. Patty - Original Message - From: Albert-Jan Roskam To: Albert-Jan Roskam ; Python Mailing List Sent: Friday, December 03, 2010 12:18 PM Subject: Re: [Tutor] Question on tkinter event binding I'll paste the working code below. It's partially in Dutch, but hey, so is Guido van Rossem. ;-) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Calling Program within Program
Hello: I would like to know how to call a program from within a program and what directory I should place one small program file in. I am running Python 2.6.6 and Windows 7. I have a directory called C:\Users\StarShip\PyProgs and it has the files BreakersCafe.txt and BreakersCafe.py. This is my primary program running fine. I have a subdirectory called C:\Users\StarShip\PyProg \PicturesForTesting and another subdirectory C:\Users\StarShip\PyProgs\CustomFunctions with various program files, functions defined in them, etc. which I import in my primary program. For example: def Newbanner(): print "\n Alternate Selections\n" Now I have the small program below which is fully self-contained and I want to execute it from within BreakersCafe.txt. I would like to use raw_input and if statement for simple yes/no asking if they would like to see this BeveragesMenu.txt and have it as the last 3-4 lines of the main(). The only directory of these three that has __init__ is C:\Users\StarShip\PyProgs\CustomFunctions and as you can see, the program below is not a function, it has no 'def' anything. I get 'NameError: global name 'BeveragesMenu' is not defined' when I run this in IDLE. I suppose I _could_ make this a function :} but it is likely doable to call a program as a program, right? I am also compiling to a .pyw file where applicable. Thanks for the help. Patty """ This is C:\Users\StarShip\PyProgs\BeveragesMenu.txt and BeveragesMenu.py. Program file for displaying an image using Tkinter built-in GUI functions. open root window, open file descriptor for image, open new window file descriptor to manipulate with Tkinter Label library function. Pic needs to be displayed as a banner. Uses the compound="top" argument to do this. --> take out the pack()function didn't work, pack()is required Uses import Tkinter Program using new breaker's jpg picture; bar choices are not selectable """ import Tkinter import ImageTk rootwindow = Tkinter.Tk() fhdl= ImageTk.Image.open("C:\Users\StarShip\PyProgs\PicturesForTesting\houseimage.jpg") image_var = ImageTk.PhotoImage(fhdl) whdl = Tkinter.Label(rootwindow, compound="top", image=image_var, text="\n\n!!!WELCOME TO BREAKER'S BREAKFAST BAR!!!\n\n\nBeverage Choices: Sparkling Water; Milk; Orange Juice; Apple Juice *OR*\n\n **From Our Bar**Smoothie; Breakers Sun Tea; Chai; Cafe Mocha; Latte; Mimosa") whdl.pack() rootwindow.mainloop() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Calling Program within Program
Hello Modulok: The code below is very simple, so I don't think you would have needed to read it. I will review the subprocess doc and look this up in my books and class notes. If I have more questions, I will email the group. I also realized that I wasn't clear in asking a secondary question which is what directory/directories to place files that are part of a program, actually an application. As if you were creating a source code hierarchy for the first time :} If I have more questions about that I will email again and change the subject header. Thanks for the reply!! Patty > Patty, > > I didn't read through your code, but to call an external program see > the 'subprocess' module in the standard library: > http://docs.python.org/library/subprocess.html > > -Modulok- > > > On 12/9/10, pa...@cruzio.com wrote: >> >> Hello: >> >> I would like to know how to call a program from within a program and >> what >> directory I should place one small program file in. I am running Python >> 2.6.6 and Windows 7. >> >> I have a directory called C:\Users\StarShip\PyProgs and it has the >> files >> BreakersCafe.txt and BreakersCafe.py. This is my primary program >> running >> fine. >> >> I have a subdirectory called C:\Users\StarShip\PyProg >> \PicturesForTesting >> and another subdirectory C:\Users\StarShip\PyProgs\CustomFunctions with >> various program files, functions defined in them, etc. which I import >> in >> my primary program. For example: >> >> def Newbanner(): >> print "\n Alternate Selections\n" >> >> Now I have the small program below which is fully self-contained and I >> want to execute it from within BreakersCafe.txt. I would like to use >> raw_input and if statement for simple yes/no asking if they would like >> to >> see this BeveragesMenu.txt and have it as the last 3-4 lines of the >> main(). >> >> The only directory of these three that has __init__ is >>C:\Users\StarShip\PyProgs\CustomFunctions >> and as you can see, the program below is not a function, it has no 'def' >> anything. I get 'NameError: global name 'BeveragesMenu' is not defined' >> when I run this in IDLE. I suppose I _could_ make this a function :} >> but >> it is likely doable to call a program as a program, right? I am also >> compiling to a .pyw file where applicable. >> >> Thanks for the help. >> >> Patty >> >> """ >> This is C:\Users\StarShip\PyProgs\BeveragesMenu.txt and >> BeveragesMenu.py. >> Program file for displaying an image using Tkinter built-in GUI >> functions. >> open root window, open file descriptor for image, open new window file >> descriptor to manipulate with Tkinter Label library function. >> >> Pic needs to be displayed as a banner. Uses the compound="top" argument >> to >> do this. >> >> --> take out the pack()function didn't work, pack()is required >> >> Uses import Tkinter >> >> Program using new breaker's jpg picture; bar choices are not selectable >> """ >> >> >> import Tkinter >> import ImageTk >> >> rootwindow = Tkinter.Tk() >> >> fhdl= >> ImageTk.Image.open("C:\Users\StarShip\PyProgs\PicturesForTesting\houseimage.jpg") >> image_var = ImageTk.PhotoImage(fhdl) >> >> whdl = Tkinter.Label(rootwindow, compound="top", image=image_var, >> text="\n\n!!!WELCOME TO BREAKER'S BREAKFAST BAR!!!\n\n\nBeverage >> Choices: >> Sparkling Water; Milk; Orange Juice; Apple Juice *OR*\n\n **From >> Our >> Bar**Smoothie; Breakers Sun Tea; Chai; Cafe Mocha; Latte; >> Mimosa") >> >> whdl.pack() >> rootwindow.mainloop() >> >> ___ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] How does it work?
- Original Message - From: "Patty" To: "Alan Gauld" Sent: Monday, January 03, 2011 9:05 AM Subject: Re: [Tutor] How does it work? Hi Folks - I read this code and tried to parse it as a pop quiz for myself ;) and have a question, maybe 2 clarifications, below: - Original Message - From: "Alan Gauld" To: Sent: Monday, January 03, 2011 8:09 AM Subject: Re: [Tutor] How does it work? "Neo Vector" wrote Could you explain me how does it work, pls? == r = '' r is an empty string for c in 'abcd': c takes the value of each letter in turn r = c + r When I first looked at this - I thought that the variable 'c' would have had to be initialized first earlier in the program. And I thought that the programmer would input a single char or a single space. I wasn't thinking counting variable for some reason. So is 'for c in', one or more of key words that Python understands that a loop is here and to actually trigger counting in a loop? Does it start with a 1 or 0 internally to do this? I also realized a mistake I may have made - maybe I confused 'for c in' with 'while c in'. r='' c="d" while c in 'abcd': r=c+r Or r='' c="d" while c in ['a', 'b', 'c', 'd']: r=c+r Also for myself I think I would have used different descriptive names for variables so that would have been less likely to throw myself off. And also doing this fast to see if I have learned. I really feel comfortable with Python now after six months and my small application is completed and looks really good. I don't know how I would have been able to make the simplest, smallest GUI part of my application - using Tkinter and PIL- fast without the references and explanations of Wayne Werner and Alan - Thanks to those on the list who are so helpful! Patty strings can be added such that the result is the concatenation of the two strings. So in this case: r becomes the sum of its old value and the current value of c repeat for the next value of c. If that doesn't help then tell us which bit(s) of it you don't understand. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How does it work?
Yes, I knew there was something I wasn't getting. This is the explanation I was looking for - and I'm sorry about the incorrect indentation. And I agree with Alan that 'foreach' would have been a good name for this type of loop. I need to sort out 'loop structures' in my notes and read up on these for sure. Thanks, Patty - Original Message ----- From: "Dave Angel" To: "Patty" Cc: Sent: Monday, January 03, 2011 9:52 AM Subject: Re: [Tutor] How does it work? On 01/-10/-28163 02:59 PM, Patty wrote: for c in 'abcd': .. When I first looked at this - I thought that the variable 'c' would have had to be initialized first earlier in the program. And I thought that the programmer would input a single char or a single space. I wasn't thinking counting variable for some reason. So is 'for c in', one or more of key words that Python understands that a loop is here and to actually trigger counting in a loop? Does it start with a 1 or 0 internally to do this? There's not necessarily any integer indexing going on. for xxx in yyy is a specific syntax that specifies a loop based on a sequence. In this case the string 'abcd' is a sequence of chars, so you get c to have a value of 'a', 'b', 'c', and 'd'. But other sequences might not have any index meaning at all, so it doesn't make sense to ask if it's 0 or 1 based. For example, you can iterate over the keys of a map, where the order is irrelevant. All you really know is you'll get them all if you finish the loop. I also realized a mistake I may have made - maybe I confused 'for c in' with 'while c in'. r='' c="d" while c in 'abcd': r=c+r You messed up the indentation. But if the r=c+r line is indented, then this is an infinite loop. It'll quit when memory is exhausted. Why? Because nothing in the loop changes c. So since it's in the sequence at the beginning, it will always be. Or r='' c="d" while c in ['a', 'b', 'c', 'd']: r=c+r Similarly here. Also for myself I think I would have used different descriptive names for variables so that would have been less likely to throw myself off. Good idea. And also doing this fast to see if I have learned. I really feel comfortable with Python now after six months and my small application is completed and looks really good. I don't know how I would have been able to make the simplest, smallest GUI part of my application - using Tkinter and PIL- fast without the references and explanations of Wayne Werner and Alan - Thanks to those on the list who are so helpful! Patty HTH DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginning Python and other resources (was Re: SlicingTuples)
Hi David - I was looking for the book you recomended below - "Python 3 Object Oriented Programming" by Dusty Phillips - and found it on Amazon for $43 new on up and $70 for used but maybe that was hardback? Do you happen to know of some other way to obtain it for less than $45? Thanks Patty - Original Message - From: "David" To: "John Russell" Cc: Sent: Saturday, December 11, 2010 3:47 PM Subject: [Tutor] Beginning Python and other resources (was Re: SlicingTuples) On 12 December 2010 03:25, John Russell wrote: Last night I started working through a book (Beginning Python: Using Python 2.6 and Python 3.1) I bought to learn Python, and there is an example in it that doesn't make sense to me. I have that book too, and several others thankfully. I'm just writing to share my experience, in case another perspective from another relatively new python user is helpful to anyone. I found that book is written towards a friendly beginner level, but it omits many details and is not a comprehensive reference. It does include plenty of examples on many topics. I have read the opposite criticism of other books, so it is probably impossible for one book to fit all needs. Personally I became weary of the food/fridge/kitchen theme of the early examples as it did not engage my interest at all, and there is so much of it. However I have found that book valuable for its Part III where it covers useful applications. Although I have come to expect that its examples will often need typos corrected or other small modifications to get them to run properly on Python 2.6. So while working through Parts I and II, if your experience is anything like mine where I moved away from it fairly quickly, you will definitely need other resources. Fortunately they are abundantly available. In case you are unaware, a Tutorial and Reference are integrated with Python. On my Linux box the tutorial is file:///usr/share/doc/python-docs-x.x.x/html/tutorial/index.html and the Alphabetic Index to the Reference is file:///usr/share/doc/python-docs-x.x.x/html/genindex.html I find the Tutorial easily readable, whereas the Reference can be challenging, but it is comprehensive and likely contains the answer to most questions, somewhere. As an exercise I thought I'd try to find the answer to your question using these built-in docs. The keyword is "slice" which we know from the book. I couldn't find any coverage in the 2.6 tutorial so I looked up "slice" in the Alphabetic Index, and the first link took me to a section which includes the answer: "The slicing now selects all items with index k such that i <= k < j where i and j are the specified lower and upper bounds". In case you are not aware, the web has a vast amount of great material for learning Python, see for example: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers As Python is an evolving language, one needs be mindful of the differences between Python 2.x and Python 3.x when using this material. My favourite Python book of my small beginners collection is "Python 3 Object Oriented Programming" by Dusty Phillips. It claims: "If you're new to object-oriented programming techniques, or if you have basic Python skills, and wish to learn in depth how and when to correctly apply object-oriented programming in Python, this is the book for you". I endorse that completely. Having learned the syntax basics elsewhere, for me this is a book like no other. I find its topic coverage and all its short examples consistently useful, powerful, and illuminating. I find it easy to read, well matched to my level and interest, and it has made a real difference to the code I write. I use classes with confidence now. For example, it gave me the background and confidence to design a custom sortable abstract class I needed, my first personal experience of the power of OOP. Tthe python and tutorial mailing lists are a wonderul resource as you are obviously aware. Thanks to all the contributors from whom I continue to learn. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Changing Python icon - 2.6 and 3.2
Hello Folks - I have Python 2.6.6 on my Windows 7 system and installed Python 3.2. Now I want to be able to differentiate between the versions and the icon for each version of Python is the same. I figured I would change the the four application files in the C:\Python26 directory - python; python26; pythonw; pythonw26 - and give them new picture icons. But when I select any of these files and choose 'properties', there is no option to change the application icon. I looked online but the questions were not exactly the same as this one and pertained to earlier versions of Python anyway. I discovered this when I was trying to associate a folder with 2.6 based programs so that it would always execute the programs with the python 2.6 .exe. And both Pythons come up as a choice with no details indicating which is which, except a lucky guess. It does appear that I can change the actual name of the application (the field with the name allows me to edit) but that is not what I wanted to do, also unsure if that would cause a problem in other parts of the application down the road if I was changing names like that. Thanks for suggestions - Patty___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] print "Hello, World!"
Hello Doug - My very first document I read - before I took an online course - was "A Quick, Painless Tutorial on the Python Language" by Norman Matloff from UC Davis. My copy is dated May 1, 2009 but I think he has updated it -- looks like May 2010. Here is the link, you may also want to query for other links like this for Matloff because I saw a few others while looking this up for you. It is free. http://html-pdf-converter.com/pdf/a-quick-painless-tutorial-on-the-python-language.html I also liked Alan Gauld's tutorial and the videos made by Google - taught by Nick Parlante - Here is the link: http://code.google.com/edu/languages/google-python-class/ I was not really happy with the actual course I took. You can contact me offline about this. Regards, Patty - Original Message - From: "Doug Marvel" To: ; Sent: Thursday, February 03, 2011 7:28 AM Subject: Re: [Tutor] print "Hello, World!" Holy wow! I'm going to go through all of these and see what sort of understanding I can absorb. I'm super excited that a helpful community exists for this, but I'm more excited to start learning. So I'm going to go do that now. I'm starting with Alan Gauld's tutorial, but like I said, I'm going to check out all of them, until I build some confidence. So far, this one seems to run at my speed. I'll be back, for certain. It took me twenty minutes to figure out how to get the ">>>" to come up in DOS after typing 'python'. hahaha It's good to meet all of you, and thanks again. Doug On Thu, Feb 3, 2011 at 6:07 AM, Alan Gauld wrote: "michael scott" wrote already been asked, learn from others who asked before you :) Oh yea, I once read that there are no intermediate tutorials in any programming language, because once you get past the basics, you only need to reference the "documentation" that comes with the language. Thats very nearly true. There are intermediate level tutorials for a few languages but more generally you get subject specific tutorials on things like parsing, web programming, GUI programming, databases, networking, stats and scientific programming etc etc. So there are usually intermediate level tutorials to suit they are rarely full language tutorials. I try to cover that off with the advanced topics and "Python in practice" topics at the end of my tutorial. But again they are focused on specific topic areas (OS, database, networks, web). -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] list of dictionary
- Original Message - From: Pacific Morrowind To: tutor@python.org Sent: Thursday, February 24, 2011 10:21 PM Subject: Re: [Tutor] list of dictionary Hi; On 24/02/2011 9:35 PM, sunil tech wrote: Hi all... i have d=[{'qty':0.0},{'qty':0.0} If there isn't some pressing reason to dictionaries as the list items (but since I'm not sure how you're generating the list/what you are later using the list I can't tell ofc but Hi - I had just a couple comments plus clarification about lists and iterating: if applicable to your situation I'd suggest just doing for creation of the list d = [] I like creating the empty variable structure, makes the code really clear. (logic for whatever gives your values) d.append(value) etc.) when all the qty is 0.0, i want to perform some print operation (only at once, after it checks everything in the list of dictionary 'd')... if its not 0.0, print some message... Thank you in advance Presuming you do have to use the dictionaries: qty = 0.0 for item in d: Right here - is the variable 'item' created right on the spot to iterate over this list? And I think you are doing the same thing when you create the variable 'subitem' in the line below, right? I am trying to get myself to recognize an iterator variable as opposed to a counter variable I create myself to keep track of these things (used in other programming languages) - and realizing the difference between counter/iterator variables and variables that I really care about like 'd = []' . Thanks! Patty for subitem in d: if item[subitem] != 0.0: qty = item[subitem] break if qty != 0.0: print "some message - for example a non zero qty = %f" % qty (presuming you are using Python 2x - if using python 3x the syntax will be slightly different) Hopefully that will serve your purpose if not just post again and I or one of the more frequently posting helpful users here will answer soon. Nick -- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Extensions in C
- Original Message - From: "Stefan Behnel" To: Sent: Thursday, May 26, 2011 9:10 AM Subject: Re: [Tutor] Python Extensions in C James Reynolds, 26.05.2011 17:22: As an intellectual exercise, I wanted to try my hand at writing some extensions in C. This is fine for en exercise, and I hope you had fun doing this. However, for real code, I suggest you use Cython instead. Your module would have been substantially simpler and likely also faster. http://cython.org Stefan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Hello James - I saw in your email 'Being a kinetic learner' and I had to look that up - is there a difference between the words 'kinetic' and 'kinesthetic'? When I googled it, I am sure I am a kinetic learner also and I come up with programming exercises for myself as well. I am originally a C programmer and now I really like Python. I don't know what it will be like for you to learn these languages the other way around, I am not the teacher-type. And thanks to Rachel-Mikel for that really nice piece of code to save for the future. Regards, Patty ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python Extensions in C
"Alan Gauld" wrote in message news:irm3ae$vpl$1...@dough.gmane.org... "Rachel-Mikel ArceJaeger" wrote Consider these the ravings of an ex maintenance programmer who spent far too much of his life deciphering other folks "clever" C code... It wasn't clever and it wasn't working! Alan G. Yikes! Patty ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Excited about python
- Original Message - From: Kaustubh Pratap chand To: tutor@python.org Sent: Friday, June 10, 2011 5:41 AM Subject: [Tutor] Excited about python Hello, I just joined this mailing list so that i can boost up my learning of python.I come from a C background so python looks a little strange to me but it is easier to learn then any other languages around.Yet,i have not been able to find any cool books on python for peoples who are already programmers.The ones which i found which i found were quite boring and exhaustive. Can you recommend a book for a person like me which comes with a C background and the book covers all essential algoithmic methods and examples? Thank you. -- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Hello Kaustubh: I am also a C programmer and the first thing I read about Python was "A Quick, Painless Tutorial on the Python Language" by Prof. Norman Matloff of UC-Davis. Here is the link to his page -- I didn't realize he had created other tutorials regarding Python, and will have to look at those myself. http://heather.cs.ucdavis.edu/~matloff/python.html Here is the specific link to the tutorial I mentioned: http://heather.cs.ucdavis.edu/~matloff/Python/PythonIntro.pdf In addition, I wasn't satisfied after learning on my own and took an online course. I also like Beginning Python - From Novice to Professional by Magnus Hetland. I have other books as well, such as Python Programming for the Absolute Beginner by Michael Dawson, but I like Hetland's style more and have a book being shipped to me by Hetland called Python Algorithms. Good Luck Patty ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor