Re: [Tutor] 'or' in assignment (not if statement)?
> Doesn't short-circuit evaluation refer specifically to the behavior > where arguments are only evaluated if they need to be? It's a very > useful feature, but not technically required for the "val = val or 1" > behavior to work. Its essential. If Python always evaluated all parts of a boolean expression the return value would always be the last item. It's the fact that Python knows that if val is true then it doesn't need to evaluate the second term that causes it to return val rather than 1. > Also, returning on of its operands rather than a boolean is hardly a > quirk, since basically all dynamic languages do it ever since perl > made "val = val or 1" an idiom (at least, I think it was perl). Its a quirk in that it is not the intuitively expected behaviour. It's a boolean expression you would reasonably expect a true boolean result. I think you are right that Perl was the first popular language to do this, but Perl is a relatively recent arrival (abouit the same time as Python - 1988-90?) and it has become a feature of many recent dynamic languages. But most static languages still return true boolean values. Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] 'or' in assignment (not if statement)?
ALAN GAULD wrote: Doesn't short-circuit evaluation refer specifically to the behavior where arguments are only evaluated if they need to be? It's a very useful feature, but not technically required for the "val = val or 1" behavior to work. Its essential. If Python always evaluated all parts of a boolean expression the return value would always be the last item. You can simulate non-short-circuit behaviour with a function: def or_(a, b): if a: return a return b x = 0 or_(True, 1/x) Unlike the short-circuiting `or` operator, this version evaluates the 1/x even though it doesn't end up being used. This was one of the reasons why the ternary `if` operator had to be handled by syntax, rather than having people write a function: ifte(condition, a, b): if condition: return a else: return b ifte(len(x) > 0, x[0], "nothing there") This will fail if x is an empty list, unlike this: x[0] if len(x) > 0 else "nothing there" which works because the Python interpreter knows not to evaluate x[0] unless needed. It's the fact that Python knows that if val is true then it doesn't need to evaluate the second term that causes it to return val rather than 1. That's what makes it short circuiting, but that's not why it returns the first argument. `or` in standard Pascal doesn't short-circuit. Take this example `or.p` file: [st...@sylar pascal]$ cat or.p program main(input, output); function f1(a:integer):boolean; begin writeln('calling f1'); f1 := True; end; function f2(a:integer):boolean; begin writeln('calling f2'); f2 := True; end; var n: integer; f: boolean; begin n := 0; f := f1(n) or f2(n); end. [st...@sylar pascal]$ [st...@sylar pascal]$ gpc --no-short-circuit or.p [st...@sylar pascal]$ ./a.out calling f1 calling f2 (gpc defaults to the sensible but non-standard short-circuit behavior, and you have to pass a compiler option to get the standard behaviour.) Also, returning on of its operands rather than a boolean is hardly a quirk, since basically all dynamic languages do it ever since perl made "val = val or 1" an idiom (at least, I think it was perl). Its a quirk in that it is not the intuitively expected behaviour. It's a boolean expression you would reasonably expect a true boolean result. That brought a smile to my face! That's very amusing, the idea that *boolean algebra* is intuitively expected! As an experiment, offer to buy your wife (or girlfriend, boyfriend, significant other, or if all else fails, mum) dinner, and ask if she'd prefer to go to an Italian or Chinese restaurant. If she says that she doesn't understand the question, because restaurants aren't True/False boolean values, then you might have a point :) -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Meaning of -1 in Python
I'm currently working through the Google Python tutorial exercises and had questions about the following function: def not_bad(s): # +++your code here+++ # LAB(begin solution) n = s.find('not') b = s.find('bad') if n != -1 and b != -1 and b > n: s = s[:n] + 'good' + s[b+3:] return s It's clear that n!=-1 and b!=-1 means something like : "if in the string 's' we find the word "not" and in string 's' we find the word "bad." I'm wondering the following: On a deeper computational level, what is going on here? What exactly does Python take -1 to mean? Is it saying that since the string 's' is indexed starting from 0 to len(s), and since -1 is not part of that, that therefore something having the value of -1 will never be in the string? If so, then how exactly does using negative numbers to count a string work? I have read something about this earlier... Also, does the part: b>n mean, in this case: "bad comes after not in the string 's'"? Thank you very much. Sincerely, Ben ___ 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
Re: [Tutor] 'or' in assignment (not if statement)?
"Steven D'Aprano" wrote Python knows that if val is true then it doesn't need to evaluate the second term that causes it to return val rather than 1. That's what makes it short circuiting, but that's not why it returns the first argument. `or` in standard Pascal doesn't short-circuit. But Pascal returns a boolean result, it doesn't return the original value of either term, it returns the true Boolean value of the expression. Take this example `or.p` file: I don't see what point you are trying to make? Other than that Pascal doesn't do short-circuit evaluation. But that doesn't relate to the fact that its a combination of Python doing short circuit evaluation plus returning the original value that enables the "val or 1" idiom to work. It's a boolean expression you would reasonably expect a true boolean result. That brought a smile to my face! That's very amusing, the idea that *boolean algebra* is intuitively expected! It is if you are used to computer programming languages :-) So for example if I do print len("foo") I don't expect "bar" - even though bar does have the same length as "foo". The way most languages nowadays treat logic is inconsistent with how they treat other operations but done for the many conveniences that such an approach has over the more purist. eg if myString rather than if myString == "" etc. As an experiment, offer to buy your wife dinner, and ask if she'd prefer to go to an Italian or Chinese restaurant. :-) She would either answer "Yes" (she would like to go to one of them, and if I'm lucky she might give me a clue which!) or "No" (she would prefer neither, Indian perhaps...) If she says that she doesn't understand the question, because restaurants aren't True/False boolean values, then you might have a point :) Yes, I agree that only a truue mathematician would reply like that. Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Meaning of -1 in Python
"Ben Ganzfried" wrote n = s.find('not') b = s.find('bad') if n != -1 and b != -1 and b > n: s = s[:n] + 'good' + s[b+3:] return s It's clear that n!=-1 and b!=-1 means something like : "if in the string 's' we find the word "not" and in string 's' we find the word "bad." Exactly the oopsite in fact. find() returns the index where the string is fouind. -1 means the string was not found Thats why inside the if block we can use the n and b values to slice the string. They represent the positions of the words we were looking for within the string. On a deeper computational level, what is going on here? What exactly does Python take -1 to mean? Is it saying that since the string 's' is indexed starting from 0 to len(s), and since -1 is not part of that, that therefore something having the value of -1 will never be in the string? Exactly so. -1 is not a "valid" index (made more confusing by the fact that in Python it is because Python supports negatiove indexes! But forget about that temporarily!) This is a common convention in programming languages and Python has adopted it. Personally I think a return of None would have made more sense, but history has dictated otherwise! If so, then how exactly does using negative numbers to count a string work? I have read something about this earlier... Python allows you to use negative numbers to index a string in reverse. So an index of -1 actually indicates the last character, but for find() you have to forget about that... Also, does the part: b>n mean, in this case: "bad comes after not in the string 's'"? Yes, if the index of the 'b' in 'bad' is higher than the index of 'n' in 'not' then 'bad' comes after 'not'. read more about how Python functions work by using the help() function at the >>> prompt help(''.find) Note you only type the name not the () after find HTH, Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] the "**" operator?
Hi all, I was googling a way to do something like mydict=mydict.extend(additionaldict) and someone on a forum recommends this: mydict=dict(mydict, **additionaldict) What is the ** doing here? I tried to look it up, but Google seems to ignore it since it is punctuation. The poster on the forum says it will put all elements of additionaldict in mydict that are not already in mydict, which is the behavior I am looking for, but I am not sure why this would be so. TIA. -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] the "**" operator?
The value you provide as the second argument must be a dictionary. Google kwargs python for lots of more in depth info On Fri, Dec 10, 2010 at 2:14 PM, Alex Hall wrote: > Hi all, > I was googling a way to do something like > mydict=mydict.extend(additionaldict) > > and someone on a forum recommends this: > mydict=dict(mydict, **additionaldict) > What is the ** doing here? I tried to look it up, but Google seems to > ignore it since it is punctuation. The poster on the forum says it > will put all elements of additionaldict in mydict that are not already > in mydict, which is the behavior I am looking for, but I am not sure > why this would be so. TIA. > > -- > Have a great day, > Alex (msg sent from GMail website) > mehg...@gmail.com; http://www.facebook.com/mehgcap > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Joel Goldstick ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] the "**" operator?
Dnia 10-12-2010 o 20:14:30 Alex Hall napisał(a): Hi all, I was googling a way to do something like mydict=mydict.extend(additionaldict) and someone on a forum recommends this: mydict=dict(mydict, **additionaldict) What is the ** doing here? As far as I know the ** indicates that the argument passed (here named: additionaldict) is a dictionary. One * would mean that it is a tuple. I'm not sure but it seams to me that the usual way to *update* a dictionary with the contents of an other dictionary is to use the .update dictionary method. Examples: animals= {'cat': 'Bobo', 'dog': 'Rex'} animals2= {'cow': 'some name that I can\'t think of right now', 'bird': 'Falco'} animals.update(animals2) print animals {'bird': 'Falco', 'dog': 'Rex', 'cow': "some name that I can't think of right now", 'cat': 'Bobo'} print animals2 {'bird': 'Falco', 'cow': "some name that I can't think of right now"} Hope my answers are right and it helps, Piotr ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] the "**" operator?
On Fri, Dec 10, 2010 at 8:14 PM, Alex Hall wrote: > Hi all, > I was googling a way to do something like > mydict=mydict.extend(additionaldict) > mydict.update(additionaldict) see also: http://docs.python.org/library/stdtypes.html#dict.update > and someone on a forum recommends this: > mydict=dict(mydict, **additionaldict) > What is the ** doing here? I tried to look it up, but Google seems to > ignore it since it is punctuation. The poster on the forum says it > will put all elements of additionaldict in mydict that are not already > in mydict, which is the behavior I am looking for, but I am not sure > why this would be so. TIA. > The * and **, when calling functions, are what's called extended calling syntax. It's a bit hard to explain, so I'm going to do a sort of clarify by example here: >>> def f(a, b, c): ... print a, b, c ... >>> f(1, 2, 3) 1 2 3 >>> a = [1, 2, 3] >>> f(*a) 1 2 3 >>> b = {'a': 2, 'b': 1, 'c': 3} >>> f(*b) a c b >>> f(**b) 2 1 3 In short, if a = [1, 2, 3], f(*a) is the same as f(1, 2, 3). if b = {'a': 2, 'b': 1, 'c': 3}, then f(**b) is the same as f(a=2, b=1, c=3). The * will iterate over its argument, and supply the resulting values as arguments to the function (iterating over a dict will return its keys, which is what you see with f(*b) here). ** requires a mapping type, and supplies the keys and values to the function as keyword arguments. * and ** are very flexible, and you can use them alongside with regular arguments: >>> f(1, *[2, 3]) 1 2 3 >>> f(1, **{'b': 2, 'c': 3}) 1 2 3 * and ** also have uses in function definition, where they sort of do the reverse. They can capture any number of regular or keyword arguments in a tuple or dictionary: >>> def f(*args, **kwargs): ... print args, kwargs ... >>> f() () {} >>> f(1, 2, 3) (1, 2, 3) {} >>> f(1, 2, 3, a=4, b=5) (1, 2, 3) {'a': 4, 'b': 5} >>> f(a=4, b=5) () {'a': 4, 'b': 5} Like with function calls, you can mix up regular arguments and */** arguments, as long as the resulting function is unambiguous: >>> def f(a, *args, **kwargs): ... print a, args, kwargs ... >>> f() Traceback (most recent call last): File "", line 1, in TypeError: f() takes at least 1 argument (0 given) >>> f(1) 1 () {} >>> f(1, 2, 3) 1 (2, 3) {} >>> f(1, 2, 3, b=4, c=5) 1 (2, 3) {'c': 5, 'b': 4} ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Writing to the terminal?
List, Forgive me if I don't describe this well, I'm new to it: Assume I'm working in a command shell on a terminal. Something like tcsh on xterm, for example. I have a program which does *something*. Let's say it counts down from 10. How do I print a value, and then erase that value, replacing it with another value? Say I had something like '10' that appears, then wait a second, then the 10 is replaced by '9'... '8'.. and so forth. The point is, I don't want to print to a new line, nor do I want the new number to appear next to the previous number... I just want to change it in place. (If that makes any sense?) Think of console based progress counters in programs like fetch or wget, or lame. How do you do this in Python? -Modulok- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing to the terminal?
If you just want a single line you can use chr(13) which is a carriage return. If you want a more complex program you'll need a curses type library hth, wayne On 12/10/10, Modulok wrote: > List, > > Forgive me if I don't describe this well, I'm new to it: > > Assume I'm working in a command shell on a terminal. Something like > tcsh on xterm, for example. I have a program which does *something*. > Let's say it counts down from 10. How do I print a value, and then > erase that value, replacing it with another value? Say I had something > like '10' that appears, then wait a second, then the 10 is replaced by > '9'... '8'.. and so forth. The point is, I don't want to print to a > new line, nor do I want the new number to appear next to the previous > number... I just want to change it in place. (If that makes any > sense?) Think of console based progress counters in programs like > fetch or wget, or lame. > > How do you do this in Python? > -Modulok- > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > -- Sent from my mobile device ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing to the terminal?
On 12/10/2010 3:14 PM, Modulok wrote: List, Forgive me if I don't describe this well, I'm new to it: Assume I'm working in a command shell on a terminal. Something like tcsh on xterm, for example. I have a program which does *something*. Let's say it counts down from 10. How do I print a value, and then erase that value, replacing it with another value? Say I had something like '10' that appears, then wait a second, then the 10 is replaced by '9'... '8'.. and so forth. The point is, I don't want to print to a new line, nor do I want the new number to appear next to the previous number... I just want to change it in place. (If that makes any sense?) Think of console based progress counters in programs like fetch or wget, or lame. How do you do this in Python? -Modulok- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor I've never used it before, but I think the curses module does this. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing to the terminal?
On 12/10/2010 3:34 PM, Wayne Werner wrote: If you just want a single line you can use chr(13) which is a carriage return. If you want a more complex program you'll need a curses type library hth, wayne On 12/10/10, Modulok wrote: List, Forgive me if I don't describe this well, I'm new to it: Assume I'm working in a command shell on a terminal. Something like tcsh on xterm, for example. I have a program which does *something*. Let's say it counts down from 10. How do I print a value, and then erase that value, replacing it with another value? Say I had something like '10' that appears, then wait a second, then the 10 is replaced by '9'... '8'.. and so forth. The point is, I don't want to print to a new line, nor do I want the new number to appear next to the previous number... I just want to change it in place. (If that makes any sense?) Think of console based progress counters in programs like fetch or wget, or lame. How do you do this in Python? -Modulok- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Try that in the interactive interpreter, it doesn't work. >>> print "a" + chr(13) a (Python 2.6.6) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] 'ascii' codec can't decode byte
Hello members: I need your help, I'm developing a python script to make an excel file... I've been working in this for a long time. The module will write some data from a .shp file. Unfortuanely that information has some characters unrecorgnized by ascii. I tried to fix this adding an unicode sentence, but it didn't work, the script is: import os, time,fnmatch from xlwt import Workbook from osgeo import ogr,gdal,osr from dbf import * gdal.AllRegister() file_list = [] folders = None for root, folders, files in os.walk( "R:\\" ): for filename in fnmatch.filter(files, '*.shp'): file_list.append(os.path.join(root, filename) wrkbk = Workbook() wksht = wrkbk.add_sheet('shp') wksht.row(0).write(0,'ruta') wksht.row(0).write(1,'archivo' wksht.row(0).write(2,'prj') wksht.row(0).write(3,'fecha_modificacion') wksht.row(0).write(4,'maquina_host') wksht.row(0).write(5,'usuario') for row, filepath in enumerate(file_list, start=1): wksht.row(row).write(0, unicode(filepath,errors='ignore')) (ruta, filename) = os.path.split(filepath) wksht.row(row).write(1, unicode(filename,errors='ignore')) n = os.path.splitext(filepath) p = n[0]+'.prj' if os.path.exists(p): prj_text = open(p, 'r').read() unicode(prj_text,errors='ignore') wksht.row(row).write(2,prj_text) else: wksht.row(row).write(2, 'Sin prj, no se puede determinar la proyeccion') wksht.row(row).write(4, unicode(socket.gethostname(),errors='ignore')) t = time.strftime("%m/%d/%Y %I:%M:%S %p",time.localtime(os.path.getmtime(filepath))) wksht.row(row).write(3, unicode(t,errors='ignore')) wksht.row(row).write(5,unicode(os.environ.get("USERNAME"),errors='ignore')) wrkbk.save('C:\\Python26\\biblio\\biblio_shp.xls') When I run it, I got the next error: Warning 1: organizePolygons() received an unexpected geometry. Either a polygon with interior rings, or a polygon with less than 4 points, or a non-Polygon geometry. Return arguments as a collection. Warning 1: Geometry of polygon of fid 0 cannot be translated to Simple Geometry. All polygons will be contained in a multipolygon. El archivo R:\Regiones\BosquePrimavera\Redefinici¾n de ptos del ANP del B la P\D atos GPS\Meridian\polnuevonm.shp no tiene dbf Traceback (most recent call last): File "", line 1, in File "crawler_shp.py", line 138, in wrkbk.save('C:\\Python26\\biblio\\biblio_shp.xls') File "C:\Python26\lib\site-packages\xlwt\Workbook.py", line 634, in save doc.save(filename, self.get_biff_data()) File "C:\Python26\lib\site-packages\xlwt\Workbook.py", line 609, in get_biff_d ata shared_str_table = self.__sst_rec() File "C:\Python26\lib\site-packages\xlwt\Workbook.py", line 571, in __sst_rec return self.__sst.get_biff_record() File "C:\Python26\lib\site-packages\xlwt\BIFFRecords.py", line 53, in get_biff _record self._add_to_sst(s) File "C:\Python26\lib\site-packages\xlwt\BIFFRecords.py", line 66, in _add_to_ sst u_str = upack2(s, self.encoding) File "C:\Python26\lib\site-packages\xlwt\UnicodeUtils.py", line 50, in upack2 us = unicode(s, encoding) UnicodeDecodeError: 'ascii' codec can't decode byte 0xf3 in position 9: ordinal not in range(128) >>> ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing to the terminal?
Modulok wrote: List, Forgive me if I don't describe this well, I'm new to it: [snip description of a progress bar] Here's one way: import time, sys f = sys.stdout for i in range(20): time.sleep(1) # do some work f.write('=') f.flush() # make the change visible immediately else: f.write('\n') You might be able to get the same effect with print, but it's probably easier using sys.stdout directly. Here's another way, which *must* use stdout and not print. for i in range(20): percentage = i/20.0 spinner = '/-\\-'[i % 4] f.write("Progress: %5.2f%% %s %s>\r" % (percentage, spinner, '='*(i+1))) f.flush() time.sleep(1) else: f.write('\n') -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing to the terminal?
On Fri, Dec 10, 2010 at 9:38 PM, Corey Richardson wrote: > > Try that in the interactive interpreter, it doesn't work. print "a" + chr(13) > a You forgot to print something after the carriage return. It works for me: Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39) [GCC 4.4.5] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print 'a'+chr(13)+'b' b >>> the carriage return resets the cursor to the beginning of the line, so you can write over what you wrote before. Hugo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Globals as variables in a tkinter widget
This code produces a good run. from tkinter import * root = Tk() class Application(Frame): global sv, Ptype, PtypeI, sel_rate_label, label label = Label(root) Ptype = 999 PtypeI = IntVar() W = 5 Y = 4 def sel(self): global W global Y Ptype = PtypeI.get() if Ptype <= 333: print('\nResulting Values:', PtypeI.get(),Ptype) else: print('Ptype Failure:',PtypeI.get()) print('Ptype Completed',Ptype,'\n') V = 2 X = 3 Z = X * 2 W = X + 6 Y = V ** 2 U = W * Y print("V: ",V," X: ",X," Z: ",Z," W: ",W," Y: ",Y," U: ",U,'\n') return def __init__(self,master=None): Frame.__init__(self) self.pack() sel_rate_label = Label(self) sel_rate_label.config(text = '\nSelect Goats Personality Type',) sel_rate_label.pack(anchor=N) MODES = [ ("1 Below Average", 000), ("2 Average", 111), ("3 Above Average", 222), ("4 Super Star", 333), ] for text, mode in MODES: b = Radiobutton(self, text=text, variable=PtypeI, value=mode, command = self.sel) b.pack(anchor=W) label.pack() return app = Application(master=root) app.mainloop() #root.destroy() This is the IDLE output. >>> RESTART >>> Resulting Value: 333 333 Ptype Completed 333 V: 2 X: 3 Z: 6 W: 9 Y: 4 U: 36 >>> Assigning U prior to recalculating W & Y: U = W * Y V = 2 X = 3 Z = X * 2 W = X + 6 Y = V ** 2 print("V: ",V," X: ",X," Z: ",Z," W: ",W," Y: ",Y," U: ",U,'\n') Produces: >>> RESTART >>> Resulting Values: 333 333 Ptype Completed 333 Exception in Tkinter callback Traceback (most recent call last): File "C:\Python31\lib\tkinter\__init__.py", line 1399, in __call__ return self.func(*args) File "C:\Larry\FCGCF\GPDB\Dev\EX_OK.py", line 18, in sel U = W * Y TypeError: can't multiply sequence by non-int of type 'str' My goal is to I learnto use a global variable as an argument inside a widget function, My Question is: Anybody know of some good on-line documentation about using GUIs to do more than say 'Hello World'? Thanx in advance, Larry Rochester AKA echo...@aol.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] role playing game - help needed
Thanks again Alan. Much clearer now. One final part I don't understand. > "%d is the result of %d + %d" % (6+7,6,7) > >I understand (I think) the 6+7 part but why the ,6,7 after that. I could >see how either '6+7' or '6,7' would be the correct format but not both. The format string has 3 percent markers - all numbers. It is therefore expecting 3 values, so I have to give it them. The first marker gets 6+7, ie 13. The second gets 6 the third 7... Look at the first example in the loops topic in my tutorial. It uses variables in the same way rather than literal values, that might make it more obvious. Maybe :-) HTH, Alan G.___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing to the terminal?
"Modulok" wrote Assume I'm working in a command shell on a terminal. Something like tcsh on xterm, for example. I have a program which does *something*. Let's say it counts down from 10. How do I print a value, and then erase that value, replacing it with another value? This is one of those things that sounds like it should be easy but is in fact deceptively difficult to get right! It all depends on your terminal, and there are dozens of different terminal types and settings. Thats why Unix has a terminfo (or in some Unices termcap - even they can't agree! :-) library to define the different terminal types and try to bring some sanity to proceedings.But you need to learn the basic terminal control codes. In this case you need the backspace code which is Ctrl-H or chr(8). Try this print "spam" + "chr(8)*2+"ear" If your terminal recognises chr(8) as backspace you should see "spear". If it doesn't you'll see someting like: spam^h^hear The only foolproof way to do this kind of thing is to use a library like curses which allows you to positioon the cursor and overwrite whatever was there. But curses is non-trivial to use - not ridiculously hard, but non trivial. You can get a basic intro to curses in the event-driven topic of my tutorial. BTW there is quite a good writeup on terminfo here: http://tldp.org/HOWTO/Text-Terminal-HOWTO-16.html and, as usual, Wikipedia has a fair writeup. -- 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
Re: [Tutor] Globals as variables in a tkinter widget
wrote This code produces a good run. Not sure what you mean by that. What is "a good run"? from tkinter import * root = Tk() class Application(Frame): global sv, Ptype, PtypeI, sel_rate_label, label This is bizarre. Globals are generally considered evil and to be avoided if possible. One way to avoid globals is to use classes. So why on earth are you trying to introduce globals ionto a class? What do you think you will achieve that using class variables can't? label = Label(root) Ptype = 999 PtypeI = IntVar() W = 5 Y = 4 And in fact most of these should probably be instance variables defined within your init() method... def sel(self): global W global Y Ptype = PtypeI.get() if Ptype <= 333: print('\nResulting Values:', PtypeI.get(),Ptype) else: print('Ptype Failure:',PtypeI.get()) print('Ptype Completed',Ptype,'\n') V = 2 X = 3 Z = X * 2 W = X + 6 Y = V ** 2 U = W * Y print("V: ",V," X: ",X," Z: ",Z," W: ",W," Y: ",Y," U: ",U,'\n') return Mixing print statements and GUIS is valid for debugging, but these don't look like debnug statements... Are you sure you want these appearing in the console rather than the GUI? def __init__(self,master=None): Frame.__init__(self) You might want to pass the master in to Frame too... self.pack() sel_rate_label = Label(self) sel_rate_label.config(text = '\nSelect Goats Personality Type',) sel_rate_label.pack(anchor=N) MODES = [ ("1 Below Average", 000), ("2 Average", 111), ("3 Above Average", 222), ("4 Super Star", 333), ] for text, mode in MODES: b = Radiobutton(self, text=text, variable=PtypeI, value=mode, command = self.sel) b.pack(anchor=W) label.pack() Why use the global label here when you use the instance level labels elsewhere? Especially as you don't appear to use it? Resulting Values: 333 333 Ptype Completed 333 Exception in Tkinter callback Traceback (most recent call last): File "C:\Python31\lib\tkinter\__init__.py", line 1399, in __call__ return self.func(*args) File "C:\Larry\FCGCF\GPDB\Dev\EX_OK.py", line 18, in sel U = W * Y TypeError: can't multiply sequence by non-int of type 'str' It seems to think that Y is a string. Your code suggests Y is V**2 or 4. Can you insertt a print statement just before the offending line to find out what W and Y are at that exact point? My goal is to I learnto use a global variable as an argument inside a widget function, Why do you think that will be useful? What do you think you can do with globals that you can't do with class or instance variables? My Question is: Anybody know of some good on-line documentation about using GUIs to do more than say 'Hello World'? There are a lot of GUI tutorials, some even use Tkinter. Even my tutorial includes the GUI in the case study and the event driven programming topics as well as the GUI topic itself. They don;t go far beyond hello world but they do take at least one step further. 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
Re: [Tutor] the "**" operator?
Thanks all! I thought update() would add an item even if it would be a duplicate, but apparently not. I also now better understand why I am always passing around *args and **kwargs when calling super(). Very interesting... On 12/10/10, Hugo Arts wrote: > On Fri, Dec 10, 2010 at 8:14 PM, Alex Hall wrote: >> Hi all, >> I was googling a way to do something like >> mydict=mydict.extend(additionaldict) >> > > mydict.update(additionaldict) > > see also: > http://docs.python.org/library/stdtypes.html#dict.update > >> and someone on a forum recommends this: >> mydict=dict(mydict, **additionaldict) >> What is the ** doing here? I tried to look it up, but Google seems to >> ignore it since it is punctuation. The poster on the forum says it >> will put all elements of additionaldict in mydict that are not already >> in mydict, which is the behavior I am looking for, but I am not sure >> why this would be so. TIA. >> > > The * and **, when calling functions, are what's called extended > calling syntax. It's a bit hard to explain, so I'm going to do a sort > of clarify by example here: > def f(a, b, c): > ... print a, b, c > ... f(1, 2, 3) > 1 2 3 a = [1, 2, 3] f(*a) > 1 2 3 b = {'a': 2, 'b': 1, 'c': 3} f(*b) > a c b f(**b) > 2 1 3 > > In short, if a = [1, 2, 3], f(*a) is the same as f(1, 2, 3). if b = > {'a': 2, 'b': 1, 'c': 3}, then f(**b) is the same as f(a=2, b=1, c=3). > > The * will iterate over its argument, and supply the resulting values > as arguments to the function (iterating over a dict will return its > keys, which is what you see with f(*b) here). ** requires a mapping > type, and supplies the keys and values to the function as keyword > arguments. > > * and ** are very flexible, and you can use them alongside with > regular arguments: > f(1, *[2, 3]) > 1 2 3 f(1, **{'b': 2, 'c': 3}) > 1 2 3 > > * and ** also have uses in function definition, where they sort of do > the reverse. They can capture any number of regular or keyword > arguments in a tuple or dictionary: > def f(*args, **kwargs): > ... print args, kwargs > ... f() > () {} f(1, 2, 3) > (1, 2, 3) {} f(1, 2, 3, a=4, b=5) > (1, 2, 3) {'a': 4, 'b': 5} f(a=4, b=5) > () {'a': 4, 'b': 5} > > Like with function calls, you can mix up regular arguments and */** > arguments, as long as the resulting function is unambiguous: > def f(a, *args, **kwargs): > ... print a, args, kwargs > ... f() > Traceback (most recent call last): > File "", line 1, in > TypeError: f() takes at least 1 argument (0 given) f(1) > 1 () {} f(1, 2, 3) > 1 (2, 3) {} f(1, 2, 3, b=4, c=5) > 1 (2, 3) {'c': 5, 'b': 4} > -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Code evaluation inside of string fails with __get_item
I'm using Python 2.6.5. The following problem is coming from inside of a complex code base and involves an implementation that I have used for years, and is now failing to execute in certain conditions. This problem occurs with either of the follow two classes, which are 'lifted' from 'Python Cookbook'. Class code follows: class Eval: def __init__(self, globals=None, locals=None): self.globals = globals or {} self.locals = locals or None def __getitem__(self, key): if self.locals is None: self.locals = sys._getframe(1).f_locals key = key % self return eval(key, self.globals, self.locals) ## and this one: class Evalx: def __init__(self, localvals = None, globalvals = None): if localvals is None : self.locals = sys._getframe(1).f_locals else : self.locals = locals if globalvals is None : self.globals = sys._getframe(1).f_globals else : self.globals = globals def __getitem__(self,key): return eval(key,self.globals,self.locals) ## either are used the same way: To evaluate code inside of a string ## A larger description can be found at: ## http://code.activestate.com/recipes/66018-evaluating-code-inside-strings/ The execution looks like this: self.content = formatted_string % Evalx() ## where 'self' refers to an object of another class, that uses the ## Eval class Under certain circumstances, the embedded is code *not* executed. By inserting debugging stubs, I can see that the the Eval/Evalx instantiation does occur, but the overloaded function call to __get_item does *not* occur. I have also found that a seemingly unrelated event having to do with file I/O must be causing a side effect. However, to keep things simple, I am first asking the following question: What would cause __get_item__ not to be called? I can confirm by other testing that the embedded codde is properly composed with matching keywords. This is probably the most difficult to resolve problem I've ever run into in python. My lack of understand of the underlying code in the Eval classes is probably a contributing factor. TIA -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing to the terminal?
On 12/10/2010 12:14 PM Modulok said... List, Forgive me if I don't describe this well, I'm new to it: Assume I'm working in a command shell on a terminal. Something like tcsh on xterm, for example. I have a program which does *something*. Let's say it counts down from 10. How do I print a value, and then erase that value, replacing it with another value? Say I had something like '10' that appears, then wait a second, then the 10 is replaced by '9'... '8'.. and so forth. The point is, I don't want to print to a new line, nor do I want the new number to appear next to the previous number... I just want to change it in place. (If that makes any sense?) Think of console based progress counters in programs like fetch or wget, or lame. How do you do this in Python? -Modulok- ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor The trick is starting python with the -u option: em...@paj39:~$ python -u Python 2.6.4rc2 (r264rc2:75497, Oct 20 2009, 02:55:11) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> for ii in range(10): ... print " %s" % (ii,), ... time.sleep(2) ... print "\r", ... >>> Emile ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] the "**" operator?
On Sat, Dec 11, 2010 at 1:26 AM, Alex Hall wrote: > Thanks all! I thought update() would add an item even if it would be a > duplicate, but apparently not. I also now better understand why I am > always passing around *args and **kwargs when calling super(). Very > interesting... > Actually, it does. If a key is already present, the value will be overwritten (since you can't have a key with more than one value, obviously). If you don't want to overwrite the duplicates, filter them some_dict.update(x for x in additional_dict.items() if x[0] not in some_dict) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Meaning of -1 in Python
On Fri, 10 Dec 2010, Alan Gauld wrote: "Ben Ganzfried" wrote n = s.find('not') b = s.find('bad') if n != -1 and b != -1 and b > n: s = s[:n] + 'good' + s[b+3:] return s It's clear that n!=-1 and b!=-1 means something like : "if in the string 's' we find the word "not" and in string 's' we find the word "bad." Exactly the oopsite in fact. find() returns the index where the string is fouind. -1 means the string was not found I don't think it's opposite; I think Ben and Alan are saying the same thing, albeit in different ways. Ben: n = s.find('not') n!=-1 ... means something like : "if in the string 's' we find the word "not" Yes; "n != -1" means "not not found", that is, found. (ditto for the discussion of "b!=-1") Alan: -1 means the string was not found Exactly. Both of you are saying that -1 means "not found"; Ben is expresing that negating that is equivalent to "found." ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] 'or' in assignment (not if statement)?
Hi Steven On 10 December 2010 03:50, Steven D'Aprano wrote: > Some languages (Pascal comes to mind) doesn't have short-circuit behaviour > at all. > Don't mean to nit pick, but in my experience it really depends on the compiler implementation and which version of Pascal you're talking about. Certainly, Borland's Turbo Pascal had and later Object Pascal (today called Delphi) has to this day short-circuit evaluation as default behaviour, although you can turn this off via a compiler switch if you want.(And as an aside, according to wikipedia ISO Pascal actually also allows but does not require support of short-circuit boolean evaluation.) It really depends on what your program does -- if your program contains functions with side-effects (a bad idea, but if it does) then short-circuit evaluation will probably break your code. On the other hand, not having short-circuit boolean expression evaluation can in most programming contexts be needlessly inefficient. Anyway, your general point is of course quite correct, so feel free to ignore my ramblings... Best, Walter ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] using a networked data file
This is somewhat non-Python specific I have an idea for a Python application that I want to write at work. The application needs to have a data file be available to multiple users for access, read and write. I know that a typical database, such as mysql, would work ok. However, I am trying to keep managed infrastructure down to a minimum so I am considering using sqlite instead. Since there is not a database service running to handle requests to the sqlite database, how can I allow for multiple people trying to use this database at the same time? Is this practical? Thanks, Bill Allen ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Code evaluation inside of string fails with __get_item
This is a resend. I note that the original had an incorrect `reply-to' ID attached to it. (sorry) -- I'm using Python 2.6.5. The following problem is coming from inside of a complex code base and involves an implementation that I have used for years, and is now failing to execute in certain conditions. This problem occurs with either of the follow two classes, which are 'lifted' from 'Python Cookbook'. Class code follows: class Eval: def __init__(self, globals=None, locals=None): self.globals = globals or {} self.locals = locals or None def __getitem__(self, key): if self.locals is None: self.locals = sys._getframe(1).f_locals key = key % self return eval(key, self.globals, self.locals) ## and this one: class Evalx: def __init__(self, localvals = None, globalvals = None): if localvals is None : self.locals = sys._getframe(1).f_locals else : self.locals = locals if globalvals is None : self.globals = sys._getframe(1).f_globals else : self.globals = globals def __getitem__(self,key): return eval(key,self.globals,self.locals) ## either are used the same way: To evaluate code inside of a string ## A larger description can be found at: ## http://code.activestate.com/recipes/66018-evaluating-code-inside-strings/ The execution looks like this: self.content = formatted_string % Evalx() ## where 'self' refers to an object of another class, that uses the ## Eval class Under certain circumstances, the embedded is code *not* executed. By inserting debugging stubs, I can see that the the Eval/Evalx instantiation does occur, but the overloaded function call to __get_item does *not* occur. I have also found that a seemingly unrelated event having to do with file I/O must be causing a side effect. However, to keep things simple, I am first asking the following question: What would cause __get_item__ not to be called? I can confirm by other testing that the embedded codde is properly composed with matching keywords. This is probably the most difficult to resolve problem I've ever run into in python. My lack of understand of the underlying code in the Eval classes is probably a contributing factor. TIA -- Tim tim at johnsons-web.com or akwebsoft.com http://www.akwebsoft.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tutor Digest, Vol 82, Issue 45, Topic 3, Globals
-Original Message- From: tutor-request To: tutor Sent: Fri, Dec 10, 2010 6:33 pm Subject: Tutor Digest, Vol 82, Issue 45 Send Tutor mailing list submissions to tutor@python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor r, via email, send a message with subject or body 'help' to tutor-requ...@python.org You can reach the person managing the list at tutor-ow...@python.org When replying, please edit your Subject line so it is more specific han "Re: Contents of Tutor digest..." oday's Topics: 1. Re: role playing game - help needed (ALAN GAULD) 2. Re: Writing to the terminal? (Alan Gauld) 3. Re: Globals as variables in a tkinter widget (Alan Gauld) 4. Re: the "**" operator? (Alex Hall) 5. Code evaluation inside of string fails with __get_item (Tim Johnson) - Message: 1 ate: Fri, 10 Dec 2010 23:21:22 + (GMT) rom: ALAN GAULD o: Al Stern c: "tutor@python.org" ubject: Re: [Tutor] role playing game - help needed essage-ID: <448643.14907...@web86708.mail.ird.yahoo.com> ontent-Type: text/plain; charset="utf-8" Thanks again Alan. Much clearer now. One final part I don't understand. >>> "%d is the result of %d + %d" % (6+7,6,7) I understand (I think) the 6+7 part but why the ,6,7 after that. I could see how either '6+7' or '6,7' would be the correct format but not both. The format string has 3 percent markers - all numbers. t is therefore expecting 3 values, so I have to give it them. he first marker gets 6+7, ie 13. The second gets 6 he third 7... Look at the first example in the loops topic in my tutorial. t uses variables in the same way rather than literal values, hat might make it more obvious. Maybe :-) HTH, Alan G. - next part -- n HTML attachment was scrubbed... RL: <http://mail.python.org/pipermail/tutor/attachments/20101210/a7647551/attachment-0001.html> -- Message: 2 ate: Fri, 10 Dec 2010 23:42:56 - rom: "Alan Gauld" o: tutor@python.org ubject: Re: [Tutor] Writing to the terminal? essage-ID: ontent-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original Modulok" wrote > Assume I'm working in a command shell on a terminal. Something like tcsh on xterm, for example. I have a program which does *something*. Let's say it counts down from 10. How do I print a value, and then erase that value, replacing it with another value? This is one of those things that sounds like it should be easy but is n act deceptively difficult to get right! It all depends on your terminal, and there are dozens of different erminal ypes and settings. Thats why Unix has a terminfo (or in some Unices ermcap - even they can't agree! :-) library to define the different erminal ypes and try to bring some sanity to proceedings.But you need to earn the basic terminal control codes. In this case you need the backspace code which is Ctrl-H or chr(8). Try this >>> print "spam" + "chr(8)*2+"ear" If your terminal recognises chr(8) as backspace you should ee "spear". If it doesn't you'll see someting like: spam^h^hear The only foolproof way to do this kind of thing is to use a library ike urses which allows you to positioon the cursor and overwrite whatever as there. But curses is non-trivial to use - not ridiculously hard, ut on trivial. You can get a basic intro to curses in the event-driven topic f my tutorial. BTW there is quite a good writeup on terminfo here: ttp://tldp.org/HOWTO/Text-Terminal-HOWTO-16.html nd, as usual, Wikipedia has a fair writeup. -- lan Gauld uthor of the Learn to Program web site ttp://www.alan-g.me.uk/ - Message: 3 ate: Sat, 11 Dec 2010 00:06:19 - rom: "Alan Gauld" o: tutor@python.org ubject: Re: [Tutor] Globals as variables in a tkinter widget essage-ID: ontent-Type: text/plain; format=flowed; charset="iso-8859-1"; reply-type=original echo...@aol.com> wrote > This code produces a good run. Not sure what you mean by that. What is "a good run"? > from tkinter import * root = Tk() class Application(Frame): global sv, Ptype, PtypeI, sel_rate_label, label This is bizarre. lobals are generally considered evil and to be avoided if possible. ne way to avoid globals is to use classes. o why on earth are you trying to introduce globals ionto a class? hat do you think you will achieve that using class variables can't? > label = Label(root) Ptype = 999 PtypeI = IntVar() W = 5 Y = 4 And in fact most of these should probably be instance ariables defined within your init() method... def sel(self): global W global Y Ptype = P