> > On 26 Dec 2002 05:31:07 -0800, aztech1200@yahoo.com (Az Tech) wrote:
> >
> > >Hello group,
> > >
> > >Platform: ActivePython 2.2.1 on Windows 98 - but nothing OS-specific
> > >in the code.
> > >This question is about how to return a list/dictionary from a method
> > >(of a class) in such a way that it stays "read-only" to the caller -
> > >or any other technique that is equivalent in terms of effect. Read on
>
Hi people,
Some had suggested using the new 'property' feature of Py 2.2 to solve
this problem.
I tried it out, but it does not work unless I do a copy of the self.list
or self.dict before returning it.
Sample code and output below.
# New_2.2_deep_copy_nested_list01.py
# Program to test deep copy of nested list.
class BinaryFile(object):
import copy
def __init__(self):
pass
def make_list2(self):
self.__a_list2 = [ [1, 2], [3, 4], [5, 6] ]
def get_list2(self):
t_list2 = copy.deepcopy(self.__a_list2)
return t_list2
# set_list2() not defined
# del_list2() not defined
list2 = property(get_list2, None,
None,
"Two-level nested list")
def main():
bf = BinaryFile()
bf.make_list2()
#print "bf.get_list2() = ", bf.get_list2() #1
print "bef mod, bf.list2 = ", bf.list2 #2
#bf.list2 = [] #3
bf.__a_list2 = [ [0], [1] ]
print "aft mod, bf.list2 = ", bf.list2 #4
print "bf.__a_list2 = ", bf.__a_list2
if __name__ == '__main__':
main()
Output:
>>> bef mod, bf.list2 =
>>> [[1, 2], [3, 4], [5, 6]]
>>> aft mod, bf.list2 =
>>> [[1, 2], [3, 4], [5, 6]]
>>> bf.__a_list2 =
>>> [[0], [1]]
>>>
[Note: the last two lines of the output above show that it is still
possible, though, to assign to the instance's __a_list2 member - even
though this does not affect the value of the property. Is this some kind
of 'shadowing' of the member variable ?
(Used the same printing of id() both in the method and in the caller,
and it returned the same value. )
Was able to modify the member variable using the return value of the
method. The only way in which I could prevent it from being modified
was by making my self.list or self.dict as 'private', using a leading
double underscore, e.g. self.__list, as in the code above.
Also, I can get the desired result without using property at all,
simply by doing a copy (or a copy.deepcopy()) of the list/dict.
I've finally settled on this approach:
import copy
.
.
.
then, in the method, do hand-coded copy if the element is a 'scalar'
variable (a la Perl), else, if a list/dict, do a copy.deepcopy(list/dict)
and then return that copy.
Just FYI.
Az
P.S.
A partial answer to Bengt - you're right, the caller doesn't need to access the data *as* a dict - he just needs to access the individual items. I was just using a dict because I was enhancing this program from an earlier version in which I used a dict - because at that time I thought it would make it more caller-friendly (even though I was both the caller and the callee) to let the items be requested by name (e.g. file_data['file_ver'], file_data['creator'], etc.) than by indexing into the struct. That version of the app was not using classes/OO, and was a monolithic program, so there was no real need to make the return value read-only.
This is a multi-part message in MIME format.
------=_NextPart_000_001D_01C2B36B.E3A6FEC0
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
hi,
(i don't like to cross-post, but i'd sent this message originally one =
week ago to python-help@python.org and never received a response.)
i just installed ActivePython-2.2.2-224 on Windows 2000 (no Service =
Pack). don't think it matters, but i'm running a multi-boot system and =
Python has been installed on my (win2k) partition 'H:\' instead of =
'C:\'.
Python works, and Tkinter works, but not the PythonWin IDE. as soon as =
i open up the PythonWin IDE i get a popup window labelled 'Traceback =
when executing InitInstance handler'. the text inside this popup is as =
follows:
File =
"H:\Python22\Lib\site-packages\Pythonwin\pywin\framework\intpyapp.py", =
line 163, in InitInstance
import interact
File =
"H:\Python22\Lib\site-packages\Pythonwin\pywin\framework\interact.py", =
line 26, in ?
import winout
File =
"H:\Python22\Lib\site-packages\Pythonwin\pywin\framework\winout.py", =
line 228, in ?
import pywin.scintilla.view
File =
"H:\Python22\Lib\site-packages\Pythonwin\pywin\scintilla\view.py", line =
16, in ?
import bindings
File =
"H:\Python22\Lib\site-packages\Pythonwin\pywin\scintilla\bindings.py", =
line 6, in ?
import keycodes
File =
"H:\Python22\Lib\site-packages\Pythonwin\pywin\scintilla\keycodes.py", =
line 25, in ?
_better_names =3D [
exceptions.AttributeError: 'module' object has no attribute 'VK_RETURN'
please note that i've tried starting the ActivePython installer package =
and running the 'Repair' option, as well as completely uninstalling =
ActivePython and then reinstalling it (including deleting all Python =
registry items before reinstalling), but it just ain't workin'. i hope =
noone's going to suggest that i install a Win2k Service Pack...i'd like =
to avoid this.
any help would be greatly appreciated...oh, yeah - i'm 99% sure my =
ActivePython installer package is not damaged, 'cause it's the same =
installation file i've used to successfully install ActivePython on =
another Win2K computer.
thanks,
tom
------=_NextPart_000_001D_01C2B36B.E3A6FEC0
Content-Type: text/html;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
hi,
(i don't like to cross-post, but i'd =
sent this=20
message originally one week ago to python-help@python.org an=
d never=20
received a response.)
i just installed ActivePython-2.2.2-224 =
on Windows=20
2000 (no Service Pack). don't think it matters, but i'm running a=20
multi-boot system and Python has been installed on my (win2k) partition =
'H:\'=20
instead of 'C:\'.
Python works, and Tkinter works, but =
not the=20
PythonWin IDE. as soon as i open up the PythonWin IDE i get a =
popup window=20
labelled 'Traceback when executing InitInstance handler'. the text =
inside=20
this popup is as follows:
File=20
"H:\Python22\Lib\site-packages\Pythonwin\pywin\framework\intpyapp.py", =
line 163,=20
in InitInstance
import interact
File=20
"H:\Python22\Lib\site-packages\Pythonwin\pywin\framework\interact.py", =
line 26,=20
in ?
import winout
File=20
"H:\Python22\Lib\site-packages\Pythonwin\pywin\framework\winout.py", =
line 228,=20
in ?
import pywin.scintilla.view
File=20
"H:\Python22\Lib\site-packages\Pythonwin\pywin\scintilla\view.py", line =
16, in=20
?
import bindings
File=20
"H:\Python22\Lib\site-packages\Pythonwin\pywin\scintilla\bindings.py", =
line 6,=20
in ?
import keycodes
File=20
"H:\Python22\Lib\site-packages\Pythonwin\pywin\scintilla\keycodes.py", =
line 25,=20
in ?
_better_names =3D =
[
exceptions.AttributeError:=20
'module' object has no attribute 'VK_RETURN'
please note that i've tried starting =
the=20
ActivePython installer package and running the 'Repair' option, as well =
as=20
completely uninstalling ActivePython and then reinstalling it (including =
deleting all Python registry items before reinstalling), but it just =
ain't=20
workin'. i hope noone's going to suggest that i install a Win2k =
Service=20
Pack...i'd like to avoid this.
any help would be greatly=20
appreciated...oh, yeah - i'm 99% sure my ActivePython installer package =
is not=20
damaged, 'cause it's the same installation file i've used to =
successfully=20
install ActivePython on another Win2K computer.
thanks,
tom
------=_NextPart_000_001D_01C2B36B.E3A6FEC0--
From altis@semi-retired.com Fri Jan 3 15:13:41 2003
From: altis@semi-retired.com (Kevin Altis)
Date: Fri Jan 3 15:13:41 2003
Subject: [Tutor] Comments
In-Reply-To: <14429062880.20030103161907@roadrunner.nf.net>
Message-ID:
There are a few ways. You could comment out every line
# code
# ...
# won't run
comment out the block with triple quotes
"""
code
...
won't run
"""
or you could just indent the whole block and stick a test in front so it
won't be executed
if 0:
code
...
won't run
The last one is probably best if what you really want is something like
if DEBUG:
print ...
where you define DEBUG as 1 or 0 at the top of the module.
ka
> -----Original Message-----
> From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
> Adam Vardy
> Sent: Friday, January 03, 2003 11:49 AM
> To: tutor@python.org
> Subject: [Tutor] Comments
>
>
>
> How is it you phrase comments? When I'd like to take out a block and
> experiment with the rest, what's the method?
>
> {
>
> code
> ...
>
> won't run
>
> }
>
> print "will run"
>
> --
> Adam Vardy
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From aztech1200@yahoo.com Fri Jan 3 16:45:02 2003
From: aztech1200@yahoo.com (Aztech Guy)
Date: Fri Jan 3 16:45:02 2003
Subject: [Tutor] Applications/examples of some advanced Py features, please !
Message-ID: <20030103214439.9023.qmail@web9801.mail.yahoo.com>
--0-1059684377-1041630279=:8758
Content-Type: text/plain; charset=us-ascii
Hi Python gurus,
Can anyone please give some examples / applications of the use of the following advanced (advanced to me, at least :-) features of Python :
1. lambda
2. nested functions - a little info was given by Danny in reply to my earlier post on local-static variables, but I would like more.
3. Thoughts on implementing Interfaces in Py - a la Java interfaces.
I am, and will be doing more, on reading the docs and googling for this, but would anyway appreciate inputs from those who know this stuff.
I have a specific reason for the above questions- apart from general interest, of course -> I am planning to write a game-playing program in Py which will have features somewhat AI - ish. I don't have any background in AI; nor much in functional programming. I do understand recursion though. I suspect that some of the above 3 points will help me to write my app in a better way. though not sure, of course. Hence the request for examples.
For all of the above 3 points, I'm interested in :
- code examples of their use
- in what way their use makes code simpler, or maybe makes code possible that could not be written otherwise ('possible' in practical terms - I'm - vaguely - aware of the fact that all languages are supposed to be theoretically 'Turing-equivalent' or some such term - but what I mean is that if something is going to take a huge amount more code in some other language, or jumping through hoops, then I don't call it practically equivalent).
Thanks !
Az
---------------------------------
Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now
--0-1059684377-1041630279=:8758
Content-Type: text/html; charset=us-ascii
Hi Python gurus,
Can anyone please give some examples / applications of the use of the following advanced (advanced to me, at least :-) features of Python :
1. lambda
2. nested functions - a little info was given by Danny in reply to my earlier post on local-static variables, but I would like more.
3. Thoughts on implementing Interfaces in Py - a la Java interfaces.
I am, and will be doing more, on reading the docs and googling for this, but would anyway appreciate inputs from those who know this stuff.
I have a specific reason for the above questions- apart from general interest, of course -> I am planning to write a game-playing program in Py which will have features somewhat AI - ish. I don't have any background in AI; nor much in functional programming. I do understand recursion though. I suspect that some of the above 3 points will help me to write my app in a better way. though not sure, of course. Hence the request for examples.
For all of the above 3 points, I'm interested in :
- code examples of their use
- in what way their use makes code simpler, or maybe makes code possible that could not be written otherwise ('possible' in practical terms - I'm - vaguely - aware of the fact that all languages are supposed to be theoretically 'Turing-equivalent' or some such term - but what I mean is that if something is going to take a huge amount more code in some other language, or jumping through hoops, then I don't call it practically equivalent).
Thanks !
Az
Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now
--0-1059684377-1041630279=:8758--
From ramrom@earthling.net Fri Jan 3 17:40:34 2003
From: ramrom@earthling.net (Bob Gailer)
Date: Fri Jan 3 17:40:34 2003
Subject: [Tutor] subclass of list
In-Reply-To: <13827711637.20030103155636@roadrunner.nf.net>
References: <7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1.systemhost.net>
<7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1.systemhost.net>
Message-ID: <5.2.0.9.0.20030103142844.02baaac8@66.28.54.253>
--=======1596208D=======
Content-Type: text/plain; x-avg-checked=avg-ok-1CF2B71; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit
In the latest Python one can subclass types, such as list.
What is the benefit? What can one do with an instance of a subclass of list?
I'd like to think that, given:
class MyList(list):
def __init__(self, list)
self.list = list
x = MyList([3,4])
x[0] would then return 3?
Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=======1596208D=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1CF2B71
Content-Disposition: inline
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002
--=======1596208D=======--
From ramrom@earthling.net Fri Jan 3 17:47:02 2003
From: ramrom@earthling.net (Bob Gailer)
Date: Fri Jan 3 17:47:02 2003
Subject: [Tutor] Applications/examples of some advanced Py
features, please !
In-Reply-To: <20030103214439.9023.qmail@web9801.mail.yahoo.com>
Message-ID: <5.2.0.9.0.20030103154019.02ba0508@66.28.54.253>
--=======41CB536C=======
Content-Type: text/plain; x-avg-checked=avg-ok-1CF2B71; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit
Regarding lambda, it is an abbreviated way of defining a function. The
limitation is that the body of the function is one expression whose value
is returned.
f = lambda x, y:x+y
is the same as
def f(x, y):
return x+y
It is useful when you only need to refer to the function once, as in:
filter(lambda x:x>5, some-sequence-of-numbers)
That's all I have to say about lambda, except that, if you want to use it
with list comprehension the syntax is a little tricky:
[(lambda x:x>5)(item) for item in some-sequence-of-numbers]
Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=======41CB536C=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1CF2B71
Content-Disposition: inline
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002
--=======41CB536C=======--
From Don Arnold"
Message-ID: <0b1801c2b37a$d2632490$8510ba3f@defaultcomp>
----- Original Message -----
From: "Adam Vardy"
To:
Sent: Friday, January 03, 2003 1:45 PM
Subject: [Tutor] Tkinter
>
> Experimenting with TK, I came up on difficulties. Like, in one
> program, the window is there but whenever the pointer is over the
> window, there is always an hourglass. Can't see anything
> wrong.
I don't know about this one, but does it happen when you execute the script
from the command prompt? Most IDEs have their own event loop that doesn't
play nice with Tkinter.
>
> In another example, I have a button on the window. And a function is
> set to run for that. But it runs right away. And nothing happens when
> I hit the button!
>
> --
> Adam Vardy
This is a pretty common error. Make sure the callback you supply to the
button constructor does _not_ include the parentheses. For example:
b = Button(master, text="OK", command=self.ok)
assigns the function 'self.ok' as the callback to be executed when the
button is pressed. However,
b = Button(master, text="OK", command=self.ok( ) )
executes self.ok( ) once when the button is istantiated and assigns the
result to the button's 'command' attribute.
For more info on Tkinter, you might want to check out
http://www.pythonware.com/library/tkinter/introduction/index.htm .
HTH,
Don
From dman@dman.ddts.net Fri Jan 3 18:01:01 2003
From: dman@dman.ddts.net (Derrick 'dman' Hudson)
Date: Fri Jan 3 18:01:01 2003
Subject: [Tutor] Re: Embeding Python... (Please help !)
In-Reply-To: <029601c2b34f$0feaa760$8ae4e9c0@sxapc>
References: <029601c2b34f$0feaa760$8ae4e9c0@sxapc>
Message-ID: <20030103230003.GA25215@dman.ddts.net>
--G4iJoqBmSsgzjUCe
Content-Type: text/plain; charset=us-ascii
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable
On Fri, Jan 03, 2003 at 12:39:26PM -0500, Sebastien Auclair wrote:
| Our problem is so trivial, it's crazy that we can't find anything on the =
net
| that would help us.
|=20
| We are trying to use the function PyArg_Parse and others in order to simp=
ly
| get a correctly casted pointer to a Python Class instance.
In C or C++ the type will be known as "PyObject".
| That python class is in fact a subclass of a C++ class defining an
| interface. Our python file knows this interface class through SIP binding=
s.
|=20
| There are some examples of how we can get simple C type values (strings,
| int, float...) from Python types but nothing on pointers to class... We
| tried to use the O& option but it doesn't work.
| PyObject * v1 =3D PyObject_CallObject(func1,NULL);
|=20
| interface * interf =3D (interface*) v1; // OF COURSE THIS DOESN'T WORK B=
UT
| YOU GET THE IDEA....
The problem here is you want to throw python away. The python object
isn't _really_ a implementation of the interface. It is just a
PyObject. It just so happens that the contents of the PyObject make
it behave (in python) as an implementation of the interface. You need
to use the python API to interact with and extract the lower-level
data from the PyObject. For example, the interafce defines a method
named "update" you would call it with
PyObject_CallMethod(v1, "update", NULL); // it returns Py_None
Now you want to use the "getValue" method on the interface to get the
(integer) value from the class instance.
PyObject* presult =3D PyObject_CallObject(v1, "getValue", NULL);
int result =3D (int) PyInt_AsLong( presult ) ;
Py_DEREF(presult) ; presult =3D NULL ;
This might seem like it is overkill and too much effort -- after all,
you have the interface declared in C++, but since the object itself is
a python object all of its life cycle must be managed by python. The
python interpreter is needed to enforce the Python, not C++, semantics
of the object. The C (or C++) code for managing python objects will
always be much longer and more tedious than the equivalent python code
because the C (C++) compiler doesn't provide the same runtime services
for C (C++) objects that the python interpreter provides for python
objects..
NOTE: In this example code and in the code you posted there is no
error checking. If a python C-level function returns NULL that
means an exception has occured.
http://python.org/doc/current/api/exceptions.html
HTH,
-D
--=20
Windows, hmmm, does it come with a GUI interface that works or just
pretty blue screens?
=20
http://dman.ddts.net/~dman/
--G4iJoqBmSsgzjUCe
Content-Type: application/pgp-signature
Content-Disposition: inline
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org
iEYEARECAAYFAj4WFfMACgkQO8l8XBKTpRR07gCfTZ1QD0r9kweyRyJlxijJjJoU
FZsAnRUOVyrxwrw1kRB5MGSvefG/Rng6
=Yc8O
-----END PGP SIGNATURE-----
--G4iJoqBmSsgzjUCe--
From Janssen@rz.uni-frankfurt.de Fri Jan 3 18:48:02 2003
From: Janssen@rz.uni-frankfurt.de (Michael Janssen)
Date: Fri Jan 3 18:48:02 2003
Subject: [Tutor] subclass of list
In-Reply-To: <5.2.0.9.0.20030103142844.02baaac8@66.28.54.253>
Message-ID:
On Fri, 3 Jan 2003, Bob Gailer wrote:
> In the latest Python one can subclass types, such as list.
> What is the benefit? What can one do with an instance of a subclass of list?
I made very slow processes in understanding those OOP stuff, but one of
the first things I've done with it was subclassing dictionaries and
strings (sorry, not lists, but it's the same: adaptation of datastructures
to personal needs).
As a beginnner I don't subclass dict/list/string directly but the
UserDict/List/String modules: These classes reimplement the exact
behaviour of dict-list-strings. When you modify (subclass) these classes
you possibly don't overwrite some essential functionality (Because you
can take a look at the functionality in UserDict/andsoon).
If subclassed UserDict in order to provide some more methods especially
for the needs of my programm: it uses an internal "data-container" which
is in core a dict (i.e. was a dict in early programm-versions). I
recognize that I was constantly doing the same jobs with this data
containing dict and so I decided to enhance UserDict with methods for this
jobs. My life was easier since then, because I needn't to paste and copy
the code any more but use the new methods (which means: I needn't to think
of the internal implementation any more)
Some days ago I have added a "readline" methods to UserString: I was
struggling with the Classes in mailbox, mimetools and multifile moduls
which all want to get a filedescriptor to read from. Instantiate those
Classes with strings fails because of the missing readline method. Now it
*works* (Disclaimer: this was purely to learn how thoses Classes work; I
have removed this "workaround-code" and go on with real filedescriptors.)
For lists, it can be: You don't want to write median(AList) (1) but
rather: AList.median(). Or you want to compair two list not in the
implementet way (That is campaire the first values, if equally the seconds
and so on) but for example by its median. therefore you simply overwrite
the __cmp__ method. Or you want to get something completly different as a
two dimensional array. Perhaps subclassing list or UserList is a good
start point for this.
In short: You can put additional methods into your own classes and forget
about the implementation.
You can use __operator__ methods (look in
doc/lib/module-operator.html for this) to call methods "without calling
them directly" (hope you understand what I mean). With these operators you
can overwrite the *behaviour* of list/dict/string
On a side note: I've got my first inside in what OOP is for, as someone
wrotes that "OOP means to put the data and functionality together". From
then on, I rewrote my script, which consists of functions to handel input
and store it into datastructures and functions to retrieve the data and
transform it for output. now this script consist of a modified UserDict
which makes much of the work self and functions to call my UserDict
instance (that's not OOP, but it's a step, I believe ;-). Therefore I'm
comming from the datastructure side and go to put some functionality into
data, which might be a kind of OOP; but: only one kind of ;-)
Michael
> I'd like to think that, given:
>
> class MyList(list):
> def __init__(self, list)
> self.list = list
> x = MyList([3,4])
>
> x[0] would then return 3?
When you take a look into UserList.py you might find out yourself, why
this isn't already working ;-)
>
> Bob Gailer
> mailto:ramrom@earthling.net
> 303 442 2625
>
From dyoo@hkn.eecs.berkeley.edu Fri Jan 3 19:47:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri Jan 3 19:47:01 2003
Subject: [Tutor] Applications/examples of some advanced Py features,
please !
In-Reply-To: <5.2.0.9.0.20030103154019.02ba0508@66.28.54.253>
Message-ID:
On Fri, 3 Jan 2003, Bob Gailer wrote:
> Regarding lambda, it is an abbreviated way of defining a function. The
> limitation is that the body of the function is one expression whose
> value is returned.
>
> f = lambda x, y:x+y
>
> is the same as
>
> def f(x, y):
> return x+y
Hi Bob,
Python's lambda expressions are deliberately weakened to force people to
use them only for simple stuff --- Python programs favor giving real names
to functions. In contrast, in some other languages, like Scheme and
Ocaml, the lambda concept is allowed more expressivity, so lambda is more
prevalent in those languages.
> It is useful when you only need to refer to the function once, as in:
> filter(lambda x:x>5, some-sequence-of-numbers)
>
> That's all I have to say about lambda, except that, if you want to use
> it with list comprehension the syntax is a little tricky:
>
> [(lambda x:x>5)(item) for item in some-sequence-of-numbers]
I think you mean:
[item for item in some_sequence_of_numbers
if (lambda x: x>5)(item)]
to do a filtering kind of operation. But yes, this is pretty darn ugly.
List comprehensions and lambdas don't mix very well, but that's probably
because they're not supposed to. *grin*
A functional programmer would use the filter() function instead of a list
comprehension:
###
>>> some_sequence_of_numbers = [3,1,4,1,5,9,2,6]
>>> filter(lambda x: x>5, some_sequence_of_numbers)
[9, 6]
###
which, if we cross our eyes funny, can scan as "Filter a list of elements
out of some_sequence_of_numbers, chosen by this particular boolean
function."
Just to contrast with another language, let's see what this might look
like in OCaml:
(*** OCaml code --- the stuff with # in the beginning is what I type. ***)
# let some_sequence_of_numbers = [3;1;4;1;5;9;2;6];;
val some_sequence_of_numbers : int list = [3; 1; 4; 1; 5; 9; 2; 6]
# List.filter (function x -> x > 5) some_sequence_of_numbers;;
- : int list = [9; 6]
(***)
Good, at least we get a similar result. *grin*
Lambda is pretty much used as a convenient way of writing quicky one-shot
functions for "mapping" and "filtering". In computer science theory,
they're pretty important --- in the functional-based languages, lambdas
are a fundamental building block of computation --- but in Python, they
play a backstage role: it's often a good thing to just define a new
function using 'def'.
Good luck!
From beercanz@hotmail.com Fri Jan 3 21:09:02 2003
From: beercanz@hotmail.com (Guess Who? Me)
Date: Fri Jan 3 21:09:02 2003
Subject: [Tutor] Help.
Message-ID:
This is what I've done:
a=0
b=0
######
print "Enter 2 numbers!"
a=input("Give me the first number so I may munch it!")
b=input("Give me the second number so I may munch it!")
######
if a+b < 100:
print "That number 'aint so big!"
elif a+b > 100:
print "That number is huge!"
else:
print "That number is on the edge."
The question:
when I try to say, 'Sum=a+c', and plug that in for a+b in the if and elif
statements, it doesn't work. I'll plug in sum for a+b and put sum=a+b at the
top, and the program thinks every number 'aint so big - strange. Any help is
appreciated, I hope the question was clear enough.
Thanks!
Travis
_________________________________________________________________
MSN 8 with e-mail virus protection service: 2 months FREE*
http://join.msn.com/?page=features/virus
From ramrom@earthling.net Fri Jan 3 21:50:14 2003
From: ramrom@earthling.net (Bob Gailer)
Date: Fri Jan 3 21:50:14 2003
Subject: [Tutor] Help.
In-Reply-To:
Message-ID: <5.2.0.9.0.20030103194441.02c20e18@66.28.54.253>
--=======4AA0B0E=======
Content-Type: text/plain; x-avg-checked=avg-ok-1CF2B71; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit
At 02:03 AM 1/4/2003 +0000, Guess Who? Me wrote:
>a=0
>b=0
>######
>print "Enter 2 numbers!"
>a=input("Give me the first number so I may munch it!")
>b=input("Give me the second number so I may munch it!")
>######
>if a+b < 100:
> print "That number 'aint so big!"
>elif a+b > 100:
> print "That number is huge!"
>else:
> print "That number is on the edge."
>
>The question:
>when I try to say, 'Sum=a+c', and plug that in for a+b in the if and elif
>statements, it doesn't work. I'll plug in sum for a+b and put sum=a+b at
>the top, and the program thinks every number 'aint so big - strange. Any
>help is appreciated, I hope the question was clear enough.
Please provide the code that doesn't work. It's very hard to guess what it
looks like. If I took you literally, I'd expect:
sum a+b # at the top, as you say
a=0
b=0
etc which clearly won't work.
Also note that assigning a=0 and b=0 accomplishes nothing, as they are
replaced by the inputs.
Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=======4AA0B0E=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1CF2B71
Content-Disposition: inline
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002
--=======4AA0B0E=======--
From ramrom@earthling.net Fri Jan 3 22:15:01 2003
From: ramrom@earthling.net (Bob Gailer)
Date: Fri Jan 3 22:15:01 2003
Subject: [Tutor] subclass of list
In-Reply-To:
References: <5.2.0.9.0.20030103142844.02baaac8@66.28.54.253>
Message-ID: <5.2.0.9.0.20030103195708.02c31d60@66.28.54.253>
--=======7F796E11=======
Content-Type: text/plain; x-avg-checked=avg-ok-1CF2B71; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit
Your reference to UserList helped. One thing I missed was that the internal
list can be set by passing a list as the argument to the instantiation call.
>>> class UL(UserList):pass
>>> ul=UL([1,2,3])
>>> ul
[1,2,3]
>>> ul.data
[1,2,3]
AND (using list instead of UserList)
>>> class UL(llist):pass
>>> ul=UL([1,2,3])
>>> ul
[1,2,3]
HOWEVER:
>>> ul.data
AttributeError: 'UL' object has no attribute 'data'
A little "thinking and experimenting" led to: instead of manipulating
self.data one now manipulates self:
>>> class UL(list):
... def a(self):
... self[0]+=1
>>> ul=UL([1,2,3])
>>> ul.a()
>>> ul
[2, 2, 3]
Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=======7F796E11=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1CF2B71
Content-Disposition: inline
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002
--=======7F796E11=======--
From glingl@aon.at Sat Jan 4 00:37:01 2003
From: glingl@aon.at (Gregor Lingl)
Date: Sat Jan 4 00:37:01 2003
Subject: [Tutor] subclass of list
References: <7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1.systemhost.net> <7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1.systemhost.net> <5.2.0.9.0.20030103142844.02baaac8@66.28.54.253>
Message-ID: <3E1672D4.8010202@aon.at>
This is a multi-part message in MIME format.
--------------030307060502060304060109
Content-Type: text/plain; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 7bit
Bob Gailer schrieb:
> In the latest Python one can subclass types, such as list.
Hi Bob!
If you want to subclass a built-in type, you have to calls the
constructor of the parent-class in the same way as if you
subclass any class. That means, as a "class"-method, which goes like this:
>>> class MyList(list):
... def __init__(self, liste):
... list.__init__(self,liste)
...
>>> a = MyList([3,4])
>>> a
[3, 4]
>>> a[0]
3
You now can use any list method with a:
>>> a.append(1001)
>>> a
[3, 4, 1001]
>>>
>
> What is the benefit? What can one do with an instance of a subclass of
> list?
For instance - as an appendix to the median-thread from two
or three days ago - you may create a class of Lists, which know their
own median:
class mlist(list):
def __init__(self, aList):
list.__init__(self,aList)
def median(self):
# according to Don Arnolds implementation
tempList = self[:]
tempList.sort()
listLen = len(tempList)
middleIndex = (listLen - 1) // 2
if listLen % 2 == 1:
#odd number of elements. return middle element
return tempList[middleIndex]
else:
#even number of element. return average of middle 2 elements
return (tempList[middleIndex] + tempList[middleIndex + 1]) / 2.0
if __name__ == '__main__':
theList = mlist([2,3,4,5,6])
print theList
print 'median = ', theList.median()
theList = mlist([1,2,6,7])
print theList
print 'median = ', theList.median()
Running this program you get:
[2, 3, 4, 5, 6]
median = 4
[1, 2, 6, 7]
median = 4.0
You may find another interesting example in the attachment.
There is defined a class Turm, which means tower :-) ,
derived from list. Actually there the constructor list.__init__
needs not to be called, because newly constructed Turms
always are empty.
Regards, Gregor
>
> I'd like to think that, given:
>
> class MyList(list):
> def __init__(self, list)
> self.list = list
> x = MyList([3,4])
>
> x[0] would then return 3?
>
> Bob Gailer
--------------030307060502060304060109
Content-Type: text/plain;
name="hanoig.py"
Content-Transfer-Encoding: 8bit
Content-Disposition: inline;
filename="hanoig.py"
### Python für Kids - Kapitel B4 ###
# Autor: Gregor Lingl
# Datum: 29. 9. 2002
# hanoig.py
from Tkinter import Tk, Canvas
from Canvas import Rectangle
# from scheibe import Scheibe
usingIDLE = 0 # auf 1 setzen, wenn das Programm von IDLE
# aus ausgeführt wird.
class Scheibe(Rectangle):
"Bewegliches Rechteck auf einem Tkinter-Canvas"
def __init__(self,cv,pos,laenge,hoehe):
x0, y0 = pos
x1, x2 = x0-laenge/2.0, x0+laenge/2.0
y1, y2 = y0-hoehe, y0
Rectangle.__init__(self,cv,x1,y1,x2,y2,
fill = "red")
def bewege_nach(self, x, y):
from math import sqrt
x1,y1,x2,y2 = self.coords()
x0, y0 = (x1 + x2)/2, y2
dx, dy = x-x0, y-y0
d = sqrt(dx**2+dy**2)
schritte = int(d/10) + 1
dx, dy = dx/schritte, dy/schritte
for i in range(schritte):
self.move(dx,dy)
self.canvas.update()
self.canvas.after(20)
class Turm(list):
def __init__(self, x, y, h):
self.x = x
self.y = y
self.h = h
def top(self):
return self.x, self.y - len(self)*self.h
def hanoi(n,von,nach,hilf):
if n==1:
move(von,nach)
else:
hanoi(n-1,von,hilf,nach)
hanoi(1,von,nach,hilf)
hanoi(n-1,hilf,nach,von)
def move(von_turm, nach_turm):
scheibe = von_turm.pop()
x1, y1 = von_turm.top()
x2, y2 = nach_turm.top()
scheibe.bewege_nach(x1,20)
scheibe.bewege_nach(x2,20)
scheibe.bewege_nach(x2,y2)
nach_turm.append(scheibe)
def hanoispiel(n):
"""Führt ein Hanoi-Spiel mit n Scheiben aus:"""
root = Tk() # ein Fenster
root.title("Türme von Hanoi") # mit Titel,
cv = Canvas(root,width=440,height=210) # eine Leinwand -
cv.pack() # - aufspannen
pflock1 = Rectangle(cv, 75, 40, 85,190,fill='blue')
pflock2 = Rectangle(cv,215, 40,225,190,fill='blue')
pflock3 = Rectangle(cv,355, 40,365,190,fill='blue')
boden = Rectangle(cv, 5,190,435,200,fill='black')
turm_a = Turm( 80, 190, 15)
turm_b = Turm(220, 190, 15)
turm_c = Turm(360, 190, 15)
for i in range(n): # turm_a aufbauen
laengen_differenz = 100 // n
laenge = 120 - i * laengen_differenz
s = Scheibe( cv, turm_a.top(), laenge, 13)
turm_a.append(s)
hanoi(n, turm_a, turm_b, turm_c)
if not usingIDLE:
root.mainloop()
if __name__ == '__main__':
hanoispiel(7)
--------------030307060502060304060109--
From tony@tcapp.com Sat Jan 4 01:07:01 2003
From: tony@tcapp.com (Tony Cappellini)
Date: Sat Jan 4 01:07:01 2003
Subject: [Tutor] PythonWin IDE Problem on Win2K with ActivePython
Message-ID: <5.1.0.14.0.20030103221352.03f6ce10@smtp.sbcglobal.net>
Tom,
I am using Win2k SP3, but I'm using PythonWin32 1.50, on Python 2.2.2, I
don't see this problem.
What is Active Python ?
From glingl@aon.at Sat Jan 4 01:12:02 2003
From: glingl@aon.at (Gregor Lingl)
Date: Sat Jan 4 01:12:02 2003
Subject: [Tutor] Applications/examples of some advanced Py features,
please !
References:
Message-ID: <3E167961.7090302@aon.at>
>
>
>
>Lambda is pretty much used as a convenient way of writing quicky one-shot
>functions for "mapping" and "filtering". In computer science theory,
>they're pretty important --- in the functional-based languages, lambdas
>are a fundamental building block of computation --- but in Python, they
>play a backstage role: it's often a good thing to just define a new
>function using 'def'.
>
>
Just to quote Guido (from:
http://www.python.org/doc/essays/ppt/regrets/PythonRegrets.pdf )
. I've never liked lambda
- crippled (only one expression)
- confusing (no argument list parentheses)
- can use a local function instead
Gregor
From glingl@aon.at Sat Jan 4 02:36:09 2003
From: glingl@aon.at (Gregor Lingl)
Date: Sat Jan 4 02:36:09 2003
Subject: [Tutor] subclass of list
References: <7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1.systemhost.net> <7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1.systemhost.net> <5.2.0.9.0.20030103142844.02baaac8@66.28.54.253> <3E1672D4.8010202@aon.at>
Message-ID: <3E168EF4.5010200@aon.at>
:-( ! During preparing breakfast I suddenly recognized, that I had
written some nonsense here - (perhaps I should have breakfast
*before* writing emails.)
Gregor Lingl schrieb:
>
> Hi Bob!
> If you want to subclass a built-in type, you have to call the
> constructor of the parent-class in the same way as if you
> subclass any class. That means, as a "class"-method, which goes like
> this:
>
> >>> class MyList(list):
> ... def __init__(self, liste):
> ... list.__init__(self,liste)
> ...
> >>> a = MyList([3,4])
> >>> a
> [3, 4]
> >>> a[0]
> 3
This is only necessary if you additionally do something else in
the constructor. Otherwise, the constructor of the parent-class is
called automatically.
So the following simple code also works:
>>> class MyList(list):
... pass
...
>>> a = MyList([3,4])
>>> a
[3, 4]
>>> a[1]
4
>>>
Of course, MyList here is nothing more than an ordinary list.
But also mlist doesn't need special initialization:
>>> class mlist(list):
def median(self):
# according to Don Arnolds implementation
tempList = self[:]
tempList.sort()
listLen = len(tempList)
middleIndex = (listLen - 1) // 2
if listLen % 2 == 1:
#odd number of elements. return middle element
return tempList[middleIndex]
else:
#even number of element. return average of middle 2 elements
return (tempList[middleIndex] + tempList[middleIndex + 1]) / 2.0
>>>
>>> a = mlist([1,2,3])
>>> a.median()
2
>>> a = mlist([1,2,3,4])
>>> a.median()
2.5
Sorry for this error!
As an - albeit rather useless ;-) - example for a classe derived from
list, which needs
the call of the constructor of the superclass ma serve the following:
>>> class shortList(list):
... def __init__(self, aList, maxlen=3):
... self.maxlen = maxlen
... list.__init__(self,aList[-maxlen:])
... def append(self, element):
... list.append(self,element)
... if len(self)>3:
... return self.pop(0)
...
>>> a = shortList([2,3,5,7,11,13])
>>> a
[7, 11, 13]
>>> a.append(17)
7
>>> a
[11, 13, 17]
>>>
Here the definition of append (overwriting the orginal method) also shows,
how to call the append method of the superclass, which has to be done
exactly in the same way as it is done with __init__.
If you try to replace list.append(self,element) with self.append(element)
you will see immediatly that this is definitly another append (namely the
one, which is just going to be defined). Maybe this also will create
some insight on why some special syntax is necessary for calling
methods of the parent class.
Hope, this examples + explanations are correct now,
Gregor
From glingl@aon.at Sat Jan 4 04:03:02 2003
From: glingl@aon.at (Gregor Lingl)
Date: Sat Jan 4 04:03:02 2003
Subject: [Tutor] subclass of list - one more correction
References: <7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1.systemhost.net> <7497DCA1C240C042B28F6657ADFD8E097022E1@i2km11-ukbr.domain1.systemhost.net> <5.2.0.9.0.20030103142844.02baaac8@66.28.54.253> <3E1672D4.8010202@aon.at> <3E168EF4.5010200@aon.at>
Message-ID: <3E16A34C.6040101@aon.at>
Gregor Lingl schrieb
>
> As an - albeit rather useless ;-) - example for a classe derived from
> list, which needs
> the call of the constructor of the superclass ma serve the following:
>
> >>> class shortList(list):
> ... def __init__(self, aList, maxlen=3):
> ... self.maxlen = maxlen
> ... list.__init__(self,aList[-maxlen:])
> ... def append(self, element):
> ... list.append(self,element)
> ... if len(self)>3:
# Should read, of course: if len(self) > self.maxlen:
>
> ... return self.pop(0)
> ...
> Sorry. (No more comment, Gregor)
From gp@pooryorick.com Sat Jan 4 09:22:01 2003
From: gp@pooryorick.com (Poor Yorick)
Date: Sat Jan 4 09:22:01 2003
Subject: [Tutor] unicode utf-16 and readlines
Message-ID: <3E16EE3E.6020603@pooryorick.com>
On Windows 2000, Python 2.2.1 open.readlines seems to read lines
incorrectly when the file is encoded utf-16. For example:
>>> fh = open('0022data2.txt')
>>> a = fh.readlines()
>>> print a
['\xff\xfe\xfaQ\r\x00\n', '\x00']
In this example, Python seems to have incorrectly parsed the \n\r
characters at the end of the line. It's an error that one can work
around by slicing off the last three characters of every other list
element, but it makes working with utf-16 files non-intuitive,
especially for beginners. Or am I missing something?
Poor Yorick
gp@pooryorick.com
From skitzomonkey@hotmail.com Sat Jan 4 09:46:01 2003
From: skitzomonkey@hotmail.com (mike O)
Date: Sat Jan 4 09:46:01 2003
Subject: [Tutor] pausing and layout
Message-ID:
I guess I have three questions, the first being: Is there a python command
to pause until the user does something?
Also, how do you get python (when you don't run it in DOS Prompt) to not
auto-exit? I have made a few simple programs, but as soon as it shows the
answer, it exits.
last, I was wondering how you do visual stuff, or make a program run in a
window, instead of in the command prompt screen?
Thanks,
Mike
_________________________________________________________________
STOP MORE SPAM with the new MSN 8 and get 2 months FREE*
http://join.msn.com/?page=features/junkmail
From op73418@mail.telepac.pt Sat Jan 4 10:07:02 2003
From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Sat Jan 4 10:07:02 2003
Subject: [Tutor] pausing and layout
References:
Message-ID: <001301c2b403$c3768060$88190dd5@violante>
----- Original Message -----
From: "mike O"
To:
Sent: Saturday, January 04, 2003 2:45 PM
Subject: [Tutor] pausing and layout
> I guess I have three questions, the first being: Is there a python command
> to pause until the user does something?
>
What do you want exactly? "until the user does something" is a very broad
and general category to receive any useful and concrete answer. Is it input?
Then the raw_input function is probably enough for you. Something like
user_input = raw_input('Give a number, please: ')
And then the program will just halt until the user has given some input and
pressed newline.
> Also, how do you get python (when you don't run it in DOS Prompt) to not
> auto-exit? I have made a few simple programs, but as soon as it shows the
> answer, it exits.
>
Just add a raw_input() call at the end of your program. Then, as I said
earlier the program will pause giving you a chance to look at the output.
> last, I was wondering how you do visual stuff, or make a program run in a
> window, instead of in the command prompt screen?
>
This gets you in the realm of programming called GUI (graphical user
interface) programming. First, you need a GUI toolkit. Python already comes
with one: TKinter but there are others. The one I use is wxPython. But for
an intro to TKinter you can start at:
http://home.att.net/~stephen_ferg/thinking_in_tkinter/index.html
> Thanks,
> Mike
>
With my best regards,
G. Rodrigues
From gp@pooryorick.com Sat Jan 4 10:21:01 2003
From: gp@pooryorick.com (Poor Yorick)
Date: Sat Jan 4 10:21:01 2003
Subject: Keeping DOS prompt/command window open (was [Tutor] pausing and layout)
References:
Message-ID: <3E16FC16.1020009@pooryorick.com>
mike O wrote:
>
>
> Also, how do you get python (when you don't run it in DOS Prompt) to
> not auto-exit? I have made a few simple programs, but as soon as it
> shows the answer, it exits.
>
>
I've never seen my method of doing this posted, which is to opend python
using cmd.exe /k. Here are the details for Windows 2000 (same concept
should work on any version of Windows):
From Windows explorer, go to Tools - Folder Options - File Types
Select the ".py" extension and click "Advanced"
In the "Edit File Type" window, click "New"
In the action field, type in something descriptive, like "Run and remain"
In the "Application used to perform action" field, add the following line:
cmd.exe /k C:\Python22\python.exe "%1" %*
click "OK"
If you want to, set your new action as the default action.
Your new action will now be available on the menu when you right-click.
If it is the default action, it will trigger when you double-click on a
.py file.
You can also accomplish this same thing by making a shortcut to your
Python executable and then adding command-line parameters to the shortcut.
Poor Yorick
gp@pooryorick.com
From op73418@mail.telepac.pt Sat Jan 4 11:36:16 2003
From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Sat Jan 4 11:36:16 2003
Subject: [Tutor] Applications/examples of some advanced Py features, please !
References: <20030103214439.9023.qmail@web9801.mail.yahoo.com>
Message-ID: <001d01c2b410$49d816d0$88190dd5@violante>
This is a multi-part message in MIME format.
------=_NextPart_000_001A_01C2B410.49B68510
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
I will just comment on the functional stuff and reserve my comment on =
the interfaces stuff to another post.
I haven't got any specific use cases for you. But one advice that I got =
and that helped me a lot was just to browse the code in the Python =
standard library. The code there is high quality and you are bound to =
find several use cases for lambda, although much less for nested scopes =
since they are a relatively recent addition to the language.=20
If you want to learn more on functional programming, David Mertz has 3 =
articles about it in the IBM developer works site. Just google for them.
With my best regards
G. Rodrigues
----- Original Message -----=20
From: Aztech Guy=20
To: tutor@python.org=20
Sent: Friday, January 03, 2003 9:44 PM
Subject: [Tutor] Applications/examples of some advanced Py features, =
please !
Hi Python gurus,
Can anyone please give some examples / applications of the use of the =
following advanced (advanced to me, at least :-) features of Python :
1. lambda
2. nested functions - a little info was given by Danny in reply to my =
earlier post on local-static variables, but I would like more.
3. Thoughts on implementing Interfaces in Py - a la Java interfaces.
I am, and will be doing more, on reading the docs and googling for =
this, but would anyway appreciate inputs from those who know this stuff.
I have a specific reason for the above questions- apart from general =
interest, of course -> I am planning to write a game-playing program in =
Py which will have features somewhat AI - ish. I don't have any =
background in AI; nor much in functional programming. I do understand =
recursion though. I suspect that some of the above 3 points will help me =
to write my app in a better way. though not sure, of course. Hence the =
request for examples.
For all of the above 3 points, I'm interested in :
- code examples of their use
- in what way their use makes code simpler, or maybe makes code =
possible that could not be written otherwise ('possible' in practical =
terms - I'm - vaguely - aware of the fact that all languages are =
supposed to be theoretically 'Turing-equivalent' or some such term - but =
what I mean is that if something is going to take a huge amount more =
code in some other language, or jumping through hoops, then I don't call =
it practically equivalent).
Thanks !
Az
------=_NextPart_000_001A_01C2B410.49B68510
Content-Type: text/html;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
I will just comment on the functional stuff and reserve my comment =
on the=20
interfaces stuff to another post.
I haven't got any specific use =
cases=20
for you. But one advice that I got and that helped me a lot was just to =
browse=20
the code in the Python standard library. The code there is high quality =
and you=20
are bound to find several use cases for lambda, although much less for =
nested=20
scopes since they are a relatively recent addition to the language. =
If you want to learn more on functional programming, David =
Mertz has 3=20
articles about it in the IBM developer works site. Just google for=20
them.
With my best regards
G. Rodrigues
----- Original Message -----
Sent: Friday, January 03, 2003 =
9:44=20
PM
Subject: [Tutor] =
Applications/examples of=20
some advanced Py features, please !
Hi Python gurus,
Can anyone please give some examples / applications of the use =
of the=20
following advanced (advanced to me, at least :-) features of Python =
:
1. lambda
2. nested functions - a little info was given by Danny in =
reply to my=20
earlier post on local-static variables, but I would like =
more.
3. Thoughts on implementing Interfaces in Py - a la Java=20
interfaces.
I am, and will be doing more, on reading the docs and googling for =
this,=20
but would anyway appreciate inputs from those who know this stuff.
I have a specific reason for the above questions- apart from =
general=20
interest, of course -> I am planning to write a game-playing =
program in Py=20
which will have features somewhat AI - ish. I don't have any =
background in AI;=20
nor much in functional programming. I do understand recursion though. =
I=20
suspect that some of the above 3 points will help me to write my app =
in a=20
better way. though not sure, of course. Hence the request for =
examples.
For all of the above 3 points, I'm interested in :
- code examples of their use
- in what way their use makes code simpler, or maybe makes =
code=20
possible that could not be written otherwise ('possible' in practical =
terms -=20
I'm - vaguely - aware of the fact that all languages are supposed to =
be=20
theoretically 'Turing-equivalent' or some such term - but what I mean =
is that=20
if something is going to take a huge amount more code in some other =
language,=20
or jumping through hoops, then I don't call it practically=20
equivalent).
Thanks !
Az
------=_NextPart_000_001A_01C2B410.49B68510--
From Janssen@rz.uni-frankfurt.de Sat Jan 4 12:48:02 2003
From: Janssen@rz.uni-frankfurt.de (Michael Janssen)
Date: Sat Jan 4 12:48:02 2003
Subject: [Tutor] pausing and layout
In-Reply-To:
Message-ID:
On Sat, 4 Jan 2003, mike O wrote:
> I guess I have three questions, the first being: Is there a python comman=
d
> to pause until the user does something?
Hello Mike
In addition to Gon=E7alo's reply I want to say that raw_input() is typicall=
y
used in a while loop:
from types import IntType
...
while 1:
p =3D raw_input("Choose a Number or [Q]uit: ")
if p =3D=3D "Q" or p =3D=3D "q" or p =3D=3D "":
# User requests the end of the game
sys.exit()
=09elif type(p) =3D=3D IntType:
# we have checked if p is sufficient and exit while loop
break
else:
# we've got some input, but it was the wrong: continue
# with the while loop and ask the user again
print "\tError: please choose a number."
#NOW do something with "p"
In a GUI application there is a overall loop "mainloop" which waits for
any kind of user interaction (you needn't explicit programm this mainloop:
in GUI programming it comes with the package)
Michael
>
> Also, how do you get python (when you don't run it in DOS Prompt) to not
> auto-exit? I have made a few simple programs, but as soon as it shows the
> answer, it exits.
>
> last, I was wondering how you do visual stuff, or make a program run in a
> window, instead of in the command prompt screen?
>
> Thanks,
> Mike
>
> _________________________________________________________________
> STOP MORE SPAM with the new MSN 8 and get 2 months FREE*
> http://join.msn.com/?page=3Dfeatures/junkmail
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From skitzomonkey@hotmail.com Sat Jan 4 12:54:02 2003
From: skitzomonkey@hotmail.com (mike O)
Date: Sat Jan 4 12:54:02 2003
Subject: [Tutor] pausing and layout
Message-ID:
>From: Michael Janssen
>To: mike O
>CC:
>Subject: Re: [Tutor] pausing and layout
>Date: Sat, 4 Jan 2003 18:47:12 +0100 (CET)
>
>On Sat, 4 Jan 2003, mike O wrote:
>
> > I guess I have three questions, the first being: Is there a python
>command
> > to pause until the user does something?
>Hello Mike
>
>In addition to Gonçalo's reply I want to say that raw_input() is typically
>used in a while loop:
>
>from types import IntType
> ...
>
> while 1:
> p = raw_input("Choose a Number or [Q]uit: ")
> if p == "Q" or p == "q" or p == "":
> # User requests the end of the game
> sys.exit()
> elif type(p) == IntType:
> # we have checked if p is sufficient and exit while loop
> break
> else:
> # we've got some input, but it was the wrong: continue
> # with the while loop and ask the user again
> print "\tError: please choose a number."
> #NOW do something with "p"
>
If you just wanted a number, couldn't you use input instead of raw_input?
I'm not entirely sure on these two functions, other than that I thought
input was for an integer, and raw_input was for a string, is that right?
>In a GUI application there is a overall loop "mainloop" which waits for
>any kind of user interaction (you needn't explicit programm this mainloop:
>in GUI programming it comes with the package)
>
>Michael
>
> >
> > Also, how do you get python (when you don't run it in DOS Prompt) to not
> > auto-exit? I have made a few simple programs, but as soon as it shows
>the
> > answer, it exits.
> >
> > last, I was wondering how you do visual stuff, or make a program run in
>a
> > window, instead of in the command prompt screen?
> >
> > Thanks,
> > Mike
> >
> > _________________________________________________________________
> > STOP MORE SPAM with the new MSN 8 and get 2 months FREE*
> > http://join.msn.com/?page=features/junkmail
> >
> >
> > _______________________________________________
> > Tutor maillist - Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
>
>_______________________________________________
>Tutor maillist - Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
_________________________________________________________________
MSN 8 with e-mail virus protection service: 2 months FREE*
http://join.msn.com/?page=features/virus
From op73418@mail.telepac.pt Sat Jan 4 13:10:02 2003
From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Sat Jan 4 13:10:02 2003
Subject: [Tutor] pausing and layout
References:
Message-ID: <000501c2b41d$55d32f30$88190dd5@violante>
----- Original Message -----
From: "mike O"
To:
Cc:
Sent: Saturday, January 04, 2003 5:53 PM
Subject: Re: [Tutor] pausing and layout
>
>
>
>
>
>
>
> >From: Michael Janssen
> >To: mike O
> >CC:
> >Subject: Re: [Tutor] pausing and layout
> >Date: Sat, 4 Jan 2003 18:47:12 +0100 (CET)
> >
> >On Sat, 4 Jan 2003, mike O wrote:
> >
> > > I guess I have three questions, the first being: Is there a python
> >command
> > > to pause until the user does something?
> >Hello Mike
> >
> >In addition to Gonçalo's reply I want to say that raw_input() is
typically
> >used in a while loop:
> >
> >from types import IntType
> > ...
> >
> > while 1:
> > p = raw_input("Choose a Number or [Q]uit: ")
> > if p == "Q" or p == "q" or p == "":
> > # User requests the end of the game
> > sys.exit()
> > elif type(p) == IntType:
> > # we have checked if p is sufficient and exit while loop
> > break
> > else:
> > # we've got some input, but it was the wrong: continue
> > # with the while loop and ask the user again
> > print "\tError: please choose a number."
> > #NOW do something with "p"
> >
> If you just wanted a number, couldn't you use input instead of raw_input?
> I'm not entirely sure on these two functions, other than that I thought
> input was for an integer, and raw_input was for a string, is that right?
>
No. input is just a call to raw_input *and then* an evaluation of the
returned string via the eval function, that is, input is the same as
eval(raw_input("A number, please:"))
Since it does no checking whatsoever this is an absolute no-no in terms of
security - the user can do *everything* that Python is capable (yes,
including formatting the hard disk). If you really want/expect an integer
just follow the usual Python idiom: try to convert it, handling any ensuing
exceptions, e.g. something like
while 1:
s = raw_input("A number, please:")
try:
number = int(s)
break
except ValueError:
print "Hey buster, I *want* a number"
If you don't know while loop's or exception-handling I suggest you start at
the newbie tutorials (go to the newbies section in www.python.org) and post
any questions you might have here.
All the best,
G. Rodrigues
From tony@tcapp.com Sat Jan 4 13:31:19 2003
From: tony@tcapp.com (Tony Cappellini)
Date: Sat Jan 4 13:31:19 2003
Subject: [Tutor] re:Tutor] pausing and layout
Message-ID: <5.1.0.14.0.20030104103803.023e37b8@smtp.sbcglobal.net>
Mike
I 've found this recently- which is the equivalent for getch(), which will
effectively pause until the user presses a key.
There are a version for windows & unix.
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892
From Janssen@rz.uni-frankfurt.de Sat Jan 4 13:33:01 2003
From: Janssen@rz.uni-frankfurt.de (Michael Janssen)
Date: Sat Jan 4 13:33:01 2003
Subject: [Tutor] pausing + raw_input vs input
In-Reply-To:
Message-ID:
On Sat, 4 Jan 2003, mike O wrote:
> If you just wanted a number, couldn't you use input instead of raw_input?
> I'm not entirely sure on these two functions, other than that I thought
> input was for an integer, and raw_input was for a string, is that right?
half right ;-)
raw_input(prompt) returns always strings. input(prompt) returns that type
of object the expert user created at the prompt. The main difference is
not string vs any-object but expert user vs nonexpert user!
compare doc/lib/built-in-funcs.html#l2h-30
input([prompt])
Equivalent to eval(raw_input(prompt)). Warning: This function
is not safe from user errors! It expects a valid Python
expression as input; if the input is not syntactically valid, a
SyntaxError will be raised. Other exceptions may be raised if
there is an error during evaluation. (On the other hand,
sometimes this is exactly what you need when writing a quick
script for expert use.)
You can take input() to get an integer, but the user need only to
type a letter and your programm is down. Better use raw_input() and "try"
to convert the users input with int():
while 1:
user_input = raw_input("No: ")
try:
number = int(user_input)
break # stop while-loop
except ValueError:
print "that was no number: " + user_input
# implicite remain in while loop
try-except is explained in the tutorial: doc/tut/node10.html. You will
need to learn this anyway (in case not already done :-)
Michael
Example for input (at interactive interpreter):
>>> j = input("hey, experts, give me an object! ")
hey, experts, give me an object! [2, 3, 4, 5]
>>> type(j)
>>> j
[2, 3, 4, 5]
From aztech1200@yahoo.com Sat Jan 4 14:32:02 2003
From: aztech1200@yahoo.com (Aztech Guy)
Date: Sat Jan 4 14:32:02 2003
Subject: [Tutor] Applications/examples of some advanced Py features, please !
In-Reply-To: <001d01c2b410$49d816d0$88190dd5@violante>
Message-ID: <20030104193101.8744.qmail@web9806.mail.yahoo.com>
--0-1915008729-1041708661=:8337
Content-Type: text/plain; charset=us-ascii
Thanks,
Goncalo, Gregor, Bob, Danny.
I'll try out the ideas suggested and revert with my results.
Looking forward to more replies on some of the other topics not mentioned, if anyone has any ideas about them..
Goncalo - a question - does the standard Python binary distribution (I have ActivePython 2.2.1 on Windows 98 and the Python 2.2 that comes with Red Hat 7.3 on Linux) - have all/most of the source for the std. lib. or do I have to download something else separately ? I do see a lot of .py files under the Lib directory, but since I'm new to Python, I don't know if they include all of the std. lib. - or if there is a formal concept of "std. lib." as there is in C, for instance. Anyway, I do have a lot of .py files there, and I'll read thru them for lambda examples. Thanks for the tip.
Az.
Gonçalo_Rodrigues wrote:I will just comment on the functional stuff and reserve my comment on the interfaces stuff to another post.
I haven't got any specific use cases for you. But one advice that I got and that helped me a lot was just to browse the code in the Python standard library. The code there is high quality and you
---------------------------------
Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now
--0-1915008729-1041708661=:8337
Content-Type: text/html; charset=us-ascii
Thanks,
Goncalo, Gregor, Bob, Danny.
I'll try out the ideas suggested and revert with my results.
Looking forward to more replies on some of the other topics not mentioned, if anyone has any ideas about them..
Goncalo - a question - does the standard Python binary distribution (I have ActivePython 2.2.1 on Windows 98 and the Python 2.2 that comes with Red Hat 7.3 on Linux) - have all/most of the source for the std. lib. or do I have to download something else separately ? I do see a lot of .py files under the Lib directory, but since I'm new to Python, I don't know if they include all of the std. lib. - or if there is a formal concept of "std. lib." as there is in C, for instance. Anyway, I do have a lot of .py files there, and I'll read thru them for lambda examples. Thanks for the tip.
Az.
Gonçalo_Rodrigues <op73418@mail.telepac.pt> wrote:
I will just comment on the functional stuff and reserve my comment on the interfaces stuff to another post.
I haven't got any specific use cases for you. But one advice that I got and that helped me a lot was just to browse the code in the Python standard library. The code there is high quality and you
Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now
--0-1915008729-1041708661=:8337--
From dmandini@inet.hr Sat Jan 4 15:40:01 2003
From: dmandini@inet.hr (djuro)
Date: Sat Jan 4 15:40:01 2003
Subject: [Tutor] joker signs?
Message-ID: <001c01c2b47c$a2a71b00$8342cad5@hal>
Hello!
for instance:
x = ['ben','sandy','roger','hillary','john','betty']
a = x.index('ben')
print a
---------
0
How to get indexes of all names which begin with "b" (like x.index('b*')
or, find all names that contain "er". Is it possible to do using some joker
letters like in os prompt?
Thank you
Djuro
From op73418@mail.telepac.pt Sat Jan 4 16:04:02 2003
From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Sat Jan 4 16:04:02 2003
Subject: [Tutor] Applications/examples of some advanced Py features, please !
References: <20030104193101.8744.qmail@web9806.mail.yahoo.com>
Message-ID: <001701c2b435$9cc90000$88190dd5@violante>
This is a multi-part message in MIME format.
------=_NextPart_000_0014_01C2B435.9C441890
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
I use ActiveState Python distro for Windows, so what I mean by the =
standard library are the py files in the Lib directory. They are present =
in other distros for other platforms as far as I can tell.
Also, since there probably is a lot of stuff there that does not =
interest you, you could also search the vaults of parnassus for stuff =
more akin to your interests. It is the closest thing there is to CPAN in =
the Python world.
With my best regards,
G. Rodrigues
P.S: I hate to be a nitpicker, but could you ditch HTML format in favour =
of plain text? It makes harder for me (and others) to reply in a proper =
way.
----- Original Message -----=20
From: Aztech Guy=20
To: [Python Tutor]=20
Sent: Saturday, January 04, 2003 7:31 PM
Subject: Re: [Tutor] Applications/examples of some advanced Py =
features, please !
Thanks,=20
Goncalo, Gregor, Bob, Danny.=20
I'll try out the ideas suggested and revert with my results.=20
Looking forward to more replies on some of the other topics not =
mentioned, if anyone has any ideas about them..=20
Goncalo - a question - does the standard Python binary distribution (I =
have ActivePython 2.2.1 on Windows 98 and the Python 2.2 that comes with =
Red Hat 7.3 on Linux) - have all/most of the source for the std. lib. or =
do I have to download something else separately ? I do see a lot of .py =
files under the Lib directory, but since I'm new to Python, I don't know =
if they include all of the std. lib. - or if there is a formal concept =
of "std. lib." as there is in C, for instance. Anyway, I do have a lot =
of .py files there, and I'll read thru them for lambda examples. Thanks =
for the tip.=20
=20
Az.=20
------=_NextPart_000_0014_01C2B435.9C441890
Content-Type: text/html;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
I use ActiveState Python distro for =
Windows, so=20
what I mean by the standard library are the py files in the Lib =
directory. They=20
are present in other distros for other platforms as far as I can=20
tell.
Also, since there probably is a lot of =
stuff there=20
that does not interest you, you could also search the vaults of =
parnassus for=20
stuff more akin to your interests. It is the closest thing there is to =
CPAN in=20
the Python world.
With my best regards,
G. Rodrigues
P.S: I hate to be a nitpicker, but =
could you ditch=20
HTML format in favour of plain text? It makes harder for me =
(and=20
others) to reply in a proper way.
----- Original Message -----
Sent: Saturday, January 04, =
2003 7:31=20
PM
Subject: Re: [Tutor]=20
Applications/examples of some advanced Py features, please !
Thanks,=20
Goncalo, Gregor, Bob, Danny.=20
I'll try out the ideas suggested and revert with my results.=20
Looking forward to more replies on some of the other topics not =
mentioned,=20
if anyone has any ideas about them..=20
Goncalo - a question - does the standard Python binary distribution =
(I have=20
ActivePython 2.2.1 on Windows 98 and the Python 2.2 that comes with =
Red Hat=20
7.3 on Linux) - have all/most of the source for the std. lib. or do I =
have to=20
download something else separately ? I do see a lot of .py files under =
the Lib=20
directory, but since I'm new to Python, I don't know if they include =
all of=20
the std. lib. - or if there is a formal concept of "std. lib." as =
there is in=20
C, for instance. Anyway, I do have a lot of .py files =
there, and=20
I'll read thru them for lambda examples. Thanks for the tip.=20
=20
Az.
------=_NextPart_000_0014_01C2B435.9C441890--
From op73418@mail.telepac.pt Sat Jan 4 16:06:02 2003
From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Sat Jan 4 16:06:02 2003
Subject: [Tutor] My appologies
References: <20030104193101.8744.qmail@web9806.mail.yahoo.com>
Message-ID: <002001c2b435$f9669070$88190dd5@violante>
My appologies,
I request for email in text format and send out in HTML format!
Sorry, once again,
G. Rodrigues
From Janssen@rz.uni-frankfurt.de Sat Jan 4 17:38:01 2003
From: Janssen@rz.uni-frankfurt.de (Michael Janssen)
Date: Sat Jan 4 17:38:01 2003
Subject: [Tutor] joker signs?
In-Reply-To: <001c01c2b47c$a2a71b00$8342cad5@hal>
Message-ID:
On Sat, 4 Jan 2003, djuro wrote:
> Hello!
>
> for instance:
>
> x = ['ben','sandy','roger','hillary','john','betty']
> a = x.index('ben')
> print a
> ---------
> 0
>
> How to get indexes of all names which begin with "b" (like x.index('b*')
> or, find all names that contain "er". Is it possible to do using some joker
> letters like in os prompt?
Hello Djuro,
you're looking for the fnmatch modul. In Python 2.2 you can do:
>>> fnmatch.filter(['ben','sandy','roger','hillary','john','betty'], "b*")
['ben', 'betty']
Michael
>
> Thank you
>
> Djuro
>
>
>
>
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From missive@hotmail.com Sat Jan 4 21:16:03 2003
From: missive@hotmail.com (Lee Harr)
Date: Sat Jan 4 21:16:03 2003
Subject: [Tutor] Re: joker signs?
Message-ID:
>x = ['ben','sandy','roger','hillary','john','betty']
>a = x.index('ben')
>print a
>---------
>0
>How to get indexes of all names which begin with "b" (like
> >x.index('b*')
>or, find all names that contain "er". Is it possible to do using some
> >joker
>letters like in os prompt?
How about a list comprehension?
x = ['ben','sandy','roger','hillary','john','betty']
[name for name in x if name.find('b') == 0]
[name for name in x if name.find('er') >= 0]
_________________________________________________________________
Protect your PC - get McAfee.com VirusScan Online
http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963
From dyoo@hkn.eecs.berkeley.edu Sat Jan 4 22:08:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat Jan 4 22:08:01 2003
Subject: [Tutor] startswith()/endswith() string methods
In-Reply-To:
Message-ID:
On Sun, 5 Jan 2003, Lee Harr wrote:
> >x = ['ben','sandy','roger','hillary','john','betty']
>
> >How to get indexes of all names which begin with "b"
>
> How about a list comprehension?
>
> x = ['ben','sandy','roger','hillary','john','betty']
> [name for name in x if name.find('b') == 0]
> [name for name in x if name.find('er') >= 0]
Hi Lee,
By the way, strings support a 'startswith()' method, so we can replace an
expression like:
name.find('b') == 0
with
name.startswith('b')
They're equivalent, but using startswith() makes the intention of the code
slightly clearer to a human reader.
###
>>> names = ['ben','sandy','roger','hillary','john','betty']
>>> [i for i in range(len(names)) if names[i].startswith('b')]
[0, 5]
###
If we're curious, we can browse through a complete list of string methods
in the Library Documentation here:
http://www.python.org/doc/lib/string-methods.html
Hope this helps!
From dyoo@hkn.eecs.berkeley.edu Sat Jan 4 22:23:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat Jan 4 22:23:01 2003
Subject: [Tutor] unicode utf-16 and readlines [using the 'codecs' unicode
file reading module]
In-Reply-To: <3E16EE3E.6020603@pooryorick.com>
Message-ID:
On Sat, 4 Jan 2003, Poor Yorick wrote:
> On Windows 2000, Python 2.2.1 open.readlines seems to read lines
> incorrectly when the file is encoded utf-16. For example:
>
> >>> fh = open('0022data2.txt')
> >>> a = fh.readlines()
> >>> print a
> ['\xff\xfe\xfaQ\r\x00\n', '\x00']
Hi Poor Yorick,
You may want to use a "codec" to decode Unicode from a file. The 'codecs'
module is specifically designed for this:
http://www.python.org/doc/lib/module-codecs.html
For example:
###
>>> import codecs
>>> f = codecs.open('foo.txt', 'w', 'utf-16')
>>> f.write("hello world")
>>> f.close()
>>> open('foo.txt').read()
'\xff\xfeh\x00e\x00l\x00l\x00o\x00 \x00w\x00o\x00r\x00l\x00d\x00'
>>> f2 = codecs.open('foo.txt', 'r', 'utf-16')
>>> f2.readlines()
[u'hello world']
###
> In this example, Python seems to have incorrectly parsed the \n\r
> characters at the end of the line.
If you use 'codecs' and its open() function, you should be all set. I saw
a brief mention on it in a Unicode tutorial here:
http://www.reportlab.com/i18n/python_unicode_tutorial.html
I always wanted to know what 'codecs' did. Now I know. Cool. *grin*
Thanks for the question!
From dyoo@hkn.eecs.berkeley.edu Sat Jan 4 22:27:03 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sat Jan 4 22:27:03 2003
Subject: [Tutor] re:Tutor] pausing and layout (getch() equivalent)
In-Reply-To: <5.1.0.14.0.20030104103803.023e37b8@smtp.sbcglobal.net>
Message-ID:
On Sat, 4 Jan 2003, Tony Cappellini wrote:
> I 've found this recently- which is the equivalent for getch(), which will
> effectively pause until the user presses a key.
> There are a version for windows & unix.
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892
Hi Tony,
But it's buggy on Windows platforms; Poor Yorick caught me on a bad day.
*grin*
http://mail.python.org/pipermail/tutor/2002-December/019508.html
Can anyone confirm that the fix at:
http://mail.python.org/pipermail/tutor/2002-December/019516.html
is doing the right thing?
From syrinx@simplecom.net Sun Jan 5 00:52:01 2003
From: syrinx@simplecom.net (Scott)
Date: Sun Jan 5 00:52:01 2003
Subject: [Tutor] open extra xterm?
Message-ID: <20030104234319.58985892.syrinx@simplecom.net>
I'm working on a python program that will defintely need a GUI. I'll
probably do it in Tkinter. But I want to get the guts of my program
working before I start learning Tkinter.
So I need at least two windows. How do I open a second xterm for
output, while I use my main one as a readline terminal? I'm assuming
pipes or something like that, but could someone show me a small example
of spawning an xterm and writing to it. Thank you.
From Don Arnold"
Message-ID: <01b801c2b480$1e8436b0$6410ba3f@defaultcomp>
---- Original Message -----
From: "Michael Janssen"
To: "mike O"
Cc:
Sent: Saturday, January 04, 2003 11:47 AM
Subject: Re: [Tutor] pausing and layout
On Sat, 4 Jan 2003, mike O wrote:
>> I guess I have three questions, the first being: Is there a python
command
>> to pause until the user does something?
>Hello Mike
>In addition to Gonçalo's reply I want to say that raw_input() is typically
>used in a while loop:
>from types import IntType
...
> while 1:
> p = raw_input("Choose a Number or [Q]uit: ")
> if p == "Q" or p == "q" or p == "":
> # User requests the end of the game
> sys.exit()
I've come to the conclusion that I like the seemingly SQL'ish alternative to
the 'if' statement above:
if p in ('Q','q',''):
sys.exit()
It scans easily (to my eyes), and gives me fewer chances to typo.
Don
From Adam Vardy Sun Jan 5 01:47:03 2003
From: Adam Vardy (Adam Vardy)
Date: Sun Jan 5 01:47:03 2003
Subject: [Tutor] getting input from keyboard
In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097022D1@i2km11-ukbr.domain1.systemhost.net>
References: <7497DCA1C240C042B28F6657ADFD8E097022D1@i2km11-ukbr.domain1.systemhost.net>
Message-ID: <15264841136.20030103062453@roadrunner.nf.net>
Hi Allan,
Thursday, December 26, 2002, 8:38:50 AM, you wrote:
>> How do I get keyboard input in python ?
>> I want to do the equivalent of this C code, in python
>> x=getch()
>> Assuming you are on Windows you need to import mscvrt
>> and use the getch() function in there.
>> If you are on Unix you use the curses(or ncurses) module
>> which also has a getch() function.
>> With the books that I have, there are no references in the
>> index to get, keyboard input, or in the Python help file.
>> My online web tutor (and book!)has a topic on event driven
>> programming which includes an example of using msvcrt.getch()
I could not actually find it there. Can you check if that's where it
should be?
--
Adam Vardy
From beercanz@hotmail.com Sun Jan 5 03:15:01 2003
From: beercanz@hotmail.com (Guess Who? Me)
Date: Sun Jan 5 03:15:01 2003
Subject: [Tutor] Help understanding part of the tutorial
Message-ID:
http://www.honors.montana.edu/~jjc/easytut/easytut/node9.html
contains this function:
def mult(a,b):
if b == 0:
return 0
rest = mult(a,b - 1)
value = a + rest
return value
print "3*2 = ",mult(3,2)
My question is that I don't get how mult(a,b-1) returns a value - can
somebody please explain? And it still works properly if you make a==0 - but
there is no "if a==0: return 0" statement. Any help would be appreciated.
_________________________________________________________________
The new MSN 8: smart spam protection and 2 months FREE*
http://join.msn.com/?page=features/junkmail
From dyoo@hkn.eecs.berkeley.edu Sun Jan 5 04:54:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Jan 5 04:54:02 2003
Subject: [Tutor] Help understanding part of the tutorial
In-Reply-To:
Message-ID:
On Sun, 5 Jan 2003, Guess Who? Me wrote:
> http://www.honors.montana.edu/~jjc/easytut/easytut/node9.html
> contains this function:
>
> def mult(a,b):
> if b == 0:
> return 0
> rest = mult(a,b - 1)
> value = a + rest
> return value
Hello!
Hmmm... let's try to see why this works first; looking at this closely
might make the defintion above more understandable.
The Python code above is defines multiplication in terms of addition,
using a funny definition:
a * b = a + (a * (b-1))
The math works out: the left side and the right side are truly equal to
each other.
But how does this work as a process? Let's pretend that we're trying to
multiply 5 and 3, using this weird definition. Ok, let's apply this
transformation once.
5 * 3 = 5 + (5 * 2)
But we don't stop here: we now expand that 5 * 2 using the same method:
5 * 3 = 5 + (5 * 2)
= 5 + (5 + (5 * 1))
= 5 + (5 + (5 + (5 * 0)))
= 5 + (5 + (5 + (5 + (5 * -1))))
= 5 + (5 + (5 + (5 + (5 + (5 * -2)))))
...
Notice that we can do this expansion forever --- we can keep doing that
a * b = a + (a * (b-1))
operation without end, and be perfectly correct as far as the math is
concerned, but not closer to understanding multiplication. In Python,
this out-of-control definition looks like:
###
>>> def mult_broken(a, b):
... return a + mult_broken(a, b-1)
...
>>> mult_broken(5, 3)
## lots and lots of error messages pop up at this
## point
File "", line 2, in mult_broken
File "", line 2, in mult_broken
RuntimeError: maximum recursion depth exceeded
###
The calculation gets so large that Python just stops, saying the program
appears to be flailing out of control. That might make us think that this
definition is completely useless.
And that would be true, except that we do know that we can cut things
short. As soon as we hit something like a * 0, we don't have to do any
more expansion:
5 * 3 = 5 + (5 + (5 + (5 * 0)))
= 5 + (5 + (5 + 0)))
= 15
That is, we stop expanding as soon as b is equal to zero, since we know
that anything times zero is zero.
And that's where the 'if' statement comes in: we first check to see if b
is equal to zero, and then go with the definition only if it doesn't:
###
>>> def mult(a, b):
... if b == 0:
... return 0
... return a + mult(a, b-1)
...
>>> mult(5, 3)
15
###
Checking against b==0 might seem an arbitrary choice. And it is! *grin*
We can just as easily make the cutoff when 'b' is equal to -1, since
a *(-1) is just -a:
5 * 3 = 5 + (5 * 2)
= 5 + (5 + (5 * 1))
= 5 + (5 + (5 + (5 * 0)))
= 5 + (5 + (5 + (5 + (5 * -1))))
= 5 + (5 + (5 + (5 + -5)))
= 15
In Python, this looks like:
###
>>> def mult3(a, b):
... if b == -1:
... return -a
... return a + mult3(a, b-1)
...
>>> mult3(5, 3)
15
###
The point is that we've got to make the cut somewhere. In technical
terms, we need to tell Python how to solve the "base case" in a way that
can be solved really easily. In multiplication, multiplying against zero
is an easy task, so we can choose that as our "base case".
> And it still works properly if you make a==0 - but there is no "if a==0:
> return 0" statement.
Very true, but it's still ok. mult(0, 25) ends up doing something like:
0 + (0 + (0 + ... + 0))))))))))))))))))))))))
which does a lot of work for nothing, but it's still perfectly correct as
far as the math's concerned.
I feel like I'm rushing things a bit though. If you have questions,
please feel free to bring them to the Tutor list.
Good luck to you!
From dyoo@hkn.eecs.berkeley.edu Sun Jan 5 05:25:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun Jan 5 05:25:02 2003
Subject: [Tutor] Applications/examples of some advanced Py features,
please ! [Python and AI?]
In-Reply-To: <001d01c2b410$49d816d0$88190dd5@violante>
Message-ID:
On Sat, 4 Jan 2003, [iso-8859-1] Gon=E7alo Rodrigues wrote:
> If you want to learn more on functional programming, David Mertz has 3
> articles about it in the IBM developer works site. Just google for them.
Here you go:
http://www-106.ibm.com/developerworks/linux/library/l-prog.html
http://www-106.ibm.com/developerworks/library/l-prog2.html
> I have a specific reason for the above questions- apart from general
> interest, of course -> I am planning to write a game-playing program in
> Py which will have features somewhat AI - ish. I don't have any
> background in AI; nor much in functional programming.
Hmmm! You might find this useful:
http://www.norvig.com/
Peter Norvig is one of the authors of the book "Artificial Intelligence, A
Modern Approach".
http://www.cs.berkeley.edu/~russell/aima.html
It's an awesome book --- a bit on the heavy side, but chock full of good
stuff. (Although I'm sorta biased about this, having taken the course
from the other co-author of the book... *grin*)
Norvig has example code in Python, including some game-playing code:
http://www.norvig.com/python/python.html
Hope this helps!
From Janssen@rz.uni-frankfurt.de Sun Jan 5 08:10:02 2003
From: Janssen@rz.uni-frankfurt.de (Michael Janssen)
Date: Sun Jan 5 08:10:02 2003
Subject: [Tutor] open extra xterm?
In-Reply-To: <20030104234319.58985892.syrinx@simplecom.net>
Message-ID:
On Sat, 4 Jan 2003, Scott wrote:
> I'm working on a python program that will defintely need a GUI. I'll
> probably do it in Tkinter. But I want to get the guts of my program
> working before I start learning Tkinter.
>
> So I need at least two windows. How do I open a second xterm for
> output, while I use my main one as a readline terminal? I'm assuming
> pipes or something like that, but could someone show me a small example
> of spawning an xterm and writing to it. Thank you.
Hello Scott,
I can only give you some hints:
writing to another terminal is easy:
>>> fo = open("/dev/pts/4","w")
>>> fo.write("hello")
>>> fo.flush()
this will print to terminal pts/4. Use ps to identify the current
terminals:
ps -a : gives you processes run by the terminal shells. You can use "sleep
10" on your second xterm to identify it.
ps -Nx : gives you every terminal related process (including the shells)
The problem is: you need to identify the pts and (more important) you need
to start the xterm from outside the script.
When you want to work around this, *probably* os.fork() os.forkpty() and
the pty module helps you. Or you get os.system() or os.popen2() to work
(they can start a xterm but this will run under the pts-device of the
python interpreter. The popen2 fileobjects doesn't work [for me]).
Would you drop me a line when you find a solution?
Michael
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From abli@freemail.hu Sun Jan 5 09:47:01 2003
From: abli@freemail.hu (Abel Daniel)
Date: Sun Jan 5 09:47:01 2003
Subject: [Tutor] open extra xterm?
In-Reply-To: <20030104234319.58985892.syrinx@simplecom.net>
References: <20030104234319.58985892.syrinx@simplecom.net>
Message-ID: <20030105144637.GA1330@hooloovoo>
On Sat, Jan 04, 2003 at 11:43:19PM -0600 Scott (syrinx@simplecom.net) wrote:
> So I need at least two windows. How do I open a second xterm for
> output, while I use my main one as a readline terminal? I'm assuming
> pipes or something like that, but could someone show me a small example
> of spawning an xterm and writing to it. Thank you.
Not fully in python, but should work:
1, open xterm, excecute:
mkfifo /tmp/pipe
cat /tmp/pipe
2, start python program, for example:
fo = open("/tmp/pipe","w")
while 1:
i=raw_input('>>')
fo.write(i + '\n')
fo.flush()
Abel Daniel
abli@freemail.hu
From abli@freemail.hu Sun Jan 5 10:11:20 2003
From: abli@freemail.hu (Abel Daniel)
Date: Sun Jan 5 10:11:20 2003
Subject: [Tutor] open extra xterm?
In-Reply-To: <20030105144637.GA1330@hooloovoo>
References: <20030104234319.58985892.syrinx@simplecom.net> <20030105144637.GA1330@hooloovoo>
Message-ID: <20030105151056.GB1330@hooloovoo>
On Sun, Jan 05, 2003 at 03:46:37PM +0100 Abel Daniel (abli@freemail.hu) wrote:
> Not fully in python, but should work:
[..snipped...]
Ok, here is the fully python version:
import os
os.system('mkfifo /tmp/pipe')
os.system("xterm -e cat /tmp/pipe &")
fo = open("/tmp/pipe","w")
while 1: #for simulating data output
i=raw_input('>>')
fo.write(i + '\n')
fo.flush()
Of course, using /tmp/pipe silently is not exactly a good idea,
a safer version would find make up an obfuscated name, check if
it's used in /tmp/ and make a pipe with that name, but i'm to tired
to add that.
Abel Daniel
abli@freemail.hu
From aztech1200@yahoo.com Sun Jan 5 11:03:01 2003
From: aztech1200@yahoo.com (Aztech Guy)
Date: Sun Jan 5 11:03:01 2003
Subject: [Tutor] Applications/examples of some advanced Py features, please !
In-Reply-To: <001701c2b435$9cc90000$88190dd5@violante>
Message-ID: <20030105160249.54435.qmail@web9802.mail.yahoo.com>
--- Gonçalo_Rodrigues wrote:
> the vaults of parnassus for stuff more akin to your
Thanks for the info.
> HTML format in favour of plain text? It makes harder
> I hate to be a nitpicker ...
Nothing nitpicking about it :-) Sorry about the HTML.
I use browser-based Yahoo Mail, and till now no one
had asked me to not send HTML, so I had left it at the
default. I've set this mail to plain text mode, please
let me know if it still comes as HTML for any reason,
and I'll look into it.
Az
__________________________________________________
Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now.
http://mailplus.yahoo.com
From aztech1200@yahoo.com Sun Jan 5 11:11:00 2003
From: aztech1200@yahoo.com (Aztech Guy)
Date: Sun Jan 5 11:11:00 2003
Subject: [Tutor] Applications/examples of some advanced Py features, please ! [Python and AI?]
In-Reply-To:
Message-ID: <20030105161016.54847.qmail@web9802.mail.yahoo.com>
--- Danny Yoo wrote:
>
> www.norvig.com
Thanks for all the tips !
I've checked out the book, it looks good, and I bought
it.
Az.
__________________________________________________
Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now.
http://mailplus.yahoo.com
From magnus@thinkware.se Sun Jan 5 15:44:03 2003
From: magnus@thinkware.se (Magnus Lycka)
Date: Sun Jan 5 15:44:03 2003
Subject: [Tutor] 2nd bonehead question...
In-Reply-To: <200212211619.29024.shalehperry@attbi.com>
References: <5.1.0.14.0.20021221235403.02bcd400@www.thinkware.se>
<5.1.0.14.0.20021221235403.02bcd400@www.thinkware.se>
Message-ID: <5.1.0.14.0.20030105213142.02c4a830@www.thinkware.se>
At 16:19 2002-12-21 -0800, Sean 'Shaleh' Perry wrote:
> > .pyc is a .py file compiled into byte-code, a binary
> > format that the python interpreter reads. These files
> > are created automatically when a python module is
> > imported, if there isn't already an updated .pyc file.
>
>taken a step further, the interpreter has some magic to use the .pyc first if
>it exists otherwise it makes one from the .py file. There is logic there to
>see if the pyc is older than the py and if so recreate it as well.
Yes, this is good to know, since it might bite you in
some cases:
- You open an archive (.zip, .tar etc) with .py-files. You
change a file x.py, and then run the program y.py, and x.pyc
is created as you do "import x" in y.py. You see that your
fix was bad, and you revert to the original x.py by extracting
it from the archive file again. You do this with a command that
preserves time settings for the file, and to your surprise, the
bug you just backed out of is still in your program, despite
the fact that it's gone from the source...
- You make a change in foo.py module, and a foo.pyc is created.
You then realize that you have previously changed the date in
your computer to January 5, 2004 by accident. (Stupid Windows...)
You correct this, and make further changes to foo.py, but they don't
seem to be reflected in your program next time you try it...
- You use clearcase with dynamic views for source control, and you
check out an earlier version of a .py-file.
In all these situations I think Python will be tricked into using an
invalid .pyc-file.
When in doubt...just delete your .pyc-files.
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se
From magnus@thinkware.se Sun Jan 5 18:09:01 2003
From: magnus@thinkware.se (Magnus Lycka)
Date: Sun Jan 5 18:09:01 2003
Subject: [Tutor] Debug
In-Reply-To: <5.2.0.9.0.20030102111509.02bd0da8@66.28.54.253>
References: <1615745792.20030102140009@roadrunner.nf.net>
Message-ID: <5.1.0.14.0.20030106001048.02bd4e90@www.thinkware.se>
At 11:25 2003-01-02 -0700, Bob Gailer wrote:
>Sounds like you're using PythonWin, which I use also. There are behaviors
>that are unexpected and sometimes unpredictible. def _doexec(cmd, globals,
>locals): is in PyhtonWin's debugger module; why it (sometimes) shows up in
>single step is a mystery.
May I suggest that you use Boa Constructor for debugging
instead? It has the nicest GUI debugger for Python that
I have used. As an editor, I still find PythonWin better.
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se
From charlie@begeistert.org Sun Jan 5 18:13:14 2003
From: charlie@begeistert.org (Charlie Clark)
Date: Sun Jan 5 18:13:14 2003
Subject: [Tutor] Assigning function keywords dynamically
In-Reply-To: <20030105170005.14991.93345.Mailman@mail.python.org>
References: <20030105170005.14991.93345.Mailman@mail.python.org>
Message-ID: <20030106001539.1829.4@.1041771530.fake>
Dear list,
I remember a discussion about switch/case statements in Python (I know they=
only exist in C) including my own contribution but haven't been able to
find quite what I was looking for my usual sources.
I have got a little report generator that generates reports for people with=
different frequency (daily, weekly, monthly). What I want is a function
that takes the frequency and returns the correct future date for the next
run.
current implementation using mx.DateTime
from mx.DateTime import now(), DateTime.RelativeDateTime
def new_date(interval):
=09if interval =3D=3D "monatlich":
=09=09return now() + RelativeDateTime(months=3D+1)
=09elif interval =3D=3D "w=F6chentlich":
=09=09return now() + RelativeDateTime(weeks=3D+1)
=09elif interval =3D=3D "t=E4glich":
=09=09return now() + RelativeDateTime(days=3D+1)
=09else:
=09=09return "Invalid interval"
While this is fine it seems a little verbose and clumsy and not quite
Python. What would be a better way of doing this? Also would it be a good
idea to raise an exception in the else statement?
Thanx very much
Charlie
From tim.one@comcast.net Sun Jan 5 18:36:21 2003
From: tim.one@comcast.net (Tim Peters)
Date: Sun Jan 5 18:36:21 2003
Subject: [Tutor] Assigning function keywords dynamically
In-Reply-To: <200301052313.h05NDMC07191@bright09>
Message-ID:
[Charlie Clark]
> ...
> I have got a little report generator that generates reports for
> people with different frequency (daily, weekly, monthly). What I wa=
nt
> is a function that takes the frequency and returns the correct fut=
ure
> date for the next run.
>
> current implementation using mx.DateTime
>
> from mx.DateTime import now(), DateTime.RelativeDateTime
>
> def new_date(interval):
> =09if interval =3D=3D "monatlich":
> =09=09return now() + RelativeDateTime(months=3D+1)
> =09elif interval =3D=3D "w=F6chentlich":
> =09=09return now() + RelativeDateTime(weeks=3D+1)
> =09elif interval =3D=3D "t=E4glich":
> =09=09return now() + RelativeDateTime(days=3D+1)
> =09else:
> =09=09return "Invalid interval"
>
> While this is fine it seems a little verbose and clumsy and not qui=
te
> Python. What would be a better way of doing this?
You're building a mapping from strings to durations, which screams "d=
ict".
Like so:
_name2dur =3D {"monatlich": RelativeDateTime(months=3D+1),
"w=F6chentlich": RelativeDateTime(weeks=3D+1).
"t=E4glich": RelativeDateTime(days=3D+1),
}
def new_date(interval):
dur =3D _name2dur.get(interval)
if dur is None:
raise ValueError("unknown interval '%s'" % interval)
return now() + dur
> Also would it be a good idea to raise an exception in the else
> statement?
Probably. The caller presumably expects to get some kind of date obj=
ect
back from this, not some kind of string, so when it does return a str=
ing it
will probably raise some kind of baffling exception later (like "can'=
t add
time to string"), or perhaps "Invalid interval" will get stored away
somewhere and printed 3 months later. It would be hard to guess what=
went
wrong then. As a general rule, it's thoroughly appropriate for a fun=
ction
to raise an exception when a caller asks it to do something silly, an=
d
you're doing the caller a favor by not letting it get away with that =
when it
does.
From missive@hotmail.com Sun Jan 5 18:59:02 2003
From: missive@hotmail.com (Lee Harr)
Date: Sun Jan 5 18:59:02 2003
Subject: [Tutor] Re: Help understanding part of the tutorial
Message-ID:
>def mult(a,b):
> if b == 0:
> return 0
> rest = mult(a,b - 1)
> value = a + rest
> return value
>
>print "3*2 = ",mult(3,2)
>
>My question is that I don't get how mult(a,b-1) returns a value
>
Sometimes when debugging, or just trying to understand a piece
of code, it helps to move through the code step by step thinking
(or writing down) what the computer will do at each step:
ok, I am going to call mult(3, 2)
a = 3, b = 2
is b == 0? nope, so
rest = mult(3, 1)
ok, I am going to call mult(3, 1)
a = 3, b = 1
is b == 0? nope, so
rest = mult(3, 0)
# note that rest here is different from the rest up above,
# rest is "local" to this function call and is completely
# independent of the rest in the mult(3, 2) call.
ok, I am going to call mult(3, 0)
a = 3, b = 0
is b == 0? YES, so
return 0
# but, return 0 to where? who called this?
# ah, yes, it was the call to mult(3, 1), so
# back in the call to mult(3, 1)
a = 3, b = 1, rest = 0
value = 3 + 0
return 3
# return to who?
# to the mult(3, 2) call, so
# back in the call to mult(3, 2)
a = 3, b = 2, rest = 3
value = 3 + 3
return 6
# to who?
# mult(3, 2) was the original call, so we're finished
This is called a "recursive" function definition.
(which means that the function calls itself in the process
of calculating a final answer, and sets some kind of a
condition for ending the stack of recursive calls)
I am pretty sure that any recursive function can be written
in a non-recursive way. For instance:
def mult(a,b):
total = 0
while a:
total += b
a -= 1
return total
or, of course
def mult(a, b):
return a * b
_________________________________________________________________
Help STOP SPAM: Try the new MSN 8 and get 2 months FREE*
http://join.msn.com/?page=features/junkmail
From magnus@thinkware.se Sun Jan 5 19:09:01 2003
From: magnus@thinkware.se (Magnus Lycka)
Date: Sun Jan 5 19:09:01 2003
Subject: [Tutor] Good reasons for 1.5.2 compatibility?
In-Reply-To:
References:
Message-ID: <5.1.0.14.0.20030106010749.02bda648@www.thinkware.se>
At 18:45 2003-01-03 +0300, Roman Suzi wrote:
>Also I know that 2.x has difficulties with non-latin1 texts in IDLE:
>so it is not possible to use Tkinter (thus build GUIs) with standard 2.x
>versions of Python.
I can't quite follow the conclusion you are making here.
Why exactly isn't it possible to use Tkinter with standard 2.x
versions of Python?
Surely Tkinter does not depend on IDLE.
Also, it might be time to consider using Unicode for implementing
non-ASCII things in Python...
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se
From glingl@aon.at Sun Jan 5 19:47:11 2003
From: glingl@aon.at (Gregor Lingl)
Date: Sun Jan 5 19:47:11 2003
Subject: [Tutor] Re: Help understanding part of the tutorial
References:
Message-ID: <3E18D212.10506@aon.at>
Lee Harr schrieb:
>> def mult(a,b):
>> if b == 0:
>> return 0
>> rest = mult(a,b - 1)
>> value = a + rest
>> return value
>>
>> print "3*2 = ",mult(3,2)
>>
>> My question is that I don't get how mult(a,b-1) returns a value
>>
>
>
> Sometimes when debugging, or just trying to understand a piece
> of code, it helps to move through the code step by step thinking
> (or writing down) what the computer will do at each step:
>
>
> ok, I am going to call mult(3, 2)
> a = 3, b = 2
> is b == 0? nope, so
> rest = mult(3, 1)
>
> ok, I am going to call mult(3, 1)
> a = 3, b = 1
> is b == 0? nope, so
> rest = mult(3, 0)
> # note that rest here is different from the rest up above,
> # rest is "local" to this function call and is completely
> # independent of the rest in the mult(3, 2) call.
>
> ok, I am going to call mult(3, 0)
> a = 3, b = 0
> is b == 0? YES, so
> return 0
> # but, return 0 to where? who called this?
> # ah, yes, it was the call to mult(3, 1), so
>
> # back in the call to mult(3, 1)
> a = 3, b = 1, rest = 0
> value = 3 + 0
> return 3
> # return to who?
> # to the mult(3, 2) call, so
>
> # back in the call to mult(3, 2)
> a = 3, b = 2, rest = 3
> value = 3 + 3
> return 6
> # to who?
> # mult(3, 2) was the original call, so we're finished
Additionally to this mental procedure it may be helpful
to *observe* what's going on, when executing mult by
using the IDLE-debugger (supposing IDLE works on
your system).
*) start IDLE
*) write mult in a *.py file and execute it.
*) In the IDLE-menu of the interactive window click Debug|Debugger
The debugger window appears. Activate "source" by clicking
the appropriate box.
In the interactive window type mult(3,2). Then proceed by
repeatedly clicking the "Step" - button in the Debug-Control-Window,
This way you'll be able to observe:
*) in dthe debugger-window: the sequence of active function
calls, which in the case of recursive functions contain several
active copies of the same function, each of them having their own...
*) ... local variables, their values and how these are changing.
*) and finally in the editor-window you'll find the code-line marked,
which is going to be executed.
At first this may be a little confusing, but since you easily can
repeat this several times you'll get accustomed to it and it may
well help you to verify your by-hand-execution of the code
as well as to grasp the secrets of recursion.
Try it out!
Best wishes
Gregor
>
>
> This is called a "recursive" function definition.
> (which means that the function calls itself in the process
> of calculating a final answer, and sets some kind of a
> condition for ending the stack of recursive calls)
>
> I am pretty sure that any recursive function can be written
> in a non-recursive way. For instance:
>
> def mult(a,b):
> total = 0
> while a:
> total += b
> a -= 1
> return total
>
> or, of course
>
> def mult(a, b):
> return a * b
>
>
> _________________________________________________________________
> Help STOP SPAM: Try the new MSN 8 and get 2 months FREE*
> http://join.msn.com/?page=features/junkmail
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
From shalehperry@attbi.com Sun Jan 5 21:43:01 2003
From: shalehperry@attbi.com (Sean 'Shaleh' Perry)
Date: Sun Jan 5 21:43:01 2003
Subject: [Tutor] Good reasons for 1.5.2 compatibility?
In-Reply-To:
References:
Message-ID: <200301051842.13981.shalehperry@attbi.com>
On Friday 03 January 2003 08:26, Michael Janssen wrote:
> On Fri, 3 Jan 2003, John Abbe wrote:
> > Are there any factors causing reasonable people
> > to keep 1.5.2 around?
>
> Some people do keep 1.5.2 on their system, but it's hard to tell what's
> their reason (that's a "frequently not answered question" on
> comp.lang.python). Perhaps it's just they are lazy. RedHat remained for=
a
> long time on 1.5.2 cause they frighten incompatibilities with their
> system-scripts written in python, but they have skipped this position a=
nd
> switched to a recent version.
>
However there are still a lot of 1.5.2 RH systems out there.
As an earlier poster commented, unless you need a feature from 2.x being =
1.5.x=20
compliant is not that hard. The two biggies are the import string -->=20
string.foo change and list comprehensions.
From andy_osagie@hotmail.com Sun Jan 5 21:51:19 2003
From: andy_osagie@hotmail.com (Andy Osagie)
Date: Sun Jan 5 21:51:19 2003
Subject: [Tutor] Taking a screenshot
Message-ID: <000101c2b52e$48d81900$853c86ac@aeo120>
This is a multi-part message in MIME format.
------=_NextPart_000_0002_01C2B504.60021100
Content-Type: text/plain;
charset="us-ascii"
Content-Transfer-Encoding: 7bit
Hello,
Is it possible to use Python to take a screenshot of the script-user's
screen and then save it in some popular image format? I did some
searching for an answer but couldn't find any module that would help me
do it or any instructions on how to. Are there any suggestions? Thanks
in advance.
-- Andy
------=_NextPart_000_0002_01C2B504.60021100
Content-Type: text/html;
charset="us-ascii"
Content-Transfer-Encoding: quoted-printable
Hello,
Is it possible to use Python to take a screenshot of =
the
script-user’s screen and then save it in some popular image =
format? I did
some searching for an answer but couldn’t find any module that =
would help
me do it or any instructions on how to. Are there any suggestions? =
Thanks in
advance.
-- Andy
------=_NextPart_000_0002_01C2B504.60021100--
From tony@tcapp.com Mon Jan 6 02:31:06 2003
From: tony@tcapp.com (Tony Cappellini)
Date: Mon Jan 6 02:31:06 2003
Subject: [Tutor] Python docs- makes the learning harder sometimes
Message-ID: <5.1.0.14.0.20030105232139.01a768c0@smtp.sbcglobal.net>
I've got a book which refers to some really useful string functions like.
startswith()
endswith()
as in
s="Hello Python"
s.startswith("He")
s.endswith("on",6)
where each function has 2 parameters,
however, I don't understand why these functions are not in the Global
Module Index
Arggggghh !
From janos.juhasz@VELUX.com Mon Jan 6 11:47:43 2003
From: janos.juhasz@VELUX.com (janos.juhasz@VELUX.com)
Date: Mon Jan 6 11:47:43 2003
Subject: [Tutor] pyLpd
Message-ID:
Dear all,
This would be the very base of my test lpd, but i don't know how can i =
send
back an 'octete of zero bits' for acknowledgement
with self.wfile.write()
******
import SocketServer
class pyLpd(SocketServer.StreamRequestHandler):
def handle(self):
lines =3D self.rfile.readlines()
self.wfile.write()
print lines
if __name__ =3D=3D '__main__':
server =3D SocketServer.TCPServer( ('', 515), pyLpd)
server.serve_forever()
*****
Best regards,
-----------------------
Juh=E1sz J=E1nos
IT department
=
From janos.juhasz@VELUX.com Mon Jan 6 11:51:06 2003
From: janos.juhasz@VELUX.com (janos.juhasz@VELUX.com)
Date: Mon Jan 6 11:51:06 2003
Subject: [Tutor] pyLpd
Message-ID:
Dear all,
This would be the very base of my test lpd, but i don't know how i coul=
d
send back an 'octete of zero bits' for acknowledgement
with self.wfile.write()
******
import SocketServer
class pyLpd(SocketServer.StreamRequestHandler):
def handle(self):
lines =3D self.rfile.readlines()
self.wfile.write()
print lines
if __name__ =3D=3D '__main__':
server =3D SocketServer.TCPServer( ('', 515), pyLpd)
server.serve_forever()
*****
Best regards,
-----------------------
Juh=E1sz J=E1nos
IT department
=
From francois.granger@free.fr Mon Jan 6 11:51:27 2003
From: francois.granger@free.fr (Fran=?ISO-8859-1?B?5w==?=ois Granger)
Date: Mon Jan 6 11:51:27 2003
Subject: [Tutor] Python docs- makes the learning harder sometimes
In-Reply-To: <5.1.0.14.0.20030105232139.01a768c0@smtp.sbcglobal.net>
Message-ID:
on 6/01/03 8:24, Tony Cappellini at tony@tcapp.com wrote:
> startswith()
> endswith()
> however, I don't understand why these functions are not in the Global
> Module Index
They are string method and are referenced in the Python Library Reference.
http://www.python.org/doc/current/lib/string-methods.html
--
Le courrier est un moyen de communication. Les gens devraient
se poser des questions sur les implications politiques des choix (ou non
choix) de leurs outils et technologies. Pour des courriers propres :
--
From rob@uselesspython.com Mon Jan 6 11:55:11 2003
From: rob@uselesspython.com (Rob Andrews)
Date: Mon Jan 6 11:55:11 2003
Subject: [Tutor] Python docs- makes the learning harder sometimes
In-Reply-To: <5.1.0.14.0.20030105232139.01a768c0@smtp.sbcglobal.net>
Message-ID:
> -----Original Message-----
> I've got a book which refers to some really useful string functions like.
>
> startswith()
> endswith()
>
> however, I don't understand why these functions are not in the Global
> Module Index
There is a reason that startswith() and endswith() are not included in the
Global Module Index, and it's actually a pretty good one. They aren't part
of a module that needs to be imported, but built-in string methods included
in the Python Library Reference. This is a part of the documentation that
comes with Python and can be found on the python.org site in the Documents
area.
If, for example, you are running on a Windows PC (like the one I happen to
be sitting at presently), and you have Python installed at C:\Python22\, you
should be able to find these methods described in
"C:\Python22\Doc\lib\string-methods.html".
The Python Library Reference is good enough to merit reading thoroughly and
repeatedly, in my experience.
Hope this helps,
Rob
http://uselesspython.com
Got Zeus?
http://www.hellenion.org
From lumbricus@gmx.net Mon Jan 6 11:57:35 2003
From: lumbricus@gmx.net (lumbricus@gmx.net)
Date: Mon Jan 6 11:57:35 2003
Subject: [Tutor] Python docs- makes the learning harder sometimes
References: <5.1.0.14.0.20030105232139.01a768c0@smtp.sbcglobal.net>
Message-ID: <3446.1041852185@www40.gmx.net>
Hello!
> startswith()
> endswith()
[ snip ]
> where each function has 2 parameters,
> however, I don't understand why these functions are not in the Global
> Module Index
Why should they? They are string methods and not related to
a module:
"http://www.python.org/doc/current/lib/string-methods.html"
> Arggggghh !
:-) HTH, J"o!
--
sigfault
+++ GMX - Mail, Messaging & more http://www.gmx.net +++
NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen!
From magnus@thinkware.se Mon Jan 6 12:00:23 2003
From: magnus@thinkware.se (Magnus Lycka)
Date: Mon Jan 6 12:00:23 2003
Subject: [Tutor] Python docs- makes the learning harder sometimes
In-Reply-To: <5.1.0.14.0.20030105232139.01a768c0@smtp.sbcglobal.net>
Message-ID: <5.1.0.14.0.20030106124636.02bd8ec0@www.thinkware.se>
At 23:24 2003-01-05 -0800, Tony Cappellini wrote:
>I've got a book which refers to some really useful string functions like.
>
>startswith()
>endswith()
Those are methods of string objects. String is a builtin type.
>however, I don't understand why these functions are not in the Global
>Module Index
That's because they have no place in a list of module names. The
Global Module Index is only an alphabetical list of modules. I.e.
roughly the same thing as the section names in chapters 3 to 22 in
the Python Library Reference, but in a different order.
In other words, if a name X is listed in the Global Module Index,
you can type "import X" in your python program to load that module
if you have a standard Python installation. There's no sense in
doing "import startswith", right?
>Arggggghh !
Now now, calm down a bit! ;)
The Global Module Index is very useful for finding *modules* by
their names, but the most important parts of the Library Reference
is chapter 2: "Built-in Functions, Types, and Exceptions". What you
look for is here: http://www.python.org/doc/current/lib/string-methods.html
in 2.2.6.1. I suggest that you skim through chapter 2 now and then.
Don't bother memorizing everything, but as your experience in Python
progresses, you will find that new things will turn out to be useful,
and you will refresh your memory about the basics in Python.
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se
From magnus@thinkware.se Mon Jan 6 12:04:33 2003
From: magnus@thinkware.se (Magnus Lycka)
Date: Mon Jan 6 12:04:33 2003
Subject: [Tutor] Better (free) IDEs than IDLE for Linux ?
In-Reply-To: <20021224145203.37898.qmail@web9806.mail.yahoo.com>
References: <7497DCA1C240C042B28F6657ADFD8E0974DA78@i2km11-ukbr.domain1.systemhost.net>
Message-ID: <5.1.0.14.0.20030106130722.02c5eb58@www.thinkware.se>
At 06:52 2002-12-24 -0800, Aztech Guy wrote:
>[Az] Yes, I have that book. It's good. One nice example is about scroll
>bars - he argues that the up and down arrowheads on a scroll bar should be
>adjacent, not at opposite ends of the bar, to reduce mousing. Haven't seen
>that idea make its way into many apps though. Maybe it requires changes at
>the toolkit level and would break compatibility in some way.
Yes, it's a toolkit issue, and probably something we should
not "fix" for individual applications. Doing what is expected
might be better than doing what's "best".
I think NeXT had this, right? So does some Linux GUI toolkits.
Not only the NextStep derivates.
MacOS 8/9 had both arrowheads in both ends of the scrollbar, to
try to please everybody. I don't know if that kind of duplication
was a good idea. I'm not sure what MacOS X does.
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se
From magnus@thinkware.se Mon Jan 6 12:04:49 2003
From: magnus@thinkware.se (Magnus Lycka)
Date: Mon Jan 6 12:04:49 2003
Subject: [Tutor] Taking a screenshot
In-Reply-To: <000101c2b52e$48d81900$853c86ac@aeo120>
Message-ID: <5.1.0.14.0.20030106130623.02beabb0@www.thinkware.se>
At 21:49 2003-01-05 -0500, Andy Osagie wrote:
>Is it possible to use Python to take a screenshot of the script-user s
>screen and then save it in some popular image format? I did some searching
>for an answer but couldn t find any module that would help me do it or any
>instructions on how to. Are there any suggestions? Thanks in advance.
I'm sure it is, but as we discussed recently, things like
this are done in different ways on different platforms. This
is not a general enough thing for Python to have one standard,
cross-platform way of doing it.
I you are using MS Windows, I imagine there is a way of doing
this through the win32 libraries in the Mark Hammonds win32all
bundle. (This is included by default in ActivePython.)
I doubt that there are Python specific docs for this though. You
might have to wade through some Win32 docs to figure it out. Or
try the python-win32 mailing list.
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se
From Don Arnold"
Message-ID: <041d01c2b57d$a74ff5d0$6410ba3f@defaultcomp>
----- Original Message -----
From: "Tony Cappellini"
To:
Sent: Monday, January 06, 2003 1:24 AM
Subject: [Tutor] Python docs- makes the learning harder sometimes
>
>
> I've got a book which refers to some really useful string functions like.
>
> startswith()
> endswith()
>
> as in
> s="Hello Python"
> s.startswith("He")
> s.endswith("on",6)
>
> where each function has 2 parameters,
> however, I don't understand why these functions are not in the Global
> Module Index
>
I think you're expecting too much of the Global Module Index. It provides a
llisting of Python's standard modules. What you are looking for are methods
of the string class. Since this class is built into the language, there's no
module associated with it to index. You'll have better luck looking for
these in the Python Library Reference, where they're under section 2.2.6.1,
'String Methods'.
> Arggggghh !
>
I understand your frustration. Learning a language straight from the
documentation (even a great language with great documentation) is tough. I
think you're better off working with a book that teaches Python, such as
Chun's "Core Python Programming" or Lutz's "Learning Python".
HTH,
Don
From alan.gauld@bt.com Mon Jan 6 12:20:41 2003
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon Jan 6 12:20:41 2003
Subject: [Tutor] Debug
Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022E9@i2km11-ukbr.domain1.systemhost.net>
> >Use Next instead of Step. Step steps intp when you *really* want to
> >get inside a function...
>
> Unfortunately that does not solve the problem with the
> PythonWin debugger.
> It still halts in debugger.py.
I didn't get that problem, I just set a break point, hit run then
used step over/step into to go through my code.
I tried the same in IDLE and found its debugger to be far bewtter
since it highlighted the source code better but both debuggers
step through code OK.
Neither has a watch function although both display variables
values dynamically. The Python standard debugger(pdb) is better
than either IMHO, albeit non GUI.
Alan g.
From alan.gauld@bt.com Mon Jan 6 12:20:52 2003
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon Jan 6 12:20:52 2003
Subject: [Tutor] Tkinter
Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022EA@i2km11-ukbr.domain1.systemhost.net>
> In another example, I have a button on the window. And a function is
> set to run for that. But it runs right away. And nothing happens when
> I hit the button!
You are probably trying to assign the command to a function call
rather than a function name. ie you added parentheses after the
function name. You need a reference to the fiunction
- like a function pointer in C/C++
Alan G.
From alan.gauld@bt.com Mon Jan 6 12:21:02 2003
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon Jan 6 12:21:02 2003
Subject: [Tutor] Comments
Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022EB@i2km11-ukbr.domain1.systemhost.net>
> How is it you phrase comments? When I'd like to take out a block and
> experiment with the rest, what's the method?
>
> {
>
> code
> ...
>
> won't run
>
> }
>
> print "will run"
In IDLE Select the region and choose the Edit|Comment region menu command.
Or if you prefer wrap it in an "if 0:" clause - indenting the section by
1 char or whatever...
Alan g.
From dyoo@hkn.eecs.berkeley.edu Mon Jan 6 12:22:13 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jan 6 12:22:13 2003
Subject: [Tutor] Python docs- makes the learning harder sometimes
In-Reply-To: <5.1.0.14.0.20030105232139.01a768c0@smtp.sbcglobal.net>
Message-ID:
On Sun, 5 Jan 2003, Tony Cappellini wrote:
> startswith()
> endswith()
>
> as in
> s="Hello Python"
> s.startswith("He")
> s.endswith("on",6)
>
> where each function has 2 parameters,
> however, I don't understand why these functions are not in the Global
> Module Index
Hi Tony,
The index here:
http://www.python.org/doc/lib/genindex.html
does have entries for startswith() and endswith():
http://www.python.org/doc/lib/string-methods.html#l2h-141
http://www.python.org/doc/lib/string-methods.html#l2h-119
Hope this helps!
From alan.gauld@bt.com Mon Jan 6 12:22:24 2003
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon Jan 6 12:22:24 2003
Subject: [Tutor] open extra xterm?
Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022EF@i2km11-ukbr.domain1.systemhost.net>
> So I need at least two windows. How do I open a second xterm for
> output, while I use my main one as a readline terminal?
Simplest way is to redirect your output to a file then simply
"tail" the file in the second xterm.
$ man tail
> I'm assuming pipes or something like that,
Shouldn't be necessary - unless you will be generating huge
amounts of output!
As I said earlier unix *is* an IDE...
Alan g
From charlie@begeistert.org Mon Jan 6 12:25:36 2003
From: charlie@begeistert.org (Charlie Clark)
Date: Mon Jan 6 12:25:36 2003
Subject: [Tutor] Assigning function keywords dynamically
In-Reply-To:
References:
Message-ID: <20030106163824.631.1@.1041865326.fake>
On 2003-01-06 at 00:34:40 [+0100], Tim Peters wrote:
> You're building a mapping from strings to durations, which screams
> "dict". Like so:
>
> _name2dur =3D {"monatlich": RelativeDateTime(months=3D+1),
> "w=F6chentlich": RelativeDateTime(weeks=3D+1).
> "t=E4glich": RelativeDateTime(days=3D+1),
> }
>dur =3D _name2dur.get(interval)
mm, okay I understand the mapping thing but this doesn't seem much more
efficient (in terms of typing) or sensible than the series of ifs I had; it=
probably runs a lot faster though but then again that isn't important when
compared with the subsequent SQL calls... But the mapping should be
{"monatlich": "months"...} with an intermediary function (lambda()?,
exec()?) magically inserting the keyword in a RelativeDateTime() call.
ie. return now() + RelativeDateTime(magicfunction(dur))
I also have three questions: why do you use the "_" in the name? And is
.get() becoming standard for dictionaries? how close is the upcoming
"datetime" module to mx.DateTime. For those not already aware Python 2.3
will ship with a new datetime module which has many functions similar to
the very useful eGenix's mx.DateTime.
I remember you once made a remark about it has long been possible to make
real digital computers as opposed to our current binary ones. Could you
provide a reference? I discuss these kind of things with my dad who while
regularly presenting a replica of the world's first electronic computer
("Baby" at the Museum of Science and Industry in Manchester) and going back=
as far as IBM 704s, etc. doesn't seem to recall such devices. They sound
fascinating and probably very useful.
Can anybody point me to a reasonable reference as to why so much time,
energy has been spent "developing" Linux over the last 10 years in order to=
come up essentially with a new 4.4 BSD lite? My real interest in this is:
why did yet another Unix clone receive such tremendous input from the
academic community although it seemed essentially to be reinventing the
wheel and repeating the mistakes and lessons of the previous 20 years. As
only an occasional programmer what interests me primarily are the "design"
and "project management" issues which are common to all open source
projects. The relation to Python is that Python seems to have maintained
focus and avoided feature creep to a large extent while managing to be
innovative I understand and increasingly respect this but it leaves me
wondering: how much innovation occurs when the commercial imperative is
removed? Apply this directly to Python: how many modules which are now part=
of the standard library were themselves previously commercial extensions or=
are clean room implementations of such modules, ie. mx.DateTime and
datetime; when can we afford to give something away?
Thank you very much
Charlie
From alan.gauld@bt.com Mon Jan 6 12:28:48 2003
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon Jan 6 12:28:48 2003
Subject: [Tutor] 'if a==b or a==c or a==d' alternative (was: pausing a
nd layout)
Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022F0@i2km11-ukbr.domain1.systemhost.net>
> I've come to the conclusion that I like the seemingly SQL'ish
> alternative to the 'if' statement above:
>
> if p in ('Q','q',''):
> sys.exit()
Or even:
if p in 'Qq ':
sys.exit()
saves a few quote signs...
Alan g.
From tim.one@comcast.net Mon Jan 6 12:30:41 2003
From: tim.one@comcast.net (Tim Peters)
Date: Mon Jan 6 12:30:41 2003
Subject: [Tutor] Assigning function keywords dynamically
In-Reply-To: <200301061535.h06FZ9C15436@bright09>
Message-ID:
>> _name2dur =3D {"monatlich": RelativeDateTime(months=3D+1),
>> "w=F6chentlich": RelativeDateTime(weeks=3D+1).
>> "t=E4glich": RelativeDateTime(days=3D+1),
>> }
>> dur =3D _name2dur.get(interval)
[Charlie Clark]
> mm, okay I understand the mapping thing but this doesn't seem much
> more efficient (in terms of typing) or sensible than the series of =
ifs
> I had; it probably runs a lot faster though but then again that isn=
't
> important when compared with the subsequent SQL calls...
It does the job in an obvious way -- that's as Pythonic as you can ge=
t.
dict-based code is also easier to change/maintain than masses of "if"
statements, and the mapping it provides can be reused in other routin=
es.
> But the mapping should be {"monatlich": "months"...} with an
> intermediary function (lambda()?, exec()?) magically inserting the
> keyword in a RelativeDateTime() call.
Why? The obvious way works the first time, and is easily understood =
by
anyone. If you had 10,000 phrases to map to durations, then a deeper=
level
of magic may be justified, but you've only got three values here.
> ie. return now() + RelativeDateTime(magicfunction(dur))
Spell it
return now() + RelativeDateTime(**magicfunction(dur))
and you could have magicfunction return a dict. Now you're asking "w=
hat?"
. That's the point: extra obscurity isn't worth it. If you t=
hink
there's some virtue in not typing RelativeDateTime 3 times, you can s=
cratch
that itch (again at the cost of greater obscurity) via, e.g.,
r =3D RelativeDateTime
_name2dur =3D {"monatlich": r(months=3D+1),
"w=F6chentlich": r(weeks=3D+1).
"t=E4glich": r(days=3D+1),
}
> I also have three questions: why do you use the "_" in the name?
That's a convention for names private to a module. It tells the read=
er that
_name2dur isn't part of the module's public API. If you would rather=
make
it public, that's fine too.
> And is .get() becoming standard for dictionaries?
Unclear what you're asking; dict.get() has been in Python a long time=
.
> how close is the upcoming "datetime" module to mx.DateTime.
They're different designs. datetime is aimed more at efficient field
extraction, mxDateTime more at efficient arithmetic. A detailed comp=
arison
would take more time than I can make.
> ...
>
> I remember you once made a remark about it has long been possible t=
o
> make real digital computers as opposed to our current binary ones.
Sorry, doesn't ring a bell; binary sounds pretty digital to me =
.
From alan.gauld@bt.com Mon Jan 6 12:32:33 2003
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon Jan 6 12:32:33 2003
Subject: [Tutor] getting input from keyboard
Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022E5@i2km11-ukbr.domain1.systemhost.net>
> >> My online web tutor (and book!)has a topic on event driven
> >> programming which includes an example of using msvcrt.getch()
>
> I could not actually find it there. Can you check if that's where it
> should be?
mea culpa! It's in the paper book not the web version. The web version
uses BASIC INKEY$ for the example, the book OTOH is all in Python so uses
msvcrt... sorry.
Alan G.
From alan.gauld@bt.com Mon Jan 6 12:34:49 2003
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon Jan 6 12:34:49 2003
Subject: [Tutor] pausing and layout
Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022EE@i2km11-ukbr.domain1.systemhost.net>
> I guess I have three questions, the first being: Is there a
> python command to pause until the user does something?
Check out raw_input()
> Also, how do you get python (when you don't run it in DOS
> Prompt) to not auto-exit?
There are several ways, the easiest is to use raw_input()
- see above :-)
> I was wondering how you do visual stuff, or make a
> program run in a window, instead of in the command prompt screen?
Try the GUI programming topic in my online tutorial:
Alan g.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld/
From sxa@fluent.com Mon Jan 6 12:35:41 2003
From: sxa@fluent.com (Sebastien Auclair)
Date: Mon Jan 6 12:35:41 2003
Subject: [Tutor] What's wrong with this code ?
Message-ID: <068a01c2b5a8$5f2b94a0$8ae4e9c0@sxapc>
See code example below !
We are embeding python and our C++ software is trying to get an C++ pointer
to an C++ object instantiated in a python module.
This python Class "MyClass" is a sub-class of the C++ "An_Insterface*" class
declared in library "A_Lib" that is of course accessible through SIP
bindings.
The few lines :
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
An_Interface* m_interface = NULL;
PyObject *mdict = NULL;
PyObject *func1 = NULL;
PyObject * v1 = NULL;
PyObject * sipClass;
int bErrorOccured = 0;
initlibsip();
mdict = PyModule_GetDict(m_pylib); // m_pylib is the compiled python
file... this isvalid...It was tested.
func1 = PyDict_GetItemString(mdict, "CreateInstance"); // The function
that returns an instance of the desired class. (as a pointer)
v1 = PyObject_CallObject(func1,NULL); // v1 will then contain some value
other than NULL
if (v1 == Py_None || sipIsSubClassInstance(v1,sipClass)){
file://Interesting !! This (if) test will always be FALSE (For both)
}
///// HERE ARE THE CONVERSION ATTTEMPS !!!!!!!!!!!!!!
m_interface = (An_Interface*)sipConvertToCpp (v1,sipClass,
&bErrorOccured); // returns NULL with bErrorOccured == 1
m_interface = sipForceConvertTo_An_Interface(v1, &bErrorOccured); //
returns NULL with bErrorOccured == 1
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Of course, the two last lines are both trying to do the same thing. It is
just to show you what we tried.
The python file, in short, looks like this :
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
def CreateInstance( ):
return MyClass ()
class MyClass (A_Lib.An_Interface):
def __init__(self):
A_Lib.An_Interface.__init__(self)
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
From charlie@begeistert.org Mon Jan 6 12:40:17 2003
From: charlie@begeistert.org (Charlie Clark)
Date: Mon Jan 6 12:40:17 2003
Subject: [Tutor] Assigning function keywords dynamically
In-Reply-To:
References:
Message-ID: <20030106172212.1334.3@.1041865326.fake>
On 2003-01-06 at 17:00:49 [+0100], Tim Peters wrote:
> r =3D RelativeDateTime
> _name2dur =3D {"monatlich": r(months=3D+1),
> "w=F6chentlich": r(weeks=3D+1).
> "t=E4glich": r(days=3D+1),
> }
That seems like a good compromise. Repeatedly typing "RelativeDateTime"
means typos and copy + paste leads to different errors. Will see if I can
amend this in the function which where I would like it - keep the mapping
compact and maintain functional visibility.
> > I also have three questions: why do you use the "_" in the name?
>
> That's a convention for names private to a module. It tells the reader
> that _name2dur isn't part of the module's public API. If you would
> rather make it public, that's fine too.
name-mangling. I've heard of it but I've never read anything about when to
use it and when not to use it.
> > And is .get() becoming standard for dictionaries?
>
> Unclear what you're asking; dict.get() has been in Python a long time.
I know that but I'm more used to dict['item']. I guess it has more to with
class/functional duality and programming style in Python. Could you please
explain the difference and the relevance to TOWTDT for this.
> > how close is the upcoming "datetime" module to mx.DateTime.
>
> They're different designs. datetime is aimed more at efficient field
> extraction, mxDateTime more at efficient arithmetic. A detailed
> comparison would take more time than I can make.
That's all I need to know. Seeing as Marc-Andr=E9 lives close to me I can
ask him the next time we meet for a beer.
> > ...
> >
> > I remember you once made a remark about it has long been possible to
> > make real digital computers as opposed to our current binary ones.
>
> Sorry, doesn't ring a bell; binary sounds pretty digital to me .
Base2 !=3D Base10 the last time I checked.
It was in connection with floating point and something along the lines of
"real digital computers have been possible for a long time now and would
make all of this [floating point] mess unnecessary".
Charlie
From sxa@fluent.com Mon Jan 6 12:43:02 2003
From: sxa@fluent.com (Sebastien Auclair)
Date: Mon Jan 6 12:43:02 2003
Subject: [Tutor] What's wrong with this code ?
Message-ID: <06b201c2b5a9$db1a7580$8ae4e9c0@sxapc>
See code example below !
We are embeding python and our C++ software is trying to get a C++ pointer
to a C++ object instantiated in a python module.
This python Class "MyClass" is a sub-class of the C++ "An_Insterface*" class
declared in library "A_Lib" that is of course accessible through SIP
bindings.
The few CPP lines :
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
An_Interface* m_interface = NULL;
PyObject *mdict = NULL;
PyObject *func1 = NULL;
PyObject * v1 = NULL;
PyObject * sipClass;
int bErrorOccured = 0;
initlibsip();
mdict = PyModule_GetDict(m_pylib); // m_pylib is the compiled python
file... this isvalid...It was tested.
func1 = PyDict_GetItemString(mdict, "CreateInstance"); // The function
that returns an instance of the desired class. (as a pointer)
v1 = PyObject_CallObject(func1,NULL); // v1 will then contain some value
other than NULL
if (v1 == Py_None || sipIsSubClassInstance(v1,sipClass)){
// Interesting !! This (if) test will always be FALSE (For
both)
}
///// HERE ARE THE CONVERSION ATTTEMPS !!!!!!!!!!!!!!
m_interface = (An_Interface*)sipConvertToCpp
(v1,sipClass,&bErrorOccured); // returns NULL with bErrorOccured == 1
m_interface = sipForceConvertTo_An_Interface(v1, &bErrorOccured); //
Returns NULL with bErrorOccured == 1
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Of course, the two last lines are both trying to do the same thing. It
isjust to show you what we tried.
The python file, in short, looks like this :
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
def CreateInstance( ):
return MyClass ()
class MyClass (A_Lib.An_Interface):
def __init__(self):
A_Lib.An_Interface.__init__(self)
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
From charlie@begeistert.org Mon Jan 6 13:02:07 2003
From: charlie@begeistert.org (Charlie Clark)
Date: Mon Jan 6 13:02:07 2003
Subject: [Tutor] Assigning function keywords dynamically
In-Reply-To:
References:
Message-ID: <20030106190508.2864.10@.1041865326.fake>
On 2003-01-06 at 18:44:18 [+0100], Tim Peters wrote:
>
> I expect you're conflating "digital" with "decimal", then. That's
> unusual. Digital is usually contrasted with analog, in the sense of
> discrete versus continuous.
You're right I am but I think I'm etymologically correct - we have ten
digits.
> > It was in connection with floating point and something along the lines
> > f "real digital computers have been possible for a long time now and
> > would make all of this [floating point] mess unnecessary".
>
> Decimal arithmetic does hold fewer surprises for people than binary
> floating-point, not because it's inherently better, but because people
> have certain expectations derived from a lifetime of experience with
> decimal arithmetic. That's where the feeling of discomfort comes from
> when seeing, e.g.,
>
> >>> .1
> 0.10000000000000001
indeed and I believe it can lead to problems.
> Classes simulating decimal arithmetic in Python are available now; for
> example (one close to my heart )
>
> http://sourceforge.net/projects/fixedpoint/
filed for in case I ever need it!
> Some very early computers did decimal arithmetic in hardware, but direct
> HW support for it has been falling ever since. Here's a good link:
Checking it out! IBM has impressive resources. How much difference would it
make if the hardware did support it directly? Would it be possible to build
more effecient hardware to counter current sledgehammer developments? I
somehow have the feeling that it's application field would be wider than
the cited "financial" and "scientific" applications.
Thanx again
Charlie
From tim.one@comcast.net Mon Jan 6 13:14:22 2003
From: tim.one@comcast.net (Tim Peters)
Date: Mon Jan 6 13:14:22 2003
Subject: [Tutor] Assigning function keywords dynamically
In-Reply-To: <200301061619.h06GJ3G09129@bright08.icomcast.net>
Message-ID:
[Charlie Clark]
> ...
> I know that but I'm more used to dict['item']. I guess it has
> more to with class/functional duality and programming style in Python.
> Could you please explain the difference and the relevance to TOWTDT
> for this.
If you're happy to get a KeyError exception from dict[item], that's fine.
If you would rather raise your own exception if a key is missing, and you
know None isn't a possible dict value,
result = dict.get(item) # or dict.get(item, None)
if result is None;
raise MyException
is fine. It's not deep, it's a matter of what you want to do.
>>>
>>> I remember you once made a remark about it has long been possible to
>>> make real digital computers as opposed to our current binary ones.
>> Sorry, doesn't ring a bell; binary sounds pretty digital to me .
> Base2 != Base10 the last time I checked.
I expect you're conflating "digital" with "decimal", then. That's unusual.
Digital is usually contrasted with analog, in the sense of discrete versus
continuous.
> It was in connection with floating point and something along the lines
> f "real digital computers have been possible for a long time now and
> would make all of this [floating point] mess unnecessary".
Decimal arithmetic does hold fewer surprises for people than binary
floating-point, not because it's inherently better, but because people have
certain expectations derived from a lifetime of experience with decimal
arithmetic. That's where the feeling of discomfort comes from when seeing,
e.g.,
>>> .1
0.10000000000000001
>>>
Classes simulating decimal arithmetic in Python are available now; for
example (one close to my heart )
http://sourceforge.net/projects/fixedpoint/
Some very early computers did decimal arithmetic in hardware, but direct HW
support for it has been falling ever since. Here's a good link:
http://www2.hursley.ibm.com/decimal/
From emil@lysator.liu.se Mon Jan 6 13:24:06 2003
From: emil@lysator.liu.se (Emil Styrke)
Date: Mon Jan 6 13:24:06 2003
Subject: [Tutor] pyLpd
In-Reply-To:
References:
Message-ID: <3E19C64E.106@lysator.liu.se>
janos.juhasz@VELUX.com wrote:
> Dear all,
>
> This would be the very base of my test lpd, but i don't know how can i send
> back an 'octete of zero bits' for acknowledgement
> with self.wfile.write()
That would be a byte (octet) with the value 0. You can produce one with
the string "\0". (Unlike in C, where this would just result in an empty
string.)
/Emil
>
> ******
> import SocketServer
>
>
> class pyLpd(SocketServer.StreamRequestHandler):
> def handle(self):
> lines = self.rfile.readlines()
> self.wfile.write()
> print lines
>
>
> if __name__ == '__main__':
> server = SocketServer.TCPServer( ('', 515), pyLpd)
> server.serve_forever()
> *****
>
> Best regards,
> -----------------------
> Juhász János
> IT department
>
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
From alan.gauld@bt.com Mon Jan 6 13:50:34 2003
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon Jan 6 13:50:34 2003
Subject: [Tutor] Better (free) IDEs than IDLE for Linux ?
Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022F7@i2km11-ukbr.domain1.systemhost.net>
> MacOS 8/9 had both arrowheads in both ends of the scrollbar, to
> try to please everybody. I don't know if that kind of duplication
> was a good idea. I'm not sure what MacOS X does.
Mac OS X lets you choose which style in the user prefeences but
by default they are both at the bottom.
Welcome back Magnus :-)
Alan g.
From Adam Vardy Mon Jan 6 13:58:02 2003
From: Adam Vardy (Adam Vardy)
Date: Mon Jan 6 13:58:02 2003
Subject: [Tutor] Tkinter
In-Reply-To: <0b1801c2b37a$d2632490$8510ba3f@defaultcomp>
References: <1528827481.20030103161511@roadrunner.nf.net>
<0b1801c2b37a$d2632490$8510ba3f@defaultcomp>
Message-ID: <1233543745.20030106151911@roadrunner.nf.net>
Friday, January 3, 2003, 7:22:25 PM, you wrote:
>>
>> Experimenting with TK, I came up on difficulties. Like, in one
>> program, the window is there but whenever the pointer is over the
>> window, there is always an hourglass. Can't see anything
>> wrong.
>> I don't know about this one, but does it happen when you execute the script
>> from the command prompt?
Specifically from a command prompt:
=============================================================
from Tkinter import *
import time,msvcrt
root = Tk()
c = Canvas(root)
c.pack()
o = c.create_text(35,35,text="Hi!")
root.update()
for i in range (1,10):
c.move(o,8*i,0)
root.update()
a=msvcrt.getch()
>> Most IDEs have their own event loop that doesn't
>> play nice with Tkinter.
>>
>> This is a pretty common error. Make sure the callback you supply to the
>> button constructor does _not_ include the parentheses. For example:
>> b = Button(master, text="OK", command=self.ok)
>> assigns the function 'self.ok' as the callback to be executed when the
>> button is pressed. However,
>> b = Button(master, text="OK", command=self.ok( ) )
>> executes self.ok( ) once when the button is istantiated and assigns the
>> result to the button's 'command' attribute.
How then do you send an argument to the function? And where was it
said that you could just type the name, and no () which always seem
mandatory?
--
Adam Vardy
From Adam Vardy Mon Jan 6 13:59:08 2003
From: Adam Vardy (Adam Vardy)
Date: Mon Jan 6 13:59:08 2003
Subject: [Tutor] Debug
In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097022E9@i2km11-ukbr.domain1.systemhost.net>
References: <7497DCA1C240C042B28F6657ADFD8E097022E9@i2km11-ukbr.domain1.systemhost.net>
Message-ID: <1304053478.20030106152740@roadrunner.nf.net>
Monday, January 6, 2003, 9:46:24 AM, you wrote:
>> Unfortunately that does not solve the problem with the
>> PythonWin debugger.
>> It still halts in debugger.py.
>> I didn't get that problem, I just set a break point, hit run then
>> used step over/step into to go through my code.
Ah, finally a Hand! :-)
Bless you Alan. Ok, for that, maybe you could be more specific. After
you hit Run, you probably got a prompt? How did you answer it? And
what happened after that?
--
Adam Vardy
From alan.gauld@bt.com Mon Jan 6 14:28:44 2003
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon Jan 6 14:28:44 2003
Subject: [Tutor] Assigning function keywords dynamically
Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022F8@i2km11-ukbr.domain1.systemhost.net>
> from mx.DateTime import now(), DateTime.RelativeDateTime
>=20
> def new_date(interval):
> if interval =3D=3D "monatlich":
> return now() + RelativeDateTime(months=3D+1)
> elif interval =3D=3D "w=F6chentlich":
> return now() + RelativeDateTime(weeks=3D+1)
> elif interval =3D=3D "t=E4glich":
> return now() + RelativeDateTime(days=3D+1)
> else:
> return "Invalid interval"
I don't know how RelativeDAteTime works but I assume it is returning=20
a fixed value. Thus I'd store them in a dictionary and do:
Intervals =3D {"mon":RelativeDateTime(months=3D+1),
"week":RelativeDateTime(weeks=3D+1),
"day":RelativeDateTime(days=3D+1)
}
def new_date(interval):
return now() + Intervals[interval]
That will raise an exception automatically if the key doesn't exist.
Alan g.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld/
From alan.gauld@bt.com Mon Jan 6 14:41:09 2003
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Mon Jan 6 14:41:09 2003
Subject: [Tutor] Taking a screenshot
Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022F9@i2km11-ukbr.domain1.systemhost.net>
This message is in MIME format. Since your mail reader does not understand
this format, some or all of this message may not be legible.
------_=_NextPart_001_01C2B5B2.B36CB21F
Content-Type: text/plain;
charset="iso-8859-1"
> Is it possible to use Python to take a screenshot of the script-user's
screen
> and then save it in some popular image format?
That would be incredibly system dependant. Its the same problem as trying to
clear the
screen - how can Python know what kind of screen the user has? eg. How do
you take a
screen shot of a paper teletype?
Or what about a server which doesn't have a screen?
> I did some searching for an answer but couldn't find any module that
would help me
> do it or any instructions on how to. Are there any suggestions? Thanks in
advance.
It might be possible to set up a 3rd party tool to do so using os.system()
Thats the best I can think of.
Alan g.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld/
------_=_NextPart_001_01C2B5B2.B36CB21F
Content-Type: text/html;
charset="iso-8859-1"
> Is it
possible to use Python to take a screenshot of the script-user’s
screen
> and then
save it in some popular image format?
That would be incredibly system dependant. Its the same
problem as trying to clear the
screen - how can Python know what kind of screen the
user has? eg. How do you take a
screen shot of a paper teletype?
Or what about a server which doesn't have a
screen?
> I did some searching for an answer
but couldn’t find any module that would help me
> do it or
any instructions on how to. Are there any suggestions? Thanks in advance.
It might be possible to set up a
3rd party tool to do so using os.system()
Thats the best I can think
of.
------_=_NextPart_001_01C2B5B2.B36CB21F--
From abli@freemail.hu Mon Jan 6 14:49:42 2003
From: abli@freemail.hu (Abel Daniel)
Date: Mon Jan 6 14:49:42 2003
Subject: [Tutor] open extra xterm?
In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097022EF@i2km11-ukbr.domain1.systemhost.net>
References: <7497DCA1C240C042B28F6657ADFD8E097022EF@i2km11-ukbr.domain1.systemhost.net>
Message-ID: <20030106192737.GA1476@hooloovoo>
alan.gauld@bt.com (alan.gauld@bt.com) wrote:
> > So I need at least two windows. How do I open a second xterm for
> > output, while I use my main one as a readline terminal?
>
> Simplest way is to redirect your output to a file then simply
> "tail" the file in the second xterm.
>
> $ man tail
I tried this, too, with tail -f, but there was a noticable lag
(1-2 secs).
In the other solution i posted, which uses named pipes, there was
no visible lag at all.
Abel Daniel
abli@freemail.hu
From aztech1200@yahoo.com Mon Jan 6 17:23:14 2003
From: aztech1200@yahoo.com (Aztech Guy)
Date: Mon Jan 6 17:23:14 2003
Subject: [Tutor] Better (free) IDEs than IDLE for Linux ?
In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097022F7@i2km11-ukbr.domain1.systemhost.net>
Message-ID: <20030106215135.86451.qmail@web9807.mail.yahoo.com>
--- alan.gauld@bt.com wrote:
> Welcome back Magnus :-)
I second the motion ! :-/
__________________________________________________
Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now.
http://mailplus.yahoo.com
From dyoo@hkn.eecs.berkeley.edu Mon Jan 6 17:43:55 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon Jan 6 17:43:55 2003
Subject: [Tutor] open extra xterm?
In-Reply-To: <20030106192737.GA1476@hooloovoo>
Message-ID:
On Mon, 6 Jan 2003, Abel Daniel wrote:
> alan.gauld@bt.com (alan.gauld@bt.com) wrote:
> > > So I need at least two windows. How do I open a second xterm for
> > > output, while I use my main one as a readline terminal?
> >
> > Simplest way is to redirect your output to a file then simply
> > "tail" the file in the second xterm.
> >
> > $ man tail
> I tried this, too, with tail -f, but there was a noticable lag
> (1-2 secs).
Hi Abel,
By the way, the lag is probably due to the polling behavior of 'tail -f'.
By default, tail checks the status of the file only every second. If we
want to make the polling occur more frequently, we can set the "sleep
interval" by using the '-s' option to something shorter.
Hope this helps!
From israel@lith.com Mon Jan 6 18:03:54 2003
From: israel@lith.com (Israel Evans)
Date: Mon Jan 6 18:03:54 2003
Subject: [Tutor] Better (free) IDEs than IDLE for Linux ?
Message-ID:
Enjoying Jedit which is free and in Java. It also has a Jython Console
embedded in it as well as a TON of plugins and Macros available on line.
While it doesn't have a CPython inside, it is pretty darn cool.
www.jedit.org is where to go. I've got it working very nicely on both my
Windows and MacOSX boxes.
~Israel~
-----Original Message-----
From: Aztech Guy [mailto:aztech1200@yahoo.com]
Sent: 06 January 2003 1:52 PM
To: tutor@python.org
Subject: RE: [Tutor] Better (free) IDEs than IDLE for Linux ?
--- alan.gauld@bt.com wrote:
> Welcome back Magnus :-)
I second the motion ! :-/
__________________________________________________
Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now.
http://mailplus.yahoo.com
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
_________________________________________________
Scanned for viruses on 06 Jan 2003 22:24:15
No viruses found.
Virus scanning by http://erado.com
From glingl@aon.at Mon Jan 6 19:00:23 2003
From: glingl@aon.at (Gregor Lingl)
Date: Mon Jan 6 19:00:23 2003
Subject: [Tutor] Tkinter
References: <1528827481.20030103161511@roadrunner.nf.net> <0b1801c2b37a$d2632490$8510ba3f@defaultcomp> <1233543745.20030106151911@roadrunner.nf.net>
Message-ID: <3E1A117B.30006@aon.at>
Hi, Adam!
I will shortly first give a diagnosis about the "hour-glass",
then show you an alternative way to accomplish your task
and try to explain (but surely more and clearer explanations
by others will follow)
Adam Vardy schrieb:
>Friday, January 3, 2003, 7:22:25 PM, you wrote:
>
>
>
>>>Experimenting with TK, I came up on difficulties. Like, in one
>>>program, the window is there but whenever the pointer is over the
>>>window, there is always an hourglass. Can't see anything
>>>wrong.
>>>
>>>
>
>
>
>>>I don't know about this one, but does it happen when you execute the script
>>>from the command prompt?
>>>
>>>
If you run the program below from the msdos-prompt, you will observe, that
the "focus" will shift from the msdos-window to the Tkinter-window.
But seemingly msvcrt.getch() doesn't stop it's desire for a keypress, so
your computer
remains waiting for this and therefore shows its wellknown hourglass.
in this situation, if you cliock on the msdos-window, thus restoring the
focus on it, your
program will work (approximately) as expected, but the Tkinter-window
will close after
executuion of the for-loop, something, which you might not have expected.
>Specifically from a command prompt:
>
>=============================================================
>
>from Tkinter import *
>import time,msvcrt
>
>root = Tk()
>c = Canvas(root)
>c.pack()
>
>o = c.create_text(35,35,text="Hi!")
>
>root.update()
>
>for i in range (1,10):
> c.move(o,8*i,0)
> root.update()
> a=msvcrt.getch()
>
>
>
>
This somewhat weird behaviour comes imo from the common use of
Tkinter and msvcrt, which are not made to work together.
On the contrary GUI-programs work according to an entirely different
philosophy. They catch events via the operating system and perform
actions according to these events (and the will of their programmer).
Such events are keypresses, mouseclicks, mousemoves and more ...
The programmer can bind specific actions to specific events. Then the os
informs the GUI-program about the occurence of theses events (and some
data connected with them via an event-object) and the GUI-program
performs the action bound to the event just occuring, probably using
the information, which is contained in the event-object. (Therefore the
os has to deliver the event-object (the description of the event) to the
action which is going to be performed. This action is defined as a function,
which receives the event-object as an argument. (Thus it's definition has
- in most cases - to contain a parameter, which by convention mostly is
called event).
So when the program is activ no programmer-defined loop is necessary,
because there is .... is it? an event-loop, which catches all the occuring
events. Hmmm.... it has to be there. But it has to be put there by the
programmer.
Now, woh can this be done:
(1) determin an action: c.move(o,8,0)
(2) bind it to the KeyPress-event for the root-window
(3) Make the root window listen to the occuring events:
It goes like this:
from Tkinter import *
root = Tk()
c = Canvas(root)
c.pack()
o = c.create_text(35,35,text="Hi!")
root.update()
def moveHi(event):
c.move(o,8,0) # (1)
root.bind("", moveHi) # (2)
root.mainloop() #(3)
-----------------------------------------------
This extremely simple program does not use the information
contained in event.
But the window now can be closed by clicking the x - mark
in the right upper corner (which didn't work with your earlier
program). It recognizes this mouse-click-event and responds
accordingly
If you like to see how the information contained in event can be used,
insert the following statement into the definition of moveHi
before the c.move - call:
c.itemconfigure(o,text=event.keysym)
run the program, press several (different) keys and see the text change!
One more remark to your last question below. A quick experiment in IDLE
shows that there is an important difference between a function(-object) and
the return-value(-object) of the function-
>>> def ten():
return 10
>>> ten()
10
>>> ten
>>>
For our moveHi - function the return-value will be None (as there is no
return-statement in the functino-definition).
It would make no sense to bind None to the KeyPress-Event. What is
needed is a function, i.e. something, which is callable - and which will be
called with an event-object as argument, whenever an event occurs.
In other words:
ten() is a function call, and causes the code of the function to be
executed.
ten is a function - object, which *later* may be called - or even
replaced.
Both are Python-objects and thus can, in principle, be used as arguments.
Look at the following really weird - but working - code:
from Tkinter import *
root = Tk()
c = Canvas(root)
c.pack()
o = c.create_text(35,35,text="Hi!") # I don't like o
root.update()
def moveHi(event):
root.unbind_all("")
root.bind("", moveback)
c.move(o,50,0)
def moveback(event):
root.unbind_all("")
root.bind("", moveHi)
c.move(o,-50,0)
root.bind("", moveHi)
root.mainloop()
Hope, this is a first step to clearifying GUI- things.
Regards, Gregor
>
>
>>>Most IDEs have their own event loop that doesn't
>>>play nice with Tkinter.
>>>
>>>
>
>
>
>
>
>
>>>This is a pretty common error. Make sure the callback you supply to the
>>>button constructor does _not_ include the parentheses. For example:
>>>
>>>
>
>
>
>>>b = Button(master, text="OK", command=self.ok)
>>>
>>>
>
>
>
>>>assigns the function 'self.ok' as the callback to be executed when the
>>>button is pressed. However,
>>>
>>>
>
>
>
>
>>>b = Button(master, text="OK", command=self.ok( ) )
>>>
>>>
>
>
>
>>>executes self.ok( ) once when the button is istantiated and assigns the
>>>result to the button's 'command' attribute.
>>>
>>>
>
>How then do you send an argument to the function? And where was it
>said that you could just type the name, and no () which always seem
>mandatory?
>
>
>
>
From lumbricus@gmx.net Mon Jan 6 22:33:01 2003
From: lumbricus@gmx.net (lumbricus@gmx.net)
Date: Mon Jan 6 22:33:01 2003
Subject: [Tutor] open extra xterm?
References:
Message-ID: <29890.1041895173@www40.gmx.net>
Hi!
> By the way, the lag is probably due to the polling behavior of 'tail -f'.
> By default, tail checks the status of the file only every second. If we
> want to make the polling occur more frequently, we can set the "sleep
> interval" by using the '-s' option to something shorter.
FYI: This feature is non standard.
> Hope this helps!
Dito, J"o!
--
sigfault
+++ GMX - Mail, Messaging & more http://www.gmx.net +++
NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen!
From gp@pooryorick.com Tue Jan 7 01:01:02 2003
From: gp@pooryorick.com (Poor Yorick)
Date: Tue Jan 7 01:01:02 2003
Subject: [Tutor] unicode utf-16 and readlines [using the 'codecs' unicode file reading module]
References:
Message-ID: <3E1A69D4.2010007@pooryorick.com>
Danny Yoo wrote:
>
>
>You may want to use a "codec" to decode Unicode from a file. The 'codecs'
>module is specifically designed for this:
>
> http://www.python.org/doc/lib/module-codecs.html
>
>
>For example:
>
>###
>
>>>>import codecs
>>>>f = codecs.open('foo.txt', 'w', 'utf-16')
>>>>f.write("hello world")
>>>>f.close()
>>>>open('foo.txt').read()
>>>>
>'\xff\xfeh\x00e\x00l\x00l\x00o\x00 \x00w\x00o\x00r\x00l\x00d\x00'
>
>>>>f2 = codecs.open('foo.txt', 'r', 'utf-16')
>>>>f2.readlines()
>>>>
>[u'hello world']
>###
>
Thanks for the info! Using the codecs module is much better. It's
interesting to note, though, that when using the codecs module on a real
utf-16 text file, Python's automatic handling of new line characters
seems to break down. For example:
>>> import codecs
>>> fh = codecs.open('0022data2.txt', 'r', 'utf-16')
>>> a = fh.read()
>>> a
u'\u51fa\r\n'
>>> print a
??
>>> a = a.strip()
>>> print a
?
>>>
From glingl@aon.at Tue Jan 7 03:21:53 2003
From: glingl@aon.at (Gregor Lingl)
Date: Tue Jan 7 03:21:53 2003
Subject: [Tutor] Tkinter - appendix
Message-ID: <3E1A81EB.8080507@aon.at>
Appendix:
I'm not sure if this was not already posted few days ago.
However, the following link not only does contain
an intro to Tkinter, but also links to most - if not all -
relevant documents on Tkinter:
http://home.att.net/~stephen_ferg/thinking_in_tkinter/index.html
Regards, Gregor
From mongo57a@comcast.net Tue Jan 7 12:26:18 2003
From: mongo57a@comcast.net (andy surany)
Date: Tue Jan 7 12:26:18 2003
Subject: [Tutor] Tk Listbox scrollbars
Message-ID: <000e01c2b670$b9777000$2502a8c0@emily.ewndsr01.nj.comcast.net>
Hello all,
I wrote a program for a scrolled list containing a Y-axis scrollbar
which has been working fine. At this point, my data is also overflowing
the width of the box, so I have added an X-axis scrollbar.
Both scrollbars appear, but the x-axis scrollbar is "vertical" (and
tiny...and I press the up or down arrow to move left or right). What I
want is a "slider" similar to the y scroll bar. I'm pretty sure that the
error is in the way that I am packing the widget, as follows:
sbar.pack(side=RIGHT, fill=Y) # This is for the Y-axis bar and it works
correctly
tbar.pack(side=BOTTOM) # This places the X-axis bar as described above
TIA
-Andy
From alan.gauld@bt.com Tue Jan 7 13:03:02 2003
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue Jan 7 13:03:02 2003
Subject: [Tutor] 'if a==b or a==c or a==d' alternative (was: pausing a
nd layout)
Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DA82@i2km11-ukbr.domain1.systemhost.net>
> > if p in 'Qq ':
> > sys.exit()
>
> I've just looked thru the new stuff on Python 2.3, and it
> seems that it will support larger subsplices, so that
>
> if 'ab' in 'abcdefg':
> print 'found'
>
> will actually print 'found'. Which means that the above
> example would do a sys.exit() if the user types 'Qq'.
Which is probably better than raising an exception which
is what it would do now... I guess the solution will be
to put [0] after the test variable if you really only
want to test 1 char.
if 'ab'[0] in 'abcdefg':...
But that's not so pretty. However it's countered by the number
of folks who obviously expect 'ini' to work as it will
in 2.3 - going by the number of times it crops up as a 'bug'
on this list.
But yes, I agree it's not entirely backward compatible
and might well break some old code that relied on
try/except to catch multi char input...
- oddly enough I was reading the 2.3 stuff myself at
the weekend and wondered about that too.
Alan g.
From alan.gauld@bt.com Tue Jan 7 16:11:22 2003
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue Jan 7 16:11:22 2003
Subject: [Tutor] Applications/examples of some advanced Py features, p
lease !
Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022ED@i2km11-ukbr.domain1.systemhost.net>
This message is in MIME format. Since your mail reader does not understand
this format, some or all of this message may not be legible.
------_=_NextPart_001_01C2B588.41E56D3E
Content-Type: text/plain;
charset="iso-8859-1"
> Can anyone please give some examples / applications of the use of the
following advanced
> (advanced to me, at least :-) features of Python :
1. lambda
I cover lambdas in my Functional Programming topic on my online tutor...
2. nested functions - a little info was given by Danny in reply to my
earlier post on local-static
variables, but I would like more.
Its just a function defined inside another function, it can either be a
helper function for the "parent"
one or it can be a function that is returned by the parent in a similar way
to the lambda construct
(see above). This latter style of programming is powerful in a few areas and
replaces lambdas
in many cases.
3. Thoughts on implementing Interfaces in Py - a la Java interfaces.
You can do it since an interface is just a class with empty method
definitions.
What Python won't do is force you to provide definitions though.
However there is little or no need for interfaces in Python since it support
full multiple
inheritance and its dynamic nature makes the use of interfaces redundant in
most cases anyway.
Python effectively checks the interface of any object when it uses it.
> I am planning to write a game-playing program in Py which will have
features somewhat AI - ish.
Thats fine, but you shlouldn't need interfaces. THe other features may be
useful.
> - in what way their use makes code simpler, or maybe makes code possible
> that could not be written otherwise ('possible' in practical terms - I'm
- vaguely - aware
> of the fact that all languages are supposed to be theoretically
'Turing-equivalent' or
> some such term - but what I mean is that if something is going to take a
huge
> amount more code in some other language, or jumping through hoops, then
> I don't call it practically equivalent).
Languages are practically equivalent if they can do the same jobs. There may
be good
reasons to write reams more code - like performance! But for most purposes
each
language has some things it is better at. Python is not the best AI language
but its
better than, say, C++ or Java.
IMHO of course! :-)
Alan g.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld/
------_=_NextPart_001_01C2B588.41E56D3E
Content-Type: text/html;
charset="iso-8859-1"
>
Can anyone please give some examples / applications of
the use of the following advanced
>
(advanced to me, at least :-) features of Python :
1. lambda
I cover
lambdas in my Functional Programming topic on my online
tutor...
2. nested functions - a little info was given by Danny in reply to my
earlier post on local-static
variables, but I would like more.
Its just
a function defined inside another function, it can either be a helper function
for the "parent"
one or it can be a function that is returned by
the parent in a similar way to the lambda construct
(see above). This latter
style of programming is powerful in a few areas and replaces lambdas
in many
cases.
3. Thoughts on implementing Interfaces in Py - a la Java interfaces.
You can
do it since an interface is just a class with empty method definitions.
What Python won't do is
force you to provide definitions though.
However
there is little or no need for interfaces in Python since it support full
multiple
inheritance and its dynamic nature makes the use of interfaces
redundant in most cases anyway.
Python
effectively checks the interface of any object when it uses
it.
> I am planning to write a game-playing
program in Py which will have features somewhat AI - ish.
Thats
fine, but you shlouldn't need interfaces. THe other features may be
useful.
>
- in what way their use makes code simpler, or maybe
makes code possible
> that could not be
written otherwise ('possible' in practical terms - I'm - vaguely -
aware
> of the fact that all languages are
supposed to be theoretically 'Turing-equivalent' or
>
some such term - but
what I mean is that if something is going to take a huge
>
amount more code in
some other language, or jumping through hoops, then
>
I don't call it practically equivalent).
Languages are practically equivalent if they can do the same jobs. There
may be good
reasons to write reams more code - like performance! But
for most purposes each
language has some things it is better at. Python is
not the best AI language but its
better than, say,
C++ or Java.
IMHO of
course! :-)
Alan g.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld/
------_=_NextPart_001_01C2B588.41E56D3E--
From jeff@ccvcorp.com Tue Jan 7 16:17:00 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Tue Jan 7 16:17:00 2003
Subject: [Tutor] Assigning function keywords dynamically
References: <20030106190508.2864.10@.1041865326.fake>
Message-ID: <3E19DD98.3080407@ccvcorp.com>
Charlie Clark wrote:
>On 2003-01-06 at 18:44:18 [+0100], Tim Peters wrote:
>
>
>>I expect you're conflating "digital" with "decimal", then. That's
>>unusual. Digital is usually contrasted with analog, in the sense of
>>discrete versus continuous.
>>
>>
>You're right I am but I think I'm etymologically correct - we have ten
>digits.
>
>
Well, when using decimal arithmetic we use ten digits. When using
binary arithmetic we use two digits, and when using hexadecimal
arithmetic we use sixteen. Actually, it would be more appropriate to
say that we use X number of possible values for each digit, where
0000000001 is a number with ten digits.
The point here being that precision in language can be important.
People are better at guessing likely meanings than computers are, but
it's still important to say precisely what you mean, or someone will
think you mean something else. :)
Jeff Shannon
Technician/Programmer
Credit International
From mcp.bov@insightbb.com Tue Jan 7 16:23:24 2003
From: mcp.bov@insightbb.com (Mike P)
Date: Tue Jan 7 16:23:24 2003
Subject: [Tutor] Re: Help understanding part of the tutorial
References: <20030106165735.4595.40268.Mailman@mail.python.org>
Message-ID: <000601c2b5bf$64f16d80$1de4dc0c@ct192133a>
Message: 5
From: "Lee Harr"
To: tutor@python.org
Date: Sun, 05 Jan 2003 23:46:30 +0000
Subject: [Tutor] Re: Help understanding part of the tutorial
>def mult(a,b):
> if b == 0:
> return 0
> rest = mult(a,b - 1)
> value = a + rest
> return value
>
>print "3*2 = ",mult(3,2)
>
>My question is that I don't get how mult(a,b-1) returns a value
>
Sometimes when debugging, or just trying to understand a piece
of code, it helps to move through the code step by step thinking
(or writing down) what the computer will do at each step:
ok, I am going to call mult(3, 2)
a = 3, b = 2
is b == 0? nope, so
rest = mult(3, 1)
ok, I am going to call mult(3, 1)
a = 3, b = 1
is b == 0? nope, so
rest = mult(3, 0)
# note that rest here is different from the rest up above,
# rest is "local" to this function call and is completely
# independent of the rest in the mult(3, 2) call.
ok, I am going to call mult(3, 0)
a = 3, b = 0
is b == 0? YES, so
return 0
# but, return 0 to where? who called this?
# ah, yes, it was the call to mult(3, 1), so
# back in the call to mult(3, 1)
a = 3, b = 1, rest = 0
value = 3 + 0
return 3
# return to who?
# to the mult(3, 2) call, so
# back in the call to mult(3, 2)
a = 3, b = 2, rest = 3
value = 3 + 3
return 6
# to who?
# mult(3, 2) was the original call, so we're finished
This is called a "recursive" function definition.
(which means that the function calls itself in the process
of calculating a final answer, and sets some kind of a
condition for ending the stack of recursive calls)
I am pretty sure that any recursive function can be written
in a non-recursive way. For instance:
def mult(a,b):
total = 0
while a:
total += b
a -= 1
return total
or, of course
def mult(a, b):
return a * b
-----------------------------------------
I'm still learning Python and wondered if there was a reason
I'm not seeing to use:
def mult(a,b):
if b == 0:
return 0
rest = mult(a,b - 1)
value = a + rest
return value
Instead of:
def mult(a, b):
return a * b
Regards,
Mike P.
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.435 / Virus Database: 244 - Release Date: 12/30/2002
From ramrom@earthling.net Tue Jan 7 16:23:52 2003
From: ramrom@earthling.net (Bob Gailer)
Date: Tue Jan 7 16:23:52 2003
Subject: [Tutor] Debug
In-Reply-To: <1304053478.20030106152740@roadrunner.nf.net>
References: <7497DCA1C240C042B28F6657ADFD8E097022E9@i2km11-ukbr.domain1.systemhost.net>
<7497DCA1C240C042B28F6657ADFD8E097022E9@i2km11-ukbr.domain1.systemhost.net>
Message-ID: <5.2.0.9.0.20030106131240.019fa8e8@66.28.54.253>
--=======63B61ACB=======
Content-Type: text/plain; x-avg-checked=avg-ok-E7844FA; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit
I have just e-mailled the problem to Mark Hammond. Let's see what he has to
say.
Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=======63B61ACB=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-E7844FA
Content-Disposition: inline
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002
--=======63B61ACB=======--
From mongo57a@comcast.net Tue Jan 7 16:34:35 2003
From: mongo57a@comcast.net (andy surany)
Date: Tue Jan 7 16:34:35 2003
Subject: [Tutor] Tk Listbox scrollbars
Message-ID: <00a001c2b5c7$4dc6f8c0$2502a8c0@emily.ewndsr01.nj.comcast.net>
Hello all,
I wrote a program for a scrolled list containing a Y-axis scrollbar
which has been working fine. At this point, my data is also overflowing
the width of the box, so I have added an X-axis scrollbar.
Both scrollbars appear, but the x-axis scrollbar is "vertical" (and
tiny...and I press the up or down arrow to move left or right). What I
want is a "slider" similar to the y scroll bar. I'm pretty sure that the
error is in the way that I am packing the widget, as follows:
sbar.pack(side=RIGHT, fill=Y) # This is for the Y-axis bar and it works
correctly
tbar.pack(side=BOTTOM) # This places the X-axis bar as described above
TIA
-Andy
From aztech1200@yahoo.com Tue Jan 7 16:42:48 2003
From: aztech1200@yahoo.com (Aztech Guy)
Date: Tue Jan 7 16:42:48 2003
Subject: [Tutor] Applications/examples of some advanced Py features, p lease !
In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097022ED@i2km11-ukbr.domain1.systemhost.net>
Message-ID: <20030106213856.82492.qmail@web9801.mail.yahoo.com>
Thanks, Alan !
Az.
--- alan.gauld@bt.com wrote:
> I cover lambdas in my Functional Programming topic
>
> 2. nested functions - a little info was given by
> powerful in a few areas and
> replaces lambdas
>
> 3. Thoughts on implementing Interfaces in Py - a la
> Java interfaces.
>
> You can do it since an interface is just a class
> However there is little or no need for interfaces in
> inheritance and its dynamic nature makes the use of
> interfaces redundant in
> most cases anyway.
>
>
__________________________________________________
Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now.
http://mailplus.yahoo.com
From brad.reisfeld@colostate.edu Tue Jan 7 16:44:12 2003
From: brad.reisfeld@colostate.edu (Brad Reisfeld)
Date: Tue Jan 7 16:44:12 2003
Subject: [Tutor] OO approach to solving problem?
Message-ID:
Hi,
I have a problem that I would like to solve using Python, but am not quite
sure about a good approach. I do not know much about object-oriented
methods, but it seems as if this approach might make sense for my problem.
As a simple example of what I am trying to do, imagine a collection of
creatures that you would like to 'manage'. Each creature has a certain rate
of growth, a certain probability of transforming into another creature at
some point in time, and a given lifetime. You would like to keep an
'inventory' of the creatures as a function of time.
In terms of programming, it seems to me that one approach might be to have
each creature as an instance of a creature class with properties like type
of creature, growth rate, lifetime, transformation probability, and age.
These instances would be created by a 'master class' (a factory class?) that
would 'create' each creature, update it as to its age, and transform it. At
some point, the instance would 'alert' the master class that it is ready to
die and the master class would delete it.
For my problem there will be a _large_ number of 'creatures' (>100000) and
'time' steps (>10^6).
Does the above approach sound reasonable?
If so, I think I know how to address most of the issues. However, I am
unclear as to how the creature instances can communicate with the master
class. How does the instance 'know' who created it and how to pass
information back to it? I'm sure this must be a common design pattern, but
being an old-time Fortran programmer, I haven't acquired much OO experience.
Any advice and suggestions are appreciated.
-Brad
From magnus@thinkware.se Tue Jan 7 16:53:10 2003
From: magnus@thinkware.se (Magnus Lycka)
Date: Tue Jan 7 16:53:10 2003
Subject: [Tutor] Debug
In-Reply-To: <5.2.0.9.0.20030106130034.02c8b820@66.28.54.253>
References: <5.1.0.14.0.20030106001048.02bd4e90@www.thinkware.se>
<5.2.0.9.0.20030102111509.02bd0da8@66.28.54.253>
<1615745792.20030102140009@roadrunner.nf.net>
Message-ID: <5.1.0.14.0.20030106234848.02c146c0@www.thinkware.se>
At 13:01 2003-01-06 -0700, Bob Gailer wrote:
>At 12:13 AM 1/6/2003 +0100, you wrote:
>>May I suggest that you use Boa Constructor
>
>I downloaded it; however there's no instructions (that I can find) about
>how to run it. How do you start it?
First of all, you need wxPython of suitable version as described
in http://boa-constructor.sourceforge.net/Download.html
Once installed you double click on Boa.pyw in Windows.
In other OSes I suppose you run Boa.py...
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se
From lumbricus@gmx.net Tue Jan 7 16:54:26 2003
From: lumbricus@gmx.net (lumbricus@gmx.net)
Date: Tue Jan 7 16:54:26 2003
Subject: [Tutor] pyLpd
References: <3E19C64E.106@lysator.liu.se>
Message-ID: <9258.1041894106@www40.gmx.net>
Hello!
[ snip ]
> That would be a byte (octet) with the value 0. You can produce one with
> the string "\0". (Unlike in C, where this would just result in an empty
> string.)
But a string in C is per definition an array of characters
_terminated by '\0'_. So the "empty string" in C you mention
above (*char s = "") is really one char with value 0
(which is equivalent to '\0') - mostly but not necessarily
an octet AKA byte.
BTW in C:
char *s = "\0";
This gives not an empty string - it is an array of two
characters with value 0.
> /Emil
Greets, J"o!
--
sigfault
+++ GMX - Mail, Messaging & more http://www.gmx.net +++
NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen!
From lumbricus@gmx.net Tue Jan 7 16:55:00 2003
From: lumbricus@gmx.net (lumbricus@gmx.net)
Date: Tue Jan 7 16:55:00 2003
Subject: [Tutor] Taking a screenshot
References: <7497DCA1C240C042B28F6657ADFD8E097022F9@i2km11-ukbr.domain1.systemhost.net>
Message-ID: <23260.1041894779@www40.gmx.net>
Hi!
> > Is it possible to use Python to take a screenshot of the script-user's
> screen
> > and then save it in some popular image format?
>
> That would be incredibly system dependant. Its the same problem as trying
> to
> clear the
> screen - how can Python know what kind of screen the user has? eg. How do
> you take a
> screen shot of a paper teletype?
>
> Or what about a server which doesn't have a screen?
ACK
> It might be possible to set up a 3rd party tool to do so using os.system()
f.e.:
os.system("xwd -root -out x.dump")
os.system("xwud -in x.dump")
works for me.
> Thats the best I can think of.
>
> Alan g.
Greets, J"o!
--
sigfault
+++ GMX - Mail, Messaging & more http://www.gmx.net +++
NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen!
From glingl@aon.at Tue Jan 7 17:00:28 2003
From: glingl@aon.at (Gregor Lingl)
Date: Tue Jan 7 17:00:28 2003
Subject: [Tutor] Tkinter
References: <1528827481.20030103161511@roadrunner.nf.net> <0b1801c2b37a$d2632490$8510ba3f@defaultcomp> <1233543745.20030106151911@roadrunner.nf.net>
Message-ID: <3E1A1505.1020708@aon.at>
Appendix:
I'm not sure if this was not already posted few days ago,
nevertheless the following link not only does contain
an intro to Tkinter, but also links to most - if not all -
relevant documents on Tkinter:
http://home.att.net/~stephen_ferg/thinking_in_tkinter/index.html
Regards, Gregor
Adam Vardy schrieb:
>Friday, January 3, 2003, 7:22:25 PM, you wrote:
>
>
>
>>>Experimenting with TK, I came up on difficulties. Like, in one
>>>program, the window is there but whenever the pointer is over the
>>>window, there is always an hourglass. Can't see anything
>>>wrong.
>>>
>>>
>
>
>
>>>I don't know about this one, but does it happen when you execute the script
>>>from the command prompt?
>>>
>>>
>
>Specifically from a command prompt:
>
>=============================================================
>
>from Tkinter import *
>import time,msvcrt
>
>root = Tk()
>c = Canvas(root)
>c.pack()
>
>o = c.create_text(35,35,text="Hi!")
>
>root.update()
>
>for i in range (1,10):
> c.move(o,8*i,0)
> root.update()
> a=msvcrt.getch()
>
>
>
>
>
>>>Most IDEs have their own event loop that doesn't
>>>play nice with Tkinter.
>>>
>>>
>
>
>
>
>
>
>>>This is a pretty common error. Make sure the callback you supply to the
>>>button constructor does _not_ include the parentheses. For example:
>>>
>>>
>
>
>
>>>b = Button(master, text="OK", command=self.ok)
>>>
>>>
>
>
>
>>>assigns the function 'self.ok' as the callback to be executed when the
>>>button is pressed. However,
>>>
>>>
>
>
>
>
>>>b = Button(master, text="OK", command=self.ok( ) )
>>>
>>>
>
>
>
>>>executes self.ok( ) once when the button is istantiated and assigns the
>>>result to the button's 'command' attribute.
>>>
>>>
>
>How then do you send an argument to the function? And where was it
>said that you could just type the name, and no () which always seem
>mandatory?
>
>
>
>
From magnus@thinkware.se Tue Jan 7 17:03:21 2003
From: magnus@thinkware.se (Magnus Lycka)
Date: Tue Jan 7 17:03:21 2003
Subject: [Tutor] Taking a screenshot
In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097022F9@i2km11-ukbr.domain1
.systemhost.net>
Message-ID: <5.1.0.14.0.20030107002032.02c15a28@www.thinkware.se>
At 18:37 2003-01-06 +0000, alan.gauld@bt.com wrote:
>It might be possible to set up a 3rd party tool to do so using os.system()
This is certainly possible.
For Windows, the win32all bundle has a win32clipboard module,
but the GetClipboardData function doesn't seem to handle images,
only text, so that is of little help. (Maybe there is another way
here.) Otherwise I guess it could have been possible to use some
other function that triggered PrintScreen which would put a screenshot
in the clipboard.
Actually, there is one case where I think it's fairly simple to
get screenshots in Python--cross platform even. Tkinter canvases
can dump screenshots if I understand correctly. At least as PostScript.
But that's no help if you want to get some other kind of screenshot...
Hang on, isn't there support for this in PIL? Yes, if you are using
Windows, it's supported in PIL from version 1.1.3. See the ImageGrab
module in http://www.pythonware.com/products/pil/pil-handbook.pdf
It doesn't seem to work quite as the docs suggests though... I
couldn't find any ImageGrab module. Ask on comp.lang.python, and
I'm pretty sure Fredrik will respond. Else, use his older, separate
grabscreen from http://effbot.org/downloads/
With PIL and grabscreen, I tried this, and it worked:
from PIL import Image
import _grabscreen
size, data = _grabscreen.grab()
im = Image.fromstring("RGB", size, data, "raw", "BGR", (size[0]*3+3) & -4, -1)
im.show()
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se
From fredm@smartypantsco.com Tue Jan 7 17:04:36 2003
From: fredm@smartypantsco.com (Alfred Milgrom)
Date: Tue Jan 7 17:04:36 2003
Subject: [Tutor] keeping track of multiple cascading menus in Tkinter?
Message-ID: <5.1.0.14.0.20030107111212.00ab0220@192.168.1.1>
Hi:
I wonder if anyone can help me?
I am trying to create some menus dynamically, and I would like to know
where a cascading menu is coming from.
Since the menus are built dynamically, the final menu choices could be
coming from any one of a number of parent menu choices, and I can't tell
which one was chosen.
The problem I have with the built-in menu types is that a menu item can be
either a command type or a cascading type, but not both.
I have tried to build a cascading menu with a command but no 'menu='
option, and that will execute a command to convert it to a normal cascading
menu, but it closes the menu before conversion (as with normal menu
choices) so this does not work for me. The relevant parts of this approach are:
self.mFont.add_cascade(label='Font1', command=lambda index=1 :
self.insertCascade(index))
def insertcascade(self, index):
self.mFont.entryconfigure(index, menu=self.styleMenu)
Not only do I want to have style options (normal, bold, italics), but also
size options (10pt, 12pt, etc.) so I don't want to have to create a zillion
font/style/size menus and commands.
Is there a simple way to keep track of where you are in a series of
cascading menus?
(Hope this question makes some sense).
Thanks in anticipation,
Fred Milgrom
Here is a simplified version of the code:
from Tkinter import *
class FontChooser:
def __init__(self, parent=0):
self.mainWindow = Frame(parent)
fMenu=Frame(self.mainWindow)
fMenu.pack(side=TOP,fill=X)
bFont=Menubutton(fMenu, text="Font")
bFont.pack(side=LEFT,anchor=W)
self.mFont = Menu(bFont,tearoff=0)
self.styleMenu = Menu(bFont, tearoff=0)
self.styleMenu.add_command(label='Normal')
self.styleMenu.add_command(label='Bold')
self.styleMenu.add_command(label='Italic')
self.mFont.add_command(label='Font0', command=self.font0)
self.mFont.add_cascade(label='Font1', command=lambda index=1 :
self.insertCascade(index))
bFont["menu"]=self.mFont
self.entry = Entry(self.mainWindow)
self.entry.insert(0,"Choose a font")
self.entry.pack(fill=X)
fOuter = Frame(self.mainWindow, border=1, relief="sunken")
fButtons = Frame(fOuter, border=1, relief="raised")
bClear = Button(fButtons, text="Clear",
width=8, height=1, command=self.clearText)
bQuit = Button(fButtons, text="Quit",
width=8, height=1, command=self.mainWindow.quit)
bClear.pack(side="left", padx=15, pady=1)
bQuit.pack(side="right", padx=15, pady=1)
fButtons.pack(fill=X)
fOuter.pack(fill=X)
self.mainWindow.pack()
self.mainWindow.master.title("Font chooser")
def clearText(self):
self.entry.delete(0,END)
def display (self, text) :
self.clearText()
self.entry.insert(END, text)
def font0(self):
self.display('Font 0 chosen')
def insertCascade(self, index):
self.display("Font 1 chosen")
self.mFont.entryconfigure(index, menu=self.styleMenu)
app = FontChooser()
app.mainWindow.mainloop()
From mongo57a@comcast.net Tue Jan 7 17:13:50 2003
From: mongo57a@comcast.net (andy surany)
Date: Tue Jan 7 17:13:50 2003
Subject: [Tutor] Tk Listbox scrollbars
Message-ID: <032d01c2b698$cfcb8120$2502a8c0@emily.ewndsr01.nj.comcast.net>
Sorry for the multiple postings. Looks like my service provider had
problems.....
-----Original Message-----
From: andy surany
To: tutor@python.org
Date: Tuesday, January 07, 2003 4:35 PM
Subject: [Tutor] Tk Listbox scrollbars
Hello all,
I wrote a program for a scrolled list containing a Y-axis scrollbar
which has been working fine. At this point, my data is also overflowing
the width of the box, so I have added an X-axis scrollbar.
Both scrollbars appear, but the x-axis scrollbar is "vertical" (and
tiny...and I press the up or down arrow to move left or right). What I
want is a "slider" similar to the y scroll bar. I'm pretty sure that the
error is in the way that I am packing the widget, as follows:
sbar.pack(side=RIGHT, fill=Y) # This is for the Y-axis bar and it works
correctly
tbar.pack(side=BOTTOM) # This places the X-axis bar as described above
TIA
-Andy
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
From alan.gauld@bt.com Tue Jan 7 17:55:18 2003
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue Jan 7 17:55:18 2003
Subject: [Tutor] Debug
Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DA7F@i2km11-ukbr.domain1.systemhost.net>
> >> I didn't get that problem, I just set a break point, hit run then
> >> used step over/step into to go through my code.
> you hit Run, you probably got a prompt? How did you answer it? And
> what happened after that?
OK, Here's what I'm doing step by step:
Open Python win
File->Open select debug.py
Select a line in my code and hit F9 - Toggle Breakpoint
*Hit the "Sprinting man" icon in toolbar
*Hit OK in dialog box
Select View_>Toolbars->debugging
In the debug toolbar hit GO (black arrow)
Code runs to breakpoint
Hit Step Into
Code steps into my test function(see below)
Hit step over, code stepsd to first line
Open function/local browser to see variable values
Step over thru' loop a few times
Step out of to exit loop
Examine variable values
Step out of again to reach end of program
Step over ends program with SystemExit exception displkayed
in output (shell) window
I don't think the lines prefixed '*' are needed....
just checked no, they aren't.
HTH,
Alan G.
From alan.gauld@bt.com Tue Jan 7 18:00:40 2003
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Tue Jan 7 18:00:40 2003
Subject: [Tutor] Assigning function keywords dynamically
Message-ID: <7497DCA1C240C042B28F6657ADFD8E097022FD@i2km11-ukbr.domain1.systemhost.net>
I can't resist....
> > _name2dur =3D {"monatlich": RelativeDateTime(months=3D+1),
> > "w=F6chentlich": RelativeDateTime(weeks=3D+1).
> > "t=E4glich": RelativeDateTime(days=3D+1),
> > }
> >dur =3D _name2dur.get(interval)
>=20
> mm, okay I understand the mapping thing but this doesn't seem=20
> much more efficient (in terms of typing)=20
It is if you have to add more entries later since you only need=20
update the dictionary, no modification and potential breaking=20
of existing function code involved.
> compared with the subsequent SQL calls... But the mapping should be=20
> {"monatlich": "months"...} with an intermediary function (lambda()?,=20
> exec()?) magically inserting the keyword in a RelativeDateTime() =
call.
Why? Surely we are just generating a fixed period(month, week etc?)=20
Or is the call clever enough to work out the month length depending=20
on the current date? If the latter then yes a function reference would
be necessary(either by lambda or def f...). But you don't need the=20
intermediate step, just put the function reference into the =
dictionary...)
> I also have three questions: why do you use the "_" in the=20
> name?=20
It prevents external(to the module users) seeing it.
> I remember you once made a remark about it has long been=20
> possible to make real digital computers as opposed to our=20
> current binary ones.=20
An interesting distinction. What does it mean? I've seen an
experimental three state computer once, and some early computers=20
did actually work in octal, but the complexity meant they=20
were slower than binary machines...
> ("Baby" at the Museum of Science and Industry in Manchester)=20
Heh, I saw a film on Baby once - 1956/8 or thereabouts? :-)
> Can anybody point me to a reasonable reference as to why so=20
> much time, energy has been spent "developing" Linux over=20
> the last 10 years in order to come up essentially with a=20
> new 4.4 BSD lite?=20
Have you read Neal Stephenson's history of the command line?
Grep google for Stephenson command line...
Initially it was just for kicks, plus the fact that Unix was=20
at the time(c1991) not free for the PC. Minix and Coherent=20
were available for about $100 each but neither was fully=20
featured. The Hurd was stagnating fast. There were some=20
tentative free BSD developments but they weren't aimed at=20
the PC market.
Then people realised how good Unix on a PC was compared=20
to the alternatives and flocked to it.
> wheel and repeating the mistakes and lessons of the previous=20
> 20 years.=20
But they didn't. Quite a few of the mitakes were learnt from=20
and improved upon. Linux code is/was much better than thhe early=20
Unix stuff from AT&T and even Berkely(sockets aside). It was=20
a modern Unix not an historical one - a trend that continues.
And since Unix is still the best mid range OS what else should=20
they do? Pan 9 from AT&T bombed in the market(it was never=20
really expected to be huge) and BeOS seems to have died a death=20
with only niche support.
> wondering: how much innovation occurs when the commercial=20
> imperative is removed?=20
Quite a lot. There are many open source type software projects=20
that are a long way ahead of any commercial competitor - X Windows=20
itself is probably the best example! Or the GNU emacs editor. Or gcc...
Alan G.
From scot@possum.in-berlin.de Tue Jan 7 18:31:47 2003
From: scot@possum.in-berlin.de (Scot Stevenson)
Date: Tue Jan 7 18:31:47 2003
Subject: [Tutor] 'if a==b or a==c or a==d' alternative (was: pausing a nd layout)
In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097022F0@i2km11-ukbr.domain1.systemhost.net>
References: <7497DCA1C240C042B28F6657ADFD8E097022F0@i2km11-ukbr.domain1.systemhost.net>
Message-ID: <200301070833.36497.scot@possum.in-berlin.de>
Hello Alan,
> if p in 'Qq ':
> sys.exit()
> saves a few quote signs...
I've just looked thru the new stuff on Python 2.3, and it seems that it will
support larger subsplices, so that
if 'ab' in 'abcdefg':
print 'found'
will actually print 'found'. Which means that the above example would do a
sys.exit() if the user types 'Qq'.
Okay, that's probably not going to ruin your party, but in other cases it
might be a nasty side effect one of these days.
Y, Scot
--
Scot W. Stevenson -- scot@possum.in-berlin.de -- Zepernick, Germany
From dyoo@hkn.eecs.berkeley.edu Tue Jan 7 18:34:17 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jan 7 18:34:17 2003
Subject: [Tutor] unicode utf-16 and readlines [using the 'codecs' unicode
file reading module]
In-Reply-To: <3E1A69D4.2010007@pooryorick.com>
Message-ID:
> Thanks for the info! Using the codecs module is much better. It's
> interesting to note, though, that when using the codecs module on a real
> utf-16 text file, Python's automatic handling of new line characters
> seems to break down. For example:
>
> >>> import codecs
> >>> fh = codecs.open('0022data2.txt', 'r', 'utf-16')
> >>> a = fh.read()
> >>> a
> u'\u51fa\r\n'
> >>> print a
> ??
>
>
> >>> a = a.strip()
> >>> print a
> ?
Hi Poor Yorick!
I have to admit I'm a bit confused; there shouldn't be any automatic
handling of newlines when we use read(), since read() sucks all the text
out of a file.
Can you explain more what you mean by automatic newline handling? Do you
mean a conversion of '\r\n' to '\n'?
> >>> a
> u'\u51fa\r\n'
> >>> print a
> ??
>
>
> >>> a = a.strip()
> >>> print a
> ?
I think it's working. If we look at the actual representation of the
strings, both the carriage return and the newline are being removed:
###
>>> a = u"\u51fa\r\n"
>>> a
u'\u51fa\r\n'
>>> a.strip()
u'\u51fa'
###
I can't actually use print or str() to look at the Unicode characters on
my console, since that '\u51fa' character isn't ASCII.
Best of wishes to you!
From phil@xfr.co.uk Tue Jan 7 18:41:24 2003
From: phil@xfr.co.uk (Philip Kilner)
Date: Tue Jan 7 18:41:24 2003
Subject: [Tutor] Assigning function keywords dynamically
In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E097022FD@i2km11-ukbr.domain1.systemhost.net>
References: <7497DCA1C240C042B28F6657ADFD8E097022FD@i2km11-ukbr.domain1.systemhost.net>
Message-ID:
Hi Alan,
In article
<7497DCA1C240C042B28F6657ADFD8E097022FD@i2km11-ukbr.domain1.systemhost.ne
t>, wrote:
> > wondering: how much innovation occurs when the commercial
> > imperative is removed?
>
> Quite a lot. There are many open source type software projects
> that are a long way ahead of any commercial competitor - X Windows
> itself is probably the best example! Or the GNU emacs editor. Or gcc...
>
Or Python? Commercial competitors I see none...
The idea that the wheel is an open source component in a proprietary
market hasn't held the motor industry back too badly. Clever commercial
types recognise that, just as designing next years Merc is a commercial
imperative, so is *NOT* re-inventing the wheel.
Where would we be if the likes of, say, Bill Gates, Monsanto or Glaxo had
their hands on a patent for the wheel? Not driving around in a Mercedes,
that's for sure...
Regards,
PhilK
Tue, 07 Jan 2003 23:19 GMT @ Vaio
Email: phil@xfr.co.uk / Voicemail & Facsimile: 07092 070518
Tell me and I forget.
Show me and I remember.
Involve me and I understand.
- Chinese saying
From hall@ouhep1.nhn.ou.edu Tue Jan 7 18:46:25 2003
From: hall@ouhep1.nhn.ou.edu (Isaac Hall)
Date: Tue Jan 7 18:46:25 2003
Subject: [Tutor] Tk Listbox scrollbars
In-Reply-To: <000e01c2b670$b9777000$2502a8c0@emily.ewndsr01.nj.comcast.net>
Message-ID:
Hi Andy,
You are in luck. I had to write this exact thing not long ago, so I will
just copy for you the code that I have written to do this. It is in the
form of a class, but I you can take the important things out of it.
I use grid here, but pack can be used in the same way.
I should note that when I used pack, the thing looked a little different,
but not by much. The only difference here in calling this instead of a
listbox is that the box is class.box
from Tkinter import *
class ScrolledListbox(Frame):
def __init__(self,parent):
Frame.__init__(self,parent)
self.yScroll=Scrollbar(self,orient=VERTICAL)
self.xScroll=Scrollbar(self, orient=HORIZONTAL)
self.box=Listbox(self,xscrollcommand=self.xScroll.set,
yscrollcommand=self.yScroll.set,bg='white')
self.box.grid(row=0,column=0,sticky=N+S+E+W)
self.xScroll.grid(row=1,column=0,sticky=E+W)
self.yScroll.grid(row=0,column=1,sticky=N+S)
self.xScroll["command"]=self.box.xview
self.yScroll["command"]=self.box.yview
Ike
On Tue, 7 Jan 2003, andy surany wrote:
> Hello all,
>
> I wrote a program for a scrolled list containing a Y-axis scrollbar
> which has been working fine. At this point, my data is also overflowing
> the width of the box, so I have added an X-axis scrollbar.
>
> Both scrollbars appear, but the x-axis scrollbar is "vertical" (and
> tiny...and I press the up or down arrow to move left or right). What I
> want is a "slider" similar to the y scroll bar. I'm pretty sure that the
> error is in the way that I am packing the widget, as follows:
>
> sbar.pack(side=RIGHT, fill=Y) # This is for the Y-axis bar and it works
> correctly
> tbar.pack(side=BOTTOM) # This places the X-axis bar as described above
>
> TIA
>
> -Andy
>
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
--
From malik_martin@hotmail.com Tue Jan 7 18:48:33 2003
From: malik_martin@hotmail.com (malik martin)
Date: Tue Jan 7 18:48:33 2003
Subject: [Tutor] does anyone want to read chapter 5 with me?
Message-ID:
hi i'm having problems with chapter five in hopw to think like a computer program and i barely made it through chapter 4. i think its cause i suck at math. does anyone think that they can help me out. anyone on a windows machine have a program sharing client like netmeeting? or any other suggestions?. i currently use pythonwin.
The new MSN 8 is here: Try it free* for 2 months
From Adam Vardy Tue Jan 7 19:00:41 2003
From: Adam Vardy (Adam Vardy)
Date: Tue Jan 7 19:00:41 2003
Subject: [Tutor] Debug
In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0974DA7F@i2km11-ukbr.domain1.systemhost.net>
References: <7497DCA1C240C042B28F6657ADFD8E0974DA7F@i2km11-ukbr.domain1.systemhost.net>
Message-ID: <10085524698.20030107140532@roadrunner.nf.net>
Tuesday, January 7, 2003, 7:14:51 AM, you wrote:
>> >> I didn't get that problem, I just set a break point, hit run then
>> >> used step over/step into to go through my code.
>> you hit Run, you probably got a prompt? How did you answer it? And
>> what happened after that?
>> OK, Here's what I'm doing step by step:
Thanks Alan!
>> Open Python win
File->>Open select debug.py
Don't have a 'debug.py' file. But I tried another.
>> Select a line in my code and hit F9 - Toggle Breakpoint
>> *Hit the "Sprinting man" icon in toolbar
>> *Hit OK in dialog box
Ok. Only that's the prompt I was referring to, I think. Which has 3
fields, and Browse Ok, and Cancel. How are your fields set?
Select View_>>Toolbars->debugging
>> In the debug toolbar hit GO (black arrow)
>> Code runs to breakpoint
Actually, mine went again to the same part:
else:
# Can't find the source file - linecache may have it?
import linecache
line = linecache.getline(filename, lineno)
print "%s(%d): %s" % (os.path.basename(filename), lineno, string.expandtabs(line[:-1],4))
return 0
def _doexec(cmd, globals, locals):
exec cmd in globals, locals
--
Adam Vardy
From ramrom@earthling.net Tue Jan 7 19:16:14 2003
From: ramrom@earthling.net (Bob Gailer)
Date: Tue Jan 7 19:16:14 2003
Subject: [Tutor] Debug
In-Reply-To: <5.2.0.9.0.20030106131240.019fa8e8@66.28.54.253>
References: <1304053478.20030106152740@roadrunner.nf.net>
<7497DCA1C240C042B28F6657ADFD8E097022E9@i2km11-ukbr.domain1.systemhost.net>
<7497DCA1C240C042B28F6657ADFD8E097022E9@i2km11-ukbr.domain1.systemhost.net>
Message-ID: <5.2.0.9.0.20030107170422.028e3978@66.28.54.253>
--=======14476836=======
Content-Type: text/plain; x-avg-checked=avg-ok-6F772678; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit
Mark Hammond says the PythonWin debug problem is fixed in the newest version.
Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=======14476836=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-6F772678
Content-Disposition: inline
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002
--=======14476836=======--
From dyoo@hkn.eecs.berkeley.edu Tue Jan 7 19:34:01 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jan 7 19:34:01 2003
Subject: [Tutor] does anyone want to read chapter 5 with me?
In-Reply-To:
Message-ID:
On Tue, 7 Jan 2003, malik martin wrote:
> hi i'm having problems with chapter five in hopw to think like a
> computer program and i barely made it through chapter 4.
Hi Malik,
Don't worry about it. One thing that I've noticed is that, for an author
that knows a subject too well, communicating ideas can be a hard thing...
*grin*
I know that a few of us here on Tutor are working on the same examples
from HOPW, so you have a sympathetic audience.
Can you point out a particular example from Chapter Four or Five that
you'd like to talk about? We can all pitch in to tease it, pull it, and
pick it apart here on the Tutor mailing list.
Best of wishes to you!
From gp@pooryorick.com Tue Jan 7 19:39:05 2003
From: gp@pooryorick.com (Poor Yorick)
Date: Tue Jan 7 19:39:05 2003
Subject: [Tutor] unicode utf-16 and readlines [using the 'codecs' unicode file reading module]
References:
Message-ID: <3E1B7357.5050701@pooryorick.com>
Danny Yoo wrote:
>
>
>
>I have to admit I'm a bit confused; there shouldn't be any automatic
>handling of newlines when we use read(), since read() sucks all the text
>out of a file.
>
>Can you explain more what you mean by automatic newline handling? Do you
>mean a conversion of '\r\n' to '\n'?
>
>
>
As you mentioned, strip works correctly with the list items returned by
codec.readlines(), so my problem is entirely resolved. Yes, I meant
that codecs.readlines returns '\r\n' where a standard file object
returns just '\n':
>>> import codecs
>>> fh = codecs.open('0022data2.txt', 'r', 'utf-16')
>>> a = fh.readlines()
>>> a
[u'\u51fa\r\n']
>>> fh = open('test1.txt', 'r')
>>> a = fh.readlines()
>>> a
['hello\n', 'goodbye\n', 'where\n', 'how\n', 'when']
>>>
Perhaps you could tell me if this inconsistency poses any implications
for the Python programmer.
Poor Yorick
gp@pooryorick.com
From ramrom@earthling.net Tue Jan 7 19:50:03 2003
From: ramrom@earthling.net (Bob Gailer)
Date: Tue Jan 7 19:50:03 2003
Subject: [Tutor] OO approach to solving problem?
In-Reply-To:
Message-ID: <5.2.0.9.0.20030107171040.02aa3280@66.28.54.253>
--=======39424E94=======
Content-Type: text/plain; x-avg-checked=avg-ok-6F772678; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit
At 02:32 PM 1/7/2003 -0700, Brad Reisfeld wrote:
>As a simple example of what I am trying to do, imagine a collection of
>creatures that you would like to 'manage'. Each creature has a certain rate
>of growth, a certain probability of transforming into another creature at
>some point in time, and a given lifetime. You would like to keep an
>'inventory' of the creatures as a function of time.
>
>In terms of programming, it seems to me that one approach might be to have
>each creature as an instance of a creature class with properties like type
>of creature, growth rate, lifetime, transformation probability, and age.
>These instances would be created by a 'master class' (a factory class?) that
>would 'create' each creature, update it as to its age, and transform it. At
>some point, the instance would 'alert' the master class that it is ready to
>die and the master class would delete it.
Whoa. Classes don't do things. Module statements run the show, and they in
turn can call functions, create instances of classes, and invoke instance
methods. Statements in functions and methods continue to run the show.
Potential solution outline:
class Creature:
def __init__(self, ctype, growth_rate, probability, lifetime):
self.ctype = ctype
self.growth_rate = growth_rate
self.probability = probability
self.lifetime = lifetime
self.age = 0
self.alive = 1
def grow(self):
self.age += 1
self.alive = self.lifetime > self.age
if self.alive:
# transform ??
return self.alive
if __name__ == '__main__':
collection = []
for creature_number in range(100000): # create the creature collection
# determine ctype, growth_rate, probability, lifetime for next creature
collection.append(Creature(ctype, growth_rate, probability, lifetime))
for timestep in range(1000000):
collection = [creature in collection for creature.grow()] # age each
creature and retain just those that still live
On a 1 Ghz Win2K 512 K Ram machine with collection size = 4 and 10*6 cycles
last loop required about 30 seconds. For about 100 creatures and 10*5
cycles about same time. YMMV.
Other approaches that might be faster would involve just some arrays of
data and no instance objects.
HTH
Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=======39424E94=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-6F772678
Content-Disposition: inline
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002
--=======39424E94=======--
From jeff@ccvcorp.com Tue Jan 7 20:30:09 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Tue Jan 7 20:30:09 2003
Subject: [Tutor] OO approach to solving problem?
References: <5.2.0.9.0.20030107171040.02aa3280@66.28.54.253>
Message-ID: <3E1B7EB1.1090705@ccvcorp.com>
Bob Gailer wrote:
> At 02:32 PM 1/7/2003 -0700, Brad Reisfeld wrote:
>
>> As a simple example of what I am trying to do, imagine a collection of
>> creatures that you would like to 'manage'. Each creature has a
>> certain rate
>> of growth, a certain probability of transforming into another
>> creature at
>> some point in time, and a given lifetime. You would like to keep an
>> 'inventory' of the creatures as a function of time.
>
>
> Potential solution outline:
Hrm, did you actually test your results? :)
> class Creature:
....
> def grow(self):
> self.age += 1
> self.alive = self.lifetime > self.age
> if self.alive:
> # transform ??
> return self.alive
....
> collection = [creature in collection for creature.grow()] # age
> each creature and retain just those that still live
Proper list comprehension syntax would be [creature.grow() for creature
in collection], rather than what you've got here. But this is the least
of the problems, because creature.grow(), as you've shown it, returns a
boolean value. So your first iteration of this list comprehension will
convert your list of creature instances into a list of integers (or
bools if using a sufficiently recent version of Python). The second
iteration would therefore result in a (series of) AttributeErrors, as
integers have no grow() method. (Which makes me wonder just how you got
your timing statistics....)
Something along these lines *could* be made to work by having
creature.grow() return self instead of self.alive, though, and the
general idea is pretty much correct. However, it would not be at all
out of line to have a class that manages the list of creatures -- a
CreatureCollection class. (Perhaps a Menagerie class?) The collection
class could then initialize all of the creatures, guide each through
it's grow() step, cull the dead ones, track statistics, etc.
Jeff Shannon
Technician/Programmer
Credit International
From dyoo@hkn.eecs.berkeley.edu Tue Jan 7 20:49:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jan 7 20:49:02 2003
Subject: [Tutor] Composing codecs using codecs.EncodedFile / UTF-16 DOS format
converted to Unix ASCII
In-Reply-To: <3E1B7357.5050701@pooryorick.com>
Message-ID:
On Tue, 7 Jan 2003, Poor Yorick wrote:
> >I have to admit I'm a bit confused; there shouldn't be any automatic
> >handling of newlines when we use read(), since read() sucks all the
> >text out of a file.
> >
> >Can you explain more what you mean by automatic newline handling? Do
> >you mean a conversion of '\r\n' to '\n'?
> >
> >
> >
> As you mentioned, strip works correctly with the list items returned by
> codec.readlines(), so my problem is entirely resolved. Yes, I meant
> that codecs.readlines returns '\r\n' where a standard file object
> returns just '\n':
Ah, I see what you mean now. No, as far as I understand, Python doesn't
do this automatic conversion of newlines. However, Python 2.3's
"Universal Newline" support is probably what you're looking for.
Till then, it's still possible to tie in a "\r\n" --> "\n" sort of scheme,
using the mechanism of 'codecs'. It's not documented too well, but Python
does support a scheme similar to the nested Readers that Java uses.
Here is a module I cooked up called 'u_newlines.py' that provides such a
codec for newline conversions:
###
"""A small demonstration of codec-writing. Transparently converts
"\r\n" into "\n"
Danny Yoo (dyoo@hkn.eecs.berkeley.edu)
"""
import codecs
class Codec(codecs.Codec):
def encode(self, input, errors="strict"):
return input.replace("\r\n", "\n"), len(input)
def decode(self, input, errors="strict"):
return input.replace("\r\n", "\n"), len(input)
class StreamWriter(Codec, codecs.StreamWriter): pass
class StreamReader(Codec, codecs.StreamWriter): pass
def getregentry():
return (Codec().encode,Codec().decode,StreamReader,StreamWriter)
codecs.register(getregentry)
###
Let's see this in action. Let's say that we had a sample file in UTF-16
format:
###
>>> sample_file = open("foo.txt", 'w')
>>> sample_file.write("hello world\r\nThis is a test\r\n".encode("utf-16"))
>>> sample_file.close()
>>> open("foo.txt").read()
'\xff\xfeh\x00e\x00l\x00l\x00o\x00
\x00w\x00o\x00r\x00l\x00d\x00\r\x00\n\x00T\x00h\x00i\x00s\x00
\x00i\x00s\x00 \x00a\x00 \x00t\x00e\x00s\x00t\x00\r\x00\n\x00'
###
'foo.txt' now contains two lines of UTF-16 encoded text.
Notice that a normal read() on this file isn't working too well now, since
Python doesn't know that it's reading from a UTF-16 source. However, we
can fix this by introducing a codecs.EncodedFile() wrapper around the
object:
###
>>> import codecs
>>> import u_newlines
>>> f = codecs.EncodedFile(open("foo.txt"), 'ascii', 'utf-16')
>>> f.read()
'hello world\r\nThis is a test\r\n'
###
This EncodedFile wraps around our original file, and converts our
ASCII'ish file using a UTF-16 converter.
Here's the kicker: these EncodedFiles can be "composed": we can combine
the effects of several codecs, including that of u_newlines.py above, by
doing a double wrapping of our input file!
###
>>> f = codecs.EncodedFile(open("foo.txt"), 'ascii', 'utf-16')
>>> f2 = codecs.EncodedFile(f, 'u_newlines')
>>> f2.read()
'hello world\nThis is a test\n'
###
Muhahaha. *grin*
I hope this helps!
From dyoo@hkn.eecs.berkeley.edu Tue Jan 7 20:57:04 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Tue Jan 7 20:57:04 2003
Subject: [Tutor] Re: Composing codecs using codecs.EncodedFile / UTF-16 DOS format
converted to Unix ASCII
In-Reply-To:
Message-ID:
> ###
> """A small demonstration of codec-writing. Transparently converts
> "\r\n" into "\n"
>
> Danny Yoo (dyoo@hkn.eecs.berkeley.edu)
> """
>
> import codecs
>
> class Codec(codecs.Codec):
> def encode(self, input, errors="strict"):
> return input.replace("\r\n", "\n"), len(input)
>
> def decode(self, input, errors="strict"):
> return input.replace("\r\n", "\n"), len(input)
>
> class StreamWriter(Codec, codecs.StreamWriter): pass
> class StreamReader(Codec, codecs.StreamWriter): pass
>
> def getregentry():
> return (Codec().encode,Codec().decode,StreamReader,StreamWriter)
>
> codecs.register(getregentry)
> ###
Small amendment: that last part of u_newlines.py is wrong; I should not
have touched codecs.register. Sorry about that! The corrected code,
along with a small test case, follows below:
###
"""A small demonstration of codec-writing. Transparently converts
"\r\n" into "\n"
Danny Yoo (dyoo@hkn.eecs.berkeley.edu)
"""
import codecs
class Codec(codecs.Codec):
def encode(self, input, errors="strict"):
return input.replace("\r\n", "\n"), len(input)
def decode(self, input, errors="strict"):
return input.replace("\r\n", "\n"), len(input)
class StreamWriter(Codec, codecs.StreamWriter): pass
class StreamReader(Codec, codecs.StreamWriter): pass
def getregentry():
return (Codec().encode,Codec().decode,StreamReader,StreamWriter)
def _test():
import StringIO
f = codecs.EncodedFile(StringIO.StringIO("Hello\r\nWorld\r\n"),
"u_newlines")
assert f.readlines() == ["Hello\n", "World\n"]
print "All done!"
if __name__ == '__main__':
_test()
###
Hope this helps!
From gp@pooryorick.com Tue Jan 7 21:22:34 2003
From: gp@pooryorick.com (Poor Yorick)
Date: Tue Jan 7 21:22:34 2003
Subject: [Tutor] Composing codecs using codecs.EncodedFile / UTF-16 DOS format converted to Unix ASCII
References:
Message-ID: <3E1B8B73.2040308@pooryorick.com>
Danny Yoo wrote:
>
>Ah, I see what you mean now. No, as far as I understand, Python doesn't
>do this automatic conversion of newlines. However, Python 2.3's
>"Universal Newline" support is probably what you're looking for.
>
Thanks for the sample code! It'll take me a while to digest....
But about newlines, I thought that '\n' was already a sort of universal
newline for Python. On windows platforms, both open.read and
open.readlines already transform '\r\n' into '\n' unless you use binary
mode. That's why I thought it was a discrepancy for codecs.open to
return '\r\n'.
Poor Yorick
gp@pooryorick.com
From gp@pooryorick.com Tue Jan 7 21:51:03 2003
From: gp@pooryorick.com (Poor Yorick)
Date: Tue Jan 7 21:51:03 2003
Subject: [Tutor] does anyone want to read chapter 5 with me?
References:
Message-ID: <3E1B78E9.2000703@pooryorick.com>
Danny Yoo wrote:
>
>On Tue, 7 Jan 2003, malik martin wrote:
>
>>hi i'm having problems with chapter five in hopw to think like a
>>computer program and i barely made it through chapter 4.
>>
>
Pardon me if this is painfully obvious, but what is HOPW?
Poor Yorick
gp@pooryorick.com
From ramrom@earthling.net Tue Jan 7 22:02:02 2003
From: ramrom@earthling.net (Bob Gailer)
Date: Tue Jan 7 22:02:02 2003
Subject: [Tutor] OO approach to solving problem?
In-Reply-To: <3E1B7EB1.1090705@ccvcorp.com>
References: <5.2.0.9.0.20030107171040.02aa3280@66.28.54.253>
Message-ID: <5.2.0.9.0.20030107195838.02a92e90@66.28.54.253>
--=======23CC37EB=======
Content-Type: text/plain; x-avg-checked=avg-ok-6F772678; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit
At 05:28 PM 1/7/2003 -0800, Jeff Shannon wrote:
Hrm, did you actually test your results? :)
>> collection = [creature in collection for creature.grow()] # age each
>> creature and retain just those that still live
oops: I meant collection = [creature for creature in collection if
creature.grow()]
I was testing separately, and forgot to bring the modified code back to the
e-mail. I did test the above.
Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=======23CC37EB=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-6F772678
Content-Disposition: inline
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.431 / Virus Database: 242 - Release Date: 12/17/2002
--=======23CC37EB=======--
From Don Arnold" <3E1B78E9.2000703@pooryorick.com>
Message-ID: <018001c2b6c2$141bebc0$2cd1b241@defaultcomp>
Whew! I was afraid I was the only one who didn't know what they were talking
about.
Don
----- Original Message -----
From: "Poor Yorick"
To: "Danny Yoo"
Cc: "malik martin" ;
Sent: Tuesday, January 07, 2003 7:03 PM
Subject: Re: [Tutor] does anyone want to read chapter 5 with me?
>
>
> Danny Yoo wrote:
>
> >
> >On Tue, 7 Jan 2003, malik martin wrote:
> >
> >>hi i'm having problems with chapter five in hopw to think like a
> >>computer program and i barely made it through chapter 4.
> >>
> >
> Pardon me if this is painfully obvious, but what is HOPW?
>
> Poor Yorick
> gp@pooryorick.com
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
From aicolburn@yahoo.com Tue Jan 7 22:50:03 2003
From: aicolburn@yahoo.com (Alan Colburn)
Date: Tue Jan 7 22:50:03 2003
Subject: [Tutor] wxPython newbie
Message-ID: <20030107225231.36662.qmail@web20503.mail.yahoo.com>
Having dabbled in Tkinter a bit last summer, I've now
started dabbling similarly in wxPython. For all the
newbies out there (like me) who wonder about wxPython
vs. Tkinter, from a beginner perspective, I'd tell you
not to be afraid of wxPython. I'm not finding it more
difficult to understand than Tkinter and, in fact,
wxPython has a logic to it that seems (to me) to be
more consistent--thus easier--as my learning moves
among different aspects of the module.
However, I find the documentation to be pretty skimpy.
Most people suggest looking at the wxPython tutorial,
and then working with the wxPython demo. Doing things
this way I've been able to make remarkably complex GUI
designs pretty quickly -- but I don't always
understand what I'm doing :-)
So, first, if anyone can point me toward
newbie-oriented resources to give me a more conceptual
understanding, e.g., line by line, about what's
happening in simply wxPython scripts, please do so!
Second, what's returned when a user presses the "Yes"
and "No" buttons in a dialog box whose parameters
include wxYES_NO? I'd like to include code (for a
dialog called d) that says:
if d.ShowModal()==??what goes here??:
##do something after pressing YES
Second, I get the impression there's a special dialog
called wxValidate? wxValidator? for the traditional
"Are you sure you want to do this?" type of message. I
wasn't able to find documentation on this. Any help?
As always, thank you all for your help! -- Al C.
__________________________________________________
Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now.
http://mailplus.yahoo.com
From syrinx@simplecom.net Wed Jan 8 01:14:02 2003
From: syrinx@simplecom.net (Scott)
Date: Wed Jan 8 01:14:02 2003
Subject: [Tutor] pdb
Message-ID: <20030108000851.71ecd5a7.syrinx@simplecom.net>
Does pdb really work? Everytime I try to use it, every command gets
'EOF.' What could I be doing wrong?
From johnca@ourpla.net Wed Jan 8 02:04:01 2003
From: johnca@ourpla.net (John Abbe)
Date: Wed Jan 8 02:04:01 2003
Subject: [Tutor] A little security
Message-ID:
Aksed before, but no answer, so:
I'm working on a Python CGI using passwords, which for now i've
implemented in a field that gets sent with the GET method. This is
obviously insecure. I'm guessing that https might be the simplest way
to add security, but am very open to any suggestions.
If it is to be https, i'd love to hear about any simpler ways to use
it than the stuff pointed at by this news thread:
http://groups.google.com/groups?frame=left&th=3ad2d5de60bb5f05
Life,
John
p.s. Thanks all for the answers to my 1.5.2 vs. 2.x question -- guess
i'll work to retain compatibility for now at least
--
All you /\/\ John Abbe "If you don't like the news,
need \ / CatHerder go out and make some of your own."
is... \/ http://ourpla.net/john/ --Wes Nisker
From =?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= Wed Jan 8 04:59:01 2003
From: =?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?= (=?ISO-8859-1?B?YW50b25tdWhpbiDt4CByYW1ibGVyLnJ1?=)
Date: Wed Jan 8 04:59:01 2003
Subject: [Tutor] OO approach to solving problem?
In-Reply-To:
References:
Message-ID: <471237128.20030108125756@rambler.ru>
Hello Brad,
Wednesday, January 8, 2003, 12:32:15 AM, you wrote:
BR> Does the above approach sound reasonable?
Rather reasonable. However, see several notes below.
BR> If so, I think I know how to address most of the issues. However, I am
BR> unclear as to how the creature instances can communicate with the master
BR> class. How does the instance 'know' who created it and how to pass
BR> information back to it? I'm sure this must be a common design pattern, but
BR> being an old-time Fortran programmer, I haven't acquired much OO experience.
There are several approaches. One of most simple may be to have a
reference to the 'master' object. Something like:
class BeastMaster:
def isGoingToDie(self, creature):
print "Creature", creature, "is going to die!"
# Sure, you need something else here
class BasicCreature:
def __init__(self, master):
self.master = master
def onDie(self):
self.master.isGoingToDie(self)
class Moth(BasicCreature):
def someMethod(self):
# It's going to die...
self.onDie()
Actually there is kind of general pattern: Observer pattern (google
for it and you'll find a lot).
In some cases weak references may be more useful, though I don't think
it pertains to your problem as you described it.
Another thing that should be thought out is managing parallelism. As
you described your problem it seems that creatures should live their
life in parallel. There are several approaches to it. You may use
threads and alike stuff. However, there would appear a lot of problems
with locks, synchronization (though you may be much better in parallel
programming than me, and it'd be really easy for you :) ).
There is simpler approach that in CPython seems to be quicker too: you
may use generators to dispatch process quants to creatures. If you
need more info, please, write.
--
Best regards,
antonmuhin mailto:antonmuhin@rambler.ru
From fredm@smartypantsco.com Wed Jan 8 08:17:02 2003
From: fredm@smartypantsco.com (Alfred Milgrom)
Date: Wed Jan 8 08:17:02 2003
Subject: [Tutor] is this code dangerous?
Message-ID: <5.1.0.14.0.20030108235804.01eccdd0@mail.milgromphoto.com>
Hi:
Can someone please tell me the best way to override class methods for
specific instances?
I want to have a general class, such as Person, with general methods. Some
of the instances of the Person class may have different methods, and I want
to be able to override the base method (such as the speak method for the
cranky person in the example below).
Do I need to define a new class for each instance where there is a
different method? Is there overhead associated with having a large number
of classes?
Is the following code dangerous? (Obviously I could change the name of the
cranky class to crankyperson, or something like that, and have a different
class for each instance). What is the best way to handle this?
************************
class Person:
def __init__(self, name):
self.name = name
def speak(self):
print "%s says: my name is %s" % (self.name, self.name)
hobbit = Person('Bilbo Baggins')
class cranky(Person):
def speak(self):
print "%s says: I don't tell anyone my name" % (self.name)
cranky = cranky('someone else')
hobbit.speak()
cranky.speak()
************************
Thanks in advance,
Fred Milgrom
From mfarnham@acm.org Wed Jan 8 08:24:02 2003
From: mfarnham@acm.org (Michael Farnham)
Date: Wed Jan 8 08:24:02 2003
Subject: [Tutor] does anyone want to read chapter 5 with me?
In-Reply-To: <3E1B78E9.2000703@pooryorick.com>
References: <3E1B78E9.2000703@pooryorick.com>
Message-ID: <104203287302@ispsnet.net>
On Tuesday 07 January 2003 07:03 pm, you wrote:
> Danny Yoo wrote:
> >On Tue, 7 Jan 2003, malik martin wrote:
> >>hi i'm having problems with chapter five in hopw to think like a
> >>computer program and i barely made it through chapter 4.
>
> Pardon me if this is painfully obvious, but what is HOPW?
>
> Poor Yorick
> gp@pooryorick.com
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
It looks like a typo to me. I think it should be how.
HTH
Mike
--
You've got to be honest; if you can fake that, you've got it made.
-- George Burns
From op73418@mail.telepac.pt Wed Jan 8 10:58:01 2003
From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Wed Jan 8 10:58:01 2003
Subject: [Tutor] is this code dangerous?
References: <5.1.0.14.0.20030108235804.01eccdd0@mail.milgromphoto.com>
Message-ID: <003f01c2b72f$4eed84d0$97190dd5@violante>
----- Original Message -----
From: "Alfred Milgrom"
To:
Sent: Wednesday, January 08, 2003 1:14 PM
Subject: [Tutor] is this code dangerous?
> Hi:
>
> Can someone please tell me the best way to override class methods for
> specific instances?
>
> I want to have a general class, such as Person, with general methods. Some
> of the instances of the Person class may have different methods, and I
want
> to be able to override the base method (such as the speak method for the
> cranky person in the example below).
>
> Do I need to define a new class for each instance where there is a
> different method? Is there overhead associated with having a large number
> of classes?
>
Using the example you give below you can also do:
>>> class Person:
... def __init__(self, name):
... self.name = name
... def speak(self):
... print "%s says: my name is %s" % (self.name, self.name)
...
>>> Person
>>> cranky = Person('someone else')
>>> def crankyspeak(self):
... print "%s says: I don't tell anyone my name" % (self.name)
...
>>> cranky.speak = crankyspeak
But you have to notice though that speak is not a method but a plain
function object: self is not automatically passed, e.g.
>>> cranky.speak()
Traceback (most recent call last):
File "", line 1, in ?
TypeError: crankyspeak() takes exactly 1 argument (0 given)
>>> cranky.speak(cranky)
someone else says: I don't tell anyone my name
There are ways of course to override this - e.g. using something like the
template pattern. You could code something like
class Person:
def speak(self):
__speak = self.et('my_speak')
if __speak is not None:
__speak(self)
else:
print "%s says: my name is %s" % (self.name, self.name)
This allows the user to just add a my_speak method to the instance and the
speak method just looks for it first.
I am sure there are other (and better) ways to do this, but it's an initial
step. And do not worry about overhead unless you really have to e.g. your
analysis has proved that you do need to worry - your program is not fast
enough to meet the requirements - and that this place in the program is one
of the bottlenecks.
> Is the following code dangerous? (Obviously I could change the name of the
> cranky class to crankyperson, or something like that, and have a different
> class for each instance). What is the best way to handle this?
>
What do you mean by dangerous?
> ************************
>
> class Person:
> def __init__(self, name):
> self.name = name
>
> def speak(self):
> print "%s says: my name is %s" % (self.name, self.name)
>
> hobbit = Person('Bilbo Baggins')
>
> class cranky(Person):
> def speak(self):
> print "%s says: I don't tell anyone my name" % (self.name)
>
> cranky = cranky('someone else')
>
> hobbit.speak()
> cranky.speak()
>
> ************************
>
> Thanks in advance,
> Fred Milgrom
>
With my best regards,
G. Rodrigues
From aztech1200@yahoo.com Wed Jan 8 11:23:59 2003
From: aztech1200@yahoo.com (Aztech Guy)
Date: Wed Jan 8 11:23:59 2003
Subject: [Tutor] is this code dangerous?
In-Reply-To: <5.1.0.14.0.20030108235804.01eccdd0@mail.milgromphoto.com>
Message-ID: <20030108162236.78572.qmail@web9806.mail.yahoo.com>
Hi,
[I'm fairly new to Python myself too, so take what I
say with a grain of salt and test it out.]
Answers inline in your message.
Az.
--- Alfred Milgrom wrote:
> Hi:
>
> Can someone please tell me the best way to override
> class methods for
> specific instances?
First, based on your code below, I think you may
actually mean 'instane method' instead of class
method. (Sorry if I'm wrong about that). [Not sure if
class methods are allowed in Python or not - not got
that far in the tut/docs
yet :-)] Class methods are different from instance
methods. They're allowed in C++ and Java. A class
method is a method that is not associated with a
specific instance of that class; its declaration /
definition syntax is different than for instance
methods. Also, a class method can be called - and
typically is called - without having to instantiate
even one instance of the class, whereas an instance
method can only be called when you *have* an instance,
using the syntax : inst.meth(args)
- whereas a class method is called by syntax
something like : class_name.meth(args) (don't remember
now, but I think it's class_name::meth(args) in C++.
So, assuming you mean 'instance method' :
Not sure if it can be done in Python. I do know that
it is not possible in C++ and Java but is possible in
Ruby. Maybe newer versions of Python allow it. Check
the docs - or wait for a reply from someone else :-)
>
> I want to have a general class, such as Person, with
> general methods. Some
> of the instances of the Person class may have
> different methods, and I want
> to be able to override the base method (such as the
> speak method for the
> cranky person in the example below).
>
> Do I need to define a new class for each instance
> where there is a
> different method?
See my answers above for whether it is possible in the
first place. If it is possible, then the answer to
question just above is yes, since, if you don't do it,
all instances will have the exact same methods.
Is there overhead associated with
> having a large number
> of classes?
Depends on what kind of overhead you mean.
You'll surely have more source code overhead - as in
quantity of code - when you have more classes.
Also, if you have more code, it will take longer to
load, and occupy more space in memory while the code
is running - I would think both of these would be,
roughly, directly proportional to the amount of code.
This may or may not be a concern to you, depending on
your hardware configuration - CPU, RAM, etc.
>
> Is the following code dangerous? (Obviously I could
> change the name of the
> cranky class to crankyperson, or something like
> that, and have a different
> class for each instance). What is the best way to
> handle this?
No, your code below is not 'dangerous'. What makes you
think it might be ? Actually, for the need you've
described, its the right code - if you plan to have
categories - i.e. classes - of people, such as normal
people (class Person) and cranky people (class
cranky). If you can categorize your people instances
that you need to create into a fairly small number of
such classes, then you can create a separate class for
each, each differing somewhat in the methods that they
have. (You can in fact have different methods in each
class, not just different implementations of the same
method). However, if your code is going to have a
really large number of individual people instances,
and you want different behaviour for each of them,
then it's going to be a problem for you - you'll have
to type out the code for the different methods that
each one has. Then this becomes something like you're
attacking the problem with a wrong approach. You might
then want to reconsider your design - one possible way
could be to analyse your app, and try to identify a
smaller number of categories of people, define classes
for each (e.g. Normal, Cranky, Deaf-Mute, Anti-Social,
etc.) and then parameterize the constructors so as to
be able to pass different values for some argument,
and within the speak method, use the different values
to generate different behaviour, using a nested
if/elif/..../else statement.
HTH
Az
>
> ************************
>
> class Person:
> def __init__(self, name):
> self.name = name
>
> def speak(self):
> print "%s says: my name is %s" %
> (self.name, self.name)
>
> hobbit = Person('Bilbo Baggins')
>
> class cranky(Person):
> def speak(self):
> print "%s says: I don't tell anyone my
> name" % (self.name)
>
> cranky = cranky('someone else')
>
> hobbit.speak()
> cranky.speak()
>
> ************************
>
> Thanks in advance,
> Fred Milgrom
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
__________________________________________________
Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now.
http://mailplus.yahoo.com
From alan.gauld@bt.com Wed Jan 8 11:39:07 2003
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed Jan 8 11:39:07 2003
Subject: [Tutor] does anyone want to read chapter 5 with me?
Message-ID: <7497DCA1C240C042B28F6657ADFD8E0970230C@i2km11-ukbr.domain1.systemhost.net>
> Whew! I was afraid I was the only one who didn't know what
> they were talking about.
> > >>hi i'm having problems with chapter five in hopw to think like a
> > >>computer program and i barely made it through chapter 4.
> > Pardon me if this is painfully obvious, but what is HOPW?
I believe its just a typo for "How" and the full title should
be "How to think like a computer programmer"
Alan g
From alan.gauld@bt.com Wed Jan 8 11:43:01 2003
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed Jan 8 11:43:01 2003
Subject: [Tutor] wxPython newbie
Message-ID: <7497DCA1C240C042B28F6657ADFD8E0970230D@i2km11-ukbr.domain1.systemhost.net>
> Second, what's returned when a user presses the "Yes"
> and "No" buttons in a dialog box whose parameters
> include wxYES_NO?
When in doubt print it out is my motto.
Why not just add a couple of lines:
res = d.ShowModal()
print res
See what gets printed and substitute in your program...
Alan G.
From alan.gauld@bt.com Wed Jan 8 11:46:06 2003
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed Jan 8 11:46:06 2003
Subject: [Tutor] pdb
Message-ID: <7497DCA1C240C042B28F6657ADFD8E0970230E@i2km11-ukbr.domain1.systemhost.net>
> Does pdb really work? Everytime I try to use it, every command gets
> 'EOF.' What could I be doing wrong?
Yes it works fine. If you know gdb it shouldn't cause any problems.
How are you using it?
Do you get as far as the pdb prompt?
If you type help do you get the list of commands OK?
Alan G.
From marta_andrea@libero.it Wed Jan 8 11:48:02 2003
From: marta_andrea@libero.it (Andrea Valle)
Date: Wed Jan 8 11:48:02 2003
Subject: R: [Tutor] wxPython newbie
In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0970230D@i2km11-ukbr.domain1.systemhost.net>
Message-ID:
Is there a real tutorial on wxpython (or on Tkinter)?
I started learning Pythin thanks to its marvellous tutorial by Guido.
But GUI semms to have not a resource like that.
thanks!
-a-
From alan.gauld@bt.com Wed Jan 8 12:04:22 2003
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Wed Jan 8 12:04:22 2003
Subject: [Tutor] is this code dangerous?
Message-ID: <7497DCA1C240C042B28F6657ADFD8E0970230F@i2km11-ukbr.domain1.systemhost.net>
> Can someone please tell me the best way to override class methods for
> specific instances?
You did it right in the example you gave.
> Do I need to define a new class for each instance where there is a
> different method?
You should really, the definition of a class is its interface so if
you change the interface you change the class! However Pythons
implementation of OO is so open and flexible I'm sure there is a
way to modify a method in place - there certainly is to add a
new method... I just don't think its a good idea!
> Is there overhead associated with having a
> large number of classes?
Of course - more names in the dict for a start, but not nearly as
much as in having lots of instances!
> (Obviously I could change the name of the cranky class to
> crankyperson, or something like that...
Why on earth would you want to do that? Its not necessary to
include the parent classes name when subclassing.
> have a different class for each instance).
Thats the usual way. Diffeent behaviour is different class.
BUT there is a style of programming that is designed to
limit the damage. Its called mixin programming and is
common in Lisp. The idea is you capture common groups
of behaviour as abstract classes. Then you create the
concrete classes by mutiply inheriting the mixins
you need, something like this:
class mute:
def speak(msg): pass
class shouter:
def speak(msg):
print msg.uppercase()
class old:
def age(): print "Mind your ow business!"
class young:
def age(): print "I'm ",self.age
Now we can define some persons:
class Person:
def __init__(self,age): self.age = age
def speak(msg): print msg
def age(): pass
class MutePerson(Person, mute): pass
class LoudPerson(Person, Shouter): pass
class Oldster(Person, Old): pass
class Youngster(Person, Young) pass
class OldandLoud(Person, Old, Shouter):pass
And so on, if you categorize the behaviour right, the vast
majority of classes have little or no code in them but
just mixin the behaviour needed.
You do have to be careful about things like the order
of searching for methods, especially if multiple mixins
implement the same metgod - say old had also
implemented speak()...
But it can be a useul way of reducing the complexity
of your classes.
Alan g.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld/
From dyoo@hkn.eecs.berkeley.edu Wed Jan 8 13:30:02 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Jan 8 13:30:02 2003
Subject: [Tutor] does anyone want to read chapter 5 with me?
In-Reply-To: <018001c2b6c2$141bebc0$2cd1b241@defaultcomp>
Message-ID:
On Tue, 7 Jan 2003, Don Arnold wrote:
> Whew! I was afraid I was the only one who didn't know what they were
> talking about.
> > Pardon me if this is painfully obvious, but what is HOPW?
My brain flubbed. I can't explain what HOPW means either.
I've been trying to figure out what I was thinking as I typed that.
Tracing back, I think I was mixing between "How to Think Like a Computer
Scientist":
http://www.ibiblio.org/obp/thinkCSpy/
and the Scheme textbook "How to Design Programs".
http://www.htdp.org/
Somehow, I think the "HOw to" part got stuck in my head, and got condensed
to the prefix "HO". "PW" might be a simple transposing of "Writing
Programs"... but this only a guess as what kind of long-range logic bug
was in my brain when I typed that acronym out.
In summary: I screwed up. *grin* That'll teach me to use acronyms
inapproriately. My apologies for the mixup!
From dyoo@hkn.eecs.berkeley.edu Wed Jan 8 14:14:03 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed Jan 8 14:14:03 2003
Subject: [Tutor] Composing codecs using codecs.EncodedFile / UTF-16 DOS
format converted to Unix ASCII
In-Reply-To: <3E1B8B73.2040308@pooryorick.com>
Message-ID:
On Tue, 7 Jan 2003, Poor Yorick wrote:
> >Ah, I see what you mean now. No, as far as I understand, Python
> >doesn't do this automatic conversion of newlines. However, Python
> >2.3's "Universal Newline" support is probably what you're looking for.
> >
>
> Thanks for the sample code! It'll take me a while to digest....
>
> But about newlines, I thought that '\n' was already a sort of universal
> newline for Python. On windows platforms, both open.read and
> open.readlines already transform '\r\n' into '\n' unless you use binary
> mode. That's why I thought it was a discrepancy for codecs.open to
> return '\r\n'.
Ah! I completely forgot about that!
You're right: there's an platform-dependent automatic conversion of the
line-endings.
http://www.wdvl.com/Authoring/Languages/Python/Quick/python4_2.html
if we open a file in "text" mode, which is what we've been doing in the
past examples.
However, this "\r\n"->"\n" conversion won't take its expected effect
against UTF-16-encoded files because the character sequence isn't '\r\n'
in the file, but rather, the four byte sequence: '\x00\r\x00\n'.
That is, there's padding involved because each character now consists of
two bytes each! So even when we open the file in text mode, Python file
operations don't catch and do platform-dependent conversions here.
Even the Universal Newlines support of Python 2.3 won't help us here,
since by the time we read those four bytes, normalization will pass by
without touching those strings. Or even worse, may even convert what
looks like a lone "\r" into another newline since it looks like a
Macintosh newline. So we may really need to open UTF-16 files in binary
mode after all to be careful.
Hmmm... perhaps this is a bug! Perhaps the utf-16 decoder should really
do the '\r\n' normalization if it's running on a Windows platform. I
haven't been able to Google other pages talking about this issue, so I
have no idea what other people think about it. Maybe you might want to
bring it up on the i18n-sig?
http://www.python.org/sigs/i18n-sig/
It would be an interesting thing to talk about. I'm sorry I can't give a
definitive answer on this one; I really don't know what the "right" thing
to do is in this case.
Good luck to you!
From syrinx@simplecom.net Wed Jan 8 14:27:01 2003
From: syrinx@simplecom.net (Scott)
Date: Wed Jan 8 14:27:01 2003
Subject: [Tutor] pdb
In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0970230E@i2km11-ukbr.domain1.systemhost.net>
References: <7497DCA1C240C042B28F6657ADFD8E0970230E@i2km11-ukbr.domain1.systemhost.net>
Message-ID: <20030108132202.0c290bcf.syrinx@simplecom.net>
Strange. It's working now. I have no idea what I'm doing differently,
but it's working. I hate when that happens. :(
From magnus@thinkware.se Wed Jan 8 15:48:02 2003
From: magnus@thinkware.se (Magnus Lycka)
Date: Wed Jan 8 15:48:02 2003
Subject: [Tutor] 'if a==b or a==c or a==d' alternative (was:
pausing a nd layout)
In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0974DA82@i2km11-ukbr.domain1
.systemhost.net>
Message-ID: <5.1.0.14.0.20030108214746.02bf8268@www.thinkware.se>
At 17:37 2003-01-07 +0000, alan.gauld@bt.com wrote:
> > > if p in 'Qq ':
> > > sys.exit()
> >
> > I've just looked thru the new stuff on Python 2.3, and it
> > seems that it will support larger subsplices, so that
> >
> > if 'ab' in 'abcdefg':
> > print 'found'
> >
> > will actually print 'found'. Which means that the above
> > example would do a sys.exit() if the user types 'Qq'.
>
>Which is probably better than raising an exception which
>is what it would do now... I guess the solution will be
>to put [0] after the test variable if you really only
>want to test 1 char.
>
>if 'ab'[0] in 'abcdefg':...
>
>But that's not so pretty.
Another option is:
"if len(p) == 1 and p in "Qq ":"
or
"if q in list('Qq '):"
But in the case at hand, it seems likely that we know
that q is one character long, for instance if it's the
result of a key press. On the other hand, I fear that
not even all key-presses are one character long...
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se
From magnus@thinkware.se Wed Jan 8 16:03:01 2003
From: magnus@thinkware.se (Magnus Lycka)
Date: Wed Jan 8 16:03:01 2003
Subject: [Tutor] wxPython newbie
In-Reply-To: <7497DCA1C240C042B28F6657ADFD8E0970230D@i2km11-ukbr.domain1
.systemhost.net>
Message-ID: <5.1.0.14.0.20030108220115.02c0ab18@www.thinkware.se>
At 16:41 2003-01-08 +0000, alan.gauld@bt.com wrote:
>When in doubt print it out is my motto.
And my motto is "When in doubt, learn the right way
to do it!" ;)
>Why not just add a couple of lines:
>
> res = d.ShowModal()
> print res
Because it will just be a stupid digit that doesn't
mean anything to whoever reads the code. Magic numbers
in the code is a no-no in my book. Who can be certain
that these constants will remain the same in the next
version of wxPython? (If I was wxWindows maintainer I
might just shuffle them around on purpose between
versions just to break such badly written code! ;)
>See what gets printed and substitute in your program...
Better to use wxID_YES, wxID_NO, wxID_OK or wxID_CANCEL.
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se
From magnus@thinkware.se Wed Jan 8 16:04:02 2003
From: magnus@thinkware.se (Magnus Lycka)
Date: Wed Jan 8 16:04:02 2003
Subject: [Tutor] wxPython newbie
In-Reply-To: <20030107225231.36662.qmail@web20503.mail.yahoo.com>
Message-ID: <5.1.0.14.0.20030108220658.02bfe128@www.thinkware.se>
At 14:52 2003-01-07 -0800, Alan Colburn wrote:
>So, first, if anyone can point me toward
>newbie-oriented resources to give me a more conceptual
>understanding, e.g., line by line, about what's
>happening in simply wxPython scripts, please do so!
Have you looked at the Wiki? Do you subscribe to the
wxpython mailinglist?
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se
From magnus@thinkware.se Wed Jan 8 16:11:24 2003
From: magnus@thinkware.se (Magnus Lycka)
Date: Wed Jan 8 16:11:24 2003
Subject: [Tutor] does anyone want to read chapter 5 with me?
In-Reply-To: <018001c2b6c2$141bebc0$2cd1b241@defaultcomp>
References:
<3E1B78E9.2000703@pooryorick.com>
Message-ID: <5.1.0.14.0.20030108221059.02bfdfe0@www.thinkware.se>
At 21:00 2003-01-07 -0600, Don Arnold wrote:
>Whew! I was afraid I was the only one who didn't know what they were tal=
king
>about.
It's maybe not the best tutorial for those who
feel that their math skills are weak? On the
other hand, trying to improve your understanding
of maths is likely to make you a better programmer.
Maybe something like G. P=F3lya's "How to solve it"
might be helpful?
--=20
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se
From magnus@thinkware.se Wed Jan 8 16:18:04 2003
From: magnus@thinkware.se (Magnus Lycka)
Date: Wed Jan 8 16:18:04 2003
Subject: [Tutor] pdb
In-Reply-To: <20030108132202.0c290bcf.syrinx@simplecom.net>
References: <7497DCA1C240C042B28F6657ADFD8E0970230E@i2km11-ukbr.domain1.systemhost.net>
<7497DCA1C240C042B28F6657ADFD8E0970230E@i2km11-ukbr.domain1.systemhost.net>
Message-ID: <5.1.0.14.0.20030108222005.02c73eb8@www.thinkware.se>
At 13:22 2003-01-08 -0600, Scott wrote:
>Strange. It's working now. I have no idea what I'm doing differently,
>but it's working. I hate when that happens. :(
Really? Why not just be happy instead? Life is to
short to solve boring problems like "why didn't
this work yesterday". Happy debugging!
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se
From jeff@ccvcorp.com Wed Jan 8 16:45:03 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Wed Jan 8 16:45:03 2003
Subject: [Tutor] does anyone want to read chapter 5 with me?
References:
Message-ID: <3E1C9B76.8030505@ccvcorp.com>
Danny Yoo wrote:
>
>My brain flubbed. I can't explain what HOPW means either.
>
>
>I've been trying to figure out what I was thinking as I typed that.
>
I think you expanded on a typo made by the original poster. To quote a
segment of the inital message in this thread, "...chapter five in hopw
to think like a computer program ..." -- it looks like you somehow
conflated that typo with the name of the book, and went from there.
I find that it's not all that uncommon that I will read something and
the words will come up competely different in my brain -- I won't
provide any examples, though, as most of them are horribly impolite.
>cough< ;)
Jeff Shannon
Technician/Programmer
Credit International
From malik_martin@hotmail.com Wed Jan 8 17:40:24 2003
From: malik_martin@hotmail.com (malik martin)
Date: Wed Jan 8 17:40:24 2003
Subject: [Tutor] does anyone want to read chapter 5 with me?
Message-ID:
these replies came so late i wasnt sure i would get one i'll do some reading tonight and get back to you thanks alot guys
"Maybe something like G. Pólya's "How to solve it"
might be helpful? "
i'll have to check this out
>From: Danny Yoo
>To: Don Arnold
>CC: Poor Yorick , malik martin ,
>Subject: Re: [Tutor] does anyone want to read chapter 5 with me?
>Date: Wed, 8 Jan 2003 10:28:30 -0800 (PST)
>
>
>
>On Tue, 7 Jan 2003, Don Arnold wrote:
>
> > Whew! I was afraid I was the only one who didn't know what they were
> > talking about.
>
> > > Pardon me if this is painfully obvious, but what is HOPW?
>
>
>My brain flubbed. I can't explain what HOPW means either.
>
>
>I've been trying to figure out what I was thinking as I typed that.
>Tracing back, I think I was mixing between "How to Think Like a Computer
>Scientist":
>
> http://www.ibiblio.org/obp/thinkCSpy/
>
>and the Scheme textbook "How to Design Programs".
>
> http://www.htdp.org/
>
>Somehow, I think the "HOw to" part got stuck in my head, and got condensed
>to the prefix "HO". "PW" might be a simple transposing of "Writing
>Programs"... but this only a guess as what kind of long-range logic bug
>was in my brain when I typed that acronym out.
>
>
>
>In summary: I screwed up. *grin* That'll teach me to use acronyms
>inapproriately. My apologies for the mixup!
>
>
>_______________________________________________
>Tutor maillist - Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
get 2 months FREE*
From wolf_binary@hotmail.com Wed Jan 8 19:20:02 2003
From: wolf_binary@hotmail.com (Cameron Stoner)
Date: Wed Jan 8 19:20:02 2003
Subject: [Tutor] OOP class declaration question
Message-ID:
Hi all,
Recently I made a class that I found out wouldn't work properly unless all
the variables were filled with something. My question is why do you have to
have all the fields filled with something? Is it because you can't make an
object of something without knowing what each part is soposed to be? I
thought python could allow for variable declaration on the fly and you
didn't have to worry about what type of data it was sopposed to hold.
Thanks,
-Cameron
Here is the code:
class mobileSuit:
def __init__(self,lArm, rArm, head, lLeg, rLeg, back, maxHealth):
self.leftArmHealth = lArm
self.rightArmHealth = rArm
self.headHealth = head
self.leftLegHealth = lLeg
self.rightLegHealth = rLeg
self.backHealth = back
self.maxHealth = maxHealth
self.healthPercent
self.actualHealth
#request overall health
def overallHealth(self, report):
#determine actualHealth
self.actualHealth = (self.leftArmHealth + self.rightArmHealth +
self.headHealth + self.leftLegHealth + self.rightLegHealth +
self.backHealth) / 6
#find percent of health
self.healthPercent = (self.actualHealth / self.maxHealth) * 100
# report the status with a print else return the result
if report == 1:
print "The MS health is: ", self.healthPercent
else:
return self.healthPercent
testSuit = mobileSuit(6,6,6,6,6,6,6)
_________________________________________________________________
Help STOP SPAM: Try the new MSN 8 and get 2 months FREE*
http://join.msn.com/?page=features/junkmail
From drichardson@austincityclub.org Wed Jan 8 19:26:20 2003
From: drichardson@austincityclub.org (David Richardson)
Date: Wed Jan 8 19:26:20 2003
Subject: [Tutor] weird edit menu
Message-ID:
This is a multi-part message in MIME format.
------=_NextPart_000_0026_01C2B742.F07E0370
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
visited http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html
to start toying with IDLE (python GUI)
The edit menu to python 2.2.2 does not look like the images. In fact I
can't find run script anywhere! Did I screw up something during install?
David Richardson
512 301-4429
fax 512 301-4194
------=_NextPart_000_0026_01C2B742.F07E0370
Content-Type: application/ms-tnef;
name="winmail.dat"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="winmail.dat"
eJ8+Ii0AAQaQCAAEAAAAAAABAAEAAQeQBgAIAAAA5AQAAAAAAADoAAEIgAcAGAAAAElQTS5NaWNy
b3NvZnQgTWFpbC5Ob3RlADEIAQ2ABAACAAAAAgACAAEGgAMADgAAANMHAQAIABIAEAAAAAMACAEB
A5AGAJgFAAAiAAAACwACAAEAAAALACMAAAAAAAMAJgAAAAAACwApAAAAAAADADYAAAAAAB4AcAAB
AAAAEQAAAHdlaXJkIGVkaXQgbWVudSAAAAAAAgFxAAEAAAAWAAAAAcK3dFbA0WZGdBSBSHqaYlla
C/pOwAAAAgEdDAEAAAAkAAAAU01UUDpEUklDSEFSRFNPTkBBVVNUSU5DSVRZQ0xVQi5PUkcACwAB
DgAAAABAAAYOAKCtSXS3wgECAQoOAQAAABgAAAAAAAAA3MeoePkjvUeukSiaeHGUE8KAAAALAB8O
AQAAAAIBCRABAAAAlQEAAJEBAADdAQAATFpGdfYFJeMDAAoAcmNwZzEyNRYyAPgLYG4OEDAzM08B
9wKkA+MCAGNoCsBzsGV0MCAHEwKAfQqBknYIkHdrC4BkNAxgbmMAUAsDC7UgEiAAkHQJCYAgaAJA
cDovLxBoa24uCeBjcy6CYgSQa2VsZXkU8ABkdS9+ZHlvbyAvcHl0aAIgL2nqZBWgXwuAdANgFuAS
gOhleC4UUG0JUAqxCoCwdG8gcwGQACAgGKAyeQuAZyAD8BagIEkgRExFICgWhCBHGFVJKRhEGERU
aGWWIAmAFAAgB4BudRkhEiAaVTIuHUEgZG+ZB5FubwVACQBvax4gnmkVgBkgG9EHcGFnB5BsLiAZ
4AOgZgDQBUBJVCBjAHAnBUBmEnEgnHJ1A6AE9QBweXcb0PUJcCEfgEQW8CARBPEH0dx1cBjAA3AR
MGgZYhXwjwUQGXELgBjRbGw/GwrbCvMiQGESIBQwUg3gEPEuZCNAC5AYUzUOICAzgDAxLTQ0MjkY
RMkf0HggJ1cxORKgJUgLGEQR4QAqwAAAAAsAAYAIIAYAAAAAAMAAAAAAAABGAAAAAAOFAAAAAAAA
AwADgAggBgAAAAAAwAAAAAAAAEYAAAAAEIUAAAAAAAADAA+ACCAGAAAAAADAAAAAAAAARgAAAAAB
hQAAAAAAAAMAPYAIIAYAAAAAAMAAAAAAAABGAAAAAFKFAAA/cQEACwBKgAggBgAAAAAAwAAAAAAA
AEYAAAAADoUAAAAAAAADAEyACCAGAAAAAADAAAAAAAAARgAAAAARhQAAAAAAAAMATYAIIAYAAAAA
AMAAAAAAAABGAAAAABiFAAAAAAAAHgCAgAggBgAAAAAAwAAAAAAAAEYAAAAAVIUAAAEAAAAEAAAA
OS4wAAsAgYAIIAYAAAAAAMAAAAAAAABGAAAAAAaFAAAAAAAACwCcgAggBgAAAAAAwAAAAAAAAEYA
AAAAgoUAAAEAAAACAfgPAQAAABAAAADcx6h4+SO9R66RKJp4cZQTAgH6DwEAAAAQAAAA3MeoePkj
vUeukSiaeHGUEwIB+w8BAAAAlwAAAAAAAAA4obsQBeUQGqG7CAArKlbCAABQU1RQUlguRExMAAAA
AAAAAABOSVRB+b+4AQCqADfZbgAAAEM6XERvY3VtZW50cyBhbmQgU2V0dGluZ3NcT3duZXJcTG9j
YWwgU2V0dGluZ3NcQXBwbGljYXRpb24gRGF0YVxNaWNyb3NvZnRcT3V0bG9va1xvdXRsb29rLnBz
dAAAAwD+DwUAAAADAA00/TcAAAIBfwABAAAAPgAAADxMTkVIS09KQlBFRk5OQUFKR05EQU1FUElD
RkFBLmRyaWNoYXJkc29uQGF1c3RpbmNpdHljbHViLm9yZz4AAAADAAYQHUhdvQMABxD4AAAAAwAQ
EAAAAAADABEQAAAAAB4ACBABAAAAZQAAAFZJU0lURURIVFRQOi8vSEtORUVDU0JFUktFTEVZRURV
L0RZT08vUFlUSE9OL0lETEVJTlRSTy9JTkRFWEhUTUxUT1NUQVJUVE9ZSU5HV0lUSElETEUoUFlU
SE9OR1VJKVRIRUUAAAAAjkA=
------=_NextPart_000_0026_01C2B742.F07E0370--
From ramrom@earthling.net Wed Jan 8 20:51:02 2003
From: ramrom@earthling.net (Bob Gailer)
Date: Wed Jan 8 20:51:02 2003
Subject: [Tutor] OOP class declaration question
In-Reply-To:
Message-ID: <5.2.0.9.0.20030108184713.02a7e270@66.28.54.253>
--=======3DD346F=======
Content-Type: text/plain; x-avg-checked=avg-ok-2C5849C1; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit
At 06:15 PM 1/8/2003 -0600, Cameron Stoner wrote:
>class mobileSuit:
> def __init__(self,lArm, rArm, head, lLeg, rLeg, back, maxHealth):
> self.leftArmHealth = lArm
> self.rightArmHealth = rArm
> self.headHealth = head
> self.leftLegHealth = lLeg
> self.rightLegHealth = rLeg
> self.backHealth = back
> self.maxHealth = maxHealth
OK so far.
> self.healthPercent
> self.actualHealth
These two lines will give errors, as the properties don't yet exist.
Solution: either drop these two lines or change them into assignments.
self.healthPercent = None
self.actualHealth = None
Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=======3DD346F=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-2C5849C1
Content-Disposition: inline
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003
--=======3DD346F=======--
From carroll@tjc.com Wed Jan 8 22:51:01 2003
From: carroll@tjc.com (Terry Carroll)
Date: Wed Jan 8 22:51:01 2003
Subject: R: [Tutor] wxPython newbie
In-Reply-To:
Message-ID:
On Wed, 8 Jan 2003, Andrea Valle wrote:
> Is there a real tutorial on wxpython (or on Tkinter)?
A couple for Tkinter:
http://home.att.net/~stephen_ferg/thinking_in_tkinter/
http://www.pythonware.com/library/tkinter/introduction/index.htm
--
Terry Carroll |
Santa Clara, CA | "The parties are advised to chill."
carroll@tjc.com | - Mattel, Inc. v. MCA Records, Inc.,
Modell delendus est | no. 98-56577 (9th Cir. July 24, 2002)
From carroll@tjc.com Wed Jan 8 22:53:06 2003
From: carroll@tjc.com (Terry Carroll)
Date: Wed Jan 8 22:53:06 2003
Subject: R: [Tutor] wxPython newbie
In-Reply-To:
Message-ID:
On Wed, 8 Jan 2003, Andrea Valle wrote:
> Is there a real tutorial on wxpython (or on Tkinter)?
I've never looked into wxpython, but
http://www.wxpython.org/tutorial.php and
http://wiki.wxpython.org/
look promising.
--
Terry Carroll |
Santa Clara, CA | "The parties are advised to chill."
carroll@tjc.com | - Mattel, Inc. v. MCA Records, Inc.,
Modell delendus est | no. 98-56577 (9th Cir. July 24, 2002)
From fredm@smartypantsco.com Wed Jan 8 23:02:01 2003
From: fredm@smartypantsco.com (Alfred Milgrom)
Date: Wed Jan 8 23:02:01 2003
Subject: [Tutor] is this code dangerous?
In-Reply-To: <003f01c2b72f$4eed84d0$97190dd5@violante>
References: <5.1.0.14.0.20030108235804.01eccdd0@mail.milgromphoto.com>
Message-ID: <5.1.0.14.0.20030109142846.00aaa130@192.168.1.1>
Thanks to everyone who helped me out with this question.
>What do you mean by dangerous?
What I meant by 'dangerous' was that I had named the class 'cranky', and
then threw away the reference by naming the instance 'cranky' as well.
Anyway, I just wanted to share the solution that I think I will adopt:
**************************************************
class Person:
def __init__(self, name):
self.name = name
def speak(self, dummy):
print "%s says: my name is %s" % (self.name, self.name)
def crankyspeak(self):
print "%s says: I don't tell anyone my name" % (self.name)
hobbit = Person('Bilbo Baggins')
cranky = Person('someone else')
cranky.speak=Person.crankyspeak
hobbit.speak(hobbit)
cranky.speak(cranky)
**************************************************
The benefits from my point of view are:
* I don't have to create a large number of classes
* all the code for the methods are in the one place (Person class)
* I can easily mix and match the methods for any instance without the
difficulties that Alan mentioned
* the same code structure (albeit more unwieldy than usual) can be used for
every instance/method combination (ie no problems with unbound methods or
not passing self parameter)
Thanks again for your help,
Fred Milgrom
From lumbricus@gmx.net Wed Jan 8 23:26:01 2003
From: lumbricus@gmx.net (lumbricus@gmx.net)
Date: Wed Jan 8 23:26:01 2003
Subject: [Tutor] pyLpd
References: <92CB4AC7-2312-11D7-8E1C-000393DC397E@styrke.com>
Message-ID: <22005.1042086345@www32.gmx.net>
Hi!
> Yes, the array is two chars long, but considered as a string, it _is_
> empty (strlen() returns 0). A char s[1000] filled with '\0':s is still
>
> an empty string, although the array holding it is 1000 chars in size.
>
> What I was trying to hint at in my first message was that python,
> unlike C, has a real 8 bit clean string type. I guess I could have
> expressed myself clearer. And of course, when working with raw 8-bit
> data in C one would not handle the data arrays as strings, for exactly
>
> this reason.
ACK.
> /Emil
Greetings, J"o!
--
None
--
sigfault
+++ GMX - Mail, Messaging & more http://www.gmx.net +++
NEU: Mit GMX ins Internet. Rund um die Uhr für 1 ct/ Min. surfen!
From syrinx@simplecom.net Thu Jan 9 01:48:24 2003
From: syrinx@simplecom.net (Scott)
Date: Thu Jan 9 01:48:24 2003
Subject: [Tutor] Kill A Fuction Call?
Message-ID: <20030109004334.504ca019.syrinx@simplecom.net>
Is it possible to call a function, and kill it if it doesn't complete in
a certain amount of time?
From pythonpython@hotmail.com Thu Jan 9 01:52:02 2003
From: pythonpython@hotmail.com (Hy Python)
Date: Thu Jan 9 01:52:02 2003
Subject: [Tutor] Kill A Fuction Call?
Message-ID:
try the thread or threading module.
Hy
>From: Scott
>To: tutor@python.org
>Subject: [Tutor] Kill A Fuction Call?
>Date: Thu, 9 Jan 2003 00:43:34 -0600
>
>Is it possible to call a function, and kill it if it doesn't complete in
>a certain amount of time?
>
>_______________________________________________
>Tutor maillist - Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
_________________________________________________________________
MSN 8 with e-mail virus protection service: 2 months FREE*
http://join.msn.com/?page=features/virus
From pythonpython@hotmail.com Thu Jan 9 01:54:03 2003
From: pythonpython@hotmail.com (Hy Python)
Date: Thu Jan 9 01:54:03 2003
Subject: [Tutor] How to force Tkinter scrollbar to move with the cursor without mouse/keyboard?
Message-ID:
Could someone please tell me:
How to force Tkinter scrollbar to move with the cursor without
mouse/keyboard?
I mean, when I execute something like:
textObject.mark_set(END, END)
the cursor automatically goes to the end of the textObject in the GUI
window, but the scrollbar does NOT move at all. How can I force the
scrollbar to move to the end in the GUI window with the cursor?
Thanks a lot for your help!
Hy
P.S.
The ScolledText class I am using:
class ScrolledText(Frame):
def __init__(self,parent=None,text=""):
Frame.__init__(self, parent)
self.pack(expand=YES, fill=BOTH)
self.makeWidgets()
self.setText(text)
def makeWidgets(self):
sbar=Scrollbar(self)
text=Text(self, relief=SUNKEN, width=60, height=15)
sbar.config(command=text.yview)
text.config(yscrollcommand=sbar.set)
sbar.pack(side=RIGHT, fill=Y)
text.pack(side=LEFT, expand=YES, fill=BOTH)
self.text=text
def setText(self,text):
self.text.delete('1.0', END)
self.text.insert('1.0', text)
self.text.mark_set(INSERT, END)
_________________________________________________________________
Add photos to your e-mail with MSN 8. Get 2 months FREE*.
http://join.msn.com/?page=features/featuredemail
From syrinx@simplecom.net Thu Jan 9 02:30:02 2003
From: syrinx@simplecom.net (Scott)
Date: Thu Jan 9 02:30:02 2003
Subject: [Tutor] Kill A Fuction Call?
In-Reply-To:
References:
Message-ID: <20030109012456.629f9da5.syrinx@simplecom.net>
On Thu, 09 Jan 2003 06:49:55 +0000
"Hy Python" wrote:
> try the thread or threading module.
> Hy
I thought of that but python doesn't allow you to kill threads, right?
From pythonpython@hotmail.com Thu Jan 9 02:49:02 2003
From: pythonpython@hotmail.com (Hy Python)
Date: Thu Jan 9 02:49:02 2003
Subject: [Tutor] Kill A Fuction Call?
Message-ID:
If all you want is to wait "a certain amount of time", you do not need to
kill the thread. When your main thread terminates, all the other thread will
die automatically.
example:
import thread,time
def myFunc():
time.sleep(2)
print "I am working..."
time.sleep(3)
print "I am killed by main thread..."
def mainFunc():
thread.start_new_thread(myFunc,())
time.sleep(4)
mainFunc()
In this program,
print "I am killed by main thread..."
will never be executed.
hope this helps...
Hy
On Thu, 09 Jan 2003 06:49:55 +0000
"Hy Python" wrote:
>try the thread or threading module.
>Hy
I thought of that but python doesn't allow you to kill threads, right?
>From: Scott
>To: tutor@python.org
>Subject: [Tutor] Kill A Fuction Call?
>Date: Thu, 9 Jan 2003 00:43:34 -0600
>
>Is it possible to call a function, and kill it if it doesn't complete in
>a certain amount of time?
>
>_______________________________________________
>Tutor maillist - Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
_________________________________________________________________
Add photos to your e-mail with MSN 8. Get 2 months FREE*.
http://join.msn.com/?page=features/featuredemail
From beercanz@hotmail.com Thu Jan 9 03:33:02 2003
From: beercanz@hotmail.com (Guess Who? Me)
Date: Thu Jan 9 03:33:02 2003
Subject: [Tutor] help understanding part of the tutorial...
Message-ID:
Here is the source, which is at
http://www.honors.montana.edu/~jjc/easytut/easytut/node10.html.
test.py
## This program runs a test of knowledge
true = 1
false = 0
# First get the test questions
# Later this will be modified to use file io.
def get_questions():
# notice how the data is stored as a list of lists
return [["What color is the daytime sky on a clear day?","blue"],\
["What is the answer to life, the universe and
everything?","42"],\
["What is a three letter word for mouse trap?","cat"]]
# This will test a single question
# it takes a single question in
# it returns true if the user typed the correct answer, otherwise false
def check_question(question_and_answer):
#extract the question and the answer from the list
question = question_and_answer[0]
answer = question_and_answer[1]
# give the question to the user
given_answer = raw_input(question)
# compare the user's answer to the testers answer
if answer == given_answer:
print "Correct"
return true
else:
print "Incorrect, correct was:",answer
return false
# This will run through all the questions
def run_test(questions):
if len(questions) == 0:
print "No questions were given."
# the return exits the function
return
index = 0
right = 0
while index < len(questions):
#Check the question
if check_question(questions[index]): <<<
I guess I found out how to do it now:
textObject.yview(END)
This will force the scrollbarOject.set() to push the bar to the end...
If you have better ways of achieving the same thing, please let me know.
Thanks.
Hy
>From: "Hy Python"
>To: tutor@python.org
>Subject: [Tutor] How to force Tkinter scrollbar to move with the cursor
>without mouse/keyboard?
>Date: Thu, 09 Jan 2003 06:45:44 +0000
>
>Could someone please tell me:
>How to force Tkinter scrollbar to move with the cursor without
>mouse/keyboard?
>
>I mean, when I execute something like:
> textObject.mark_set(END, END)
>the cursor automatically goes to the end of the textObject in the GUI
>window, but the scrollbar does NOT move at all. How can I force the
>scrollbar to move to the end in the GUI window with the cursor?
>
>Thanks a lot for your help!
>
>
>Hy
>P.S.
>
>The ScolledText class I am using:
>
>
>class ScrolledText(Frame):
> def __init__(self,parent=None,text=""):
> Frame.__init__(self, parent)
> self.pack(expand=YES, fill=BOTH)
> self.makeWidgets()
> self.setText(text)
> def makeWidgets(self):
> sbar=Scrollbar(self)
> text=Text(self, relief=SUNKEN, width=60, height=15)
> sbar.config(command=text.yview)
> text.config(yscrollcommand=sbar.set)
> sbar.pack(side=RIGHT, fill=Y)
> text.pack(side=LEFT, expand=YES, fill=BOTH)
> self.text=text
> def setText(self,text):
> self.text.delete('1.0', END)
> self.text.insert('1.0', text)
> self.text.mark_set(INSERT, END)
>
>
>_________________________________________________________________
>Add photos to your e-mail with MSN 8. Get 2 months FREE*.
>http://join.msn.com/?page=features/featuredemail
>
>
>_______________________________________________
>Tutor maillist - Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
_________________________________________________________________
MSN 8 helps eliminate e-mail viruses. Get 2 months FREE*
http://join.msn.com/?page=features/virus
From Janssen@rz.uni-frankfurt.de Thu Jan 9 05:00:02 2003
From: Janssen@rz.uni-frankfurt.de (Michael Janssen)
Date: Thu Jan 9 05:00:02 2003
Subject: [Tutor] Kill A Fuction Call?
In-Reply-To:
Message-ID:
also have look on the example for the signal module in the library: set
an SIGALARM handler an then set signal.alarm to an amount of time. This
*possible* also interrupts os.system or os.popen calls (havn't test it).
Michael
On Thu, 9 Jan 2003, Hy Python wrote:
> try the thread or threading module.
>
> Hy
>
>
>
> >From: Scott
> >
> >Is it possible to call a function, and kill it if it doesn't complete in
> >a certain amount of time?
> >
From abli@freemail.hu Thu Jan 9 06:17:01 2003
From: abli@freemail.hu (Abel Daniel)
Date: Thu Jan 9 06:17:01 2003
Subject: [Tutor] How to force Tkinter scrollbar to move with the cursor without mouse/keyboard?
In-Reply-To:
References:
Message-ID: <20030109111553.GA676@hooloovoo>
Hy Python (pythonpython@hotmail.com) wrote:
> I guess I found out how to do it now:
> textObject.yview(END)
> This will force the scrollbarOject.set() to push the bar to the end...
>
> If you have better ways of achieving the same thing, please let me know.
I guess the see() method is for doing exactly this:
'Scroll such that the character at INDEX is visible.'
abli
abli@freemail.hu
From magnus@thinkware.se Thu Jan 9 06:18:01 2003
From: magnus@thinkware.se (Magnus Lycka)
Date: Thu Jan 9 06:18:01 2003
Subject: [Tutor] weird edit menu
In-Reply-To:
Message-ID: <5.1.0.14.0.20030109121749.02c493c8@www.thinkware.se>
At 18:22 2003-01-08 -0600, David Richardson wrote:
>visited http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html
>to start toying with IDLE (python GUI)
>
>The edit menu to python 2.2.2 does not look like the images. In fact I
>can't find run script anywhere! Did I screw up something during install?
No, just look further!
At least in my 2.2.1, it's further down. Nine more menu items
have been inserted between Select All and Check Module.
As you see in the pictures, Danny's IDLE intro is made with
an earlier version of Python. It's a bit sloppy that they
didn't change the version number in IDLE though. (Mine is
0.8 as it is in the intro.)
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se
From magnus@thinkware.se Thu Jan 9 06:42:02 2003
From: magnus@thinkware.se (Magnus Lycka)
Date: Thu Jan 9 06:42:02 2003
Subject: [Tutor] OOP class declaration question
In-Reply-To:
Message-ID: <5.1.0.14.0.20030109115304.02c2cad8@www.thinkware.se>
At 18:15 2003-01-08 -0600, Cameron Stoner wrote:
>Hi all,
>
>Recently I made a class that I found out wouldn't work properly unless all
>the variables were filled with something.
A variable is ALWAYS a reference to an object. From
a technical point of view you can see it as a location
in a computers memory where you store an address to
another location in the memory, where some data is stored.
I imagine this is one more level of indirection than you
thought. This is the same whether you use classes or not.
It's probably more helpful if you see a variable as something
that points out an existing object, rather than as something
that you fill with an object. Let me explain why.
a = [1,2]
b = a
c = b
With the python code above, you have ONE list with the integers
1 and 2. There are three variables, but only one list object.
If you do b.append(5), and print c, it will show [1, 2, 5]. Right?
If you imagine c = b as filling the c variable with a list, you
get the wrong idea, right? c = b means that you make c point to
(or refer to) the same object in memory as the variable b (and a)
does. Right?
> My question is why do you have to have all the fields filled with
> something? Is it because you can't make an object of something without
> knowing what each part is soposed to be?
This is really nothing particular for classes.
> I thought python could allow for variable declaration on the fly and you
> didn't have to worry about what type of data it was sopposed to hold.
No. You don't have varable declarations at all in
Python. You just define them. Compare with C etc.
int i; /* declaration of i */
...
i = 5; /* definition of i */
In python this is replaced with:
i = 5 # That's all folks!
It's completely pointless in Python to refer to a variable
before you have defined it. You have it all upside down. It's
in the OTHER programming languages, the ones with static
typing that allows you (well, forces you rather) to declare
variables before you use them.
It might feel confusing that not all attributes of the class
is listed in one place as in Java or C++, but that's life in
a dynamic language. You can add new attributes in runtime as
you like. There is no way for the class definition to know
about that. If this feels like a bad thing to you, have a look
at the new style classes in Python 2.2, and slots.
>Here is the code:
>
>class mobileSuit:
> def __init__(self,lArm, rArm, head, lLeg, rLeg, back, maxHealth):
> self.leftArmHealth = lArm
> self.rightArmHealth = rArm
> self.headHealth = head
> self.leftLegHealth = lLeg
> self.rightLegHealth = rLeg
> self.backHealth = back
> self.maxHealth = maxHealth
Just skip the next two lines. They are pointless. You don't
do declarations in Python.
> self.healthPercent
> self.actualHealth
Or, optionally, you might want to set these attributes to
some default value, that you use to indicate "undefined".
Maybe None?
> #request overall health
> def overallHealth(self, report):
>
> #determine actualHealth
> self.actualHealth = (self.leftArmHealth + self.rightArmHealth +
> self.headHealth + self.leftLegHealth + self.rightLegHealth +
> self.backHealth) / 6
>
>
> #find percent of health
> self.healthPercent = (self.actualHealth / self.maxHealth) * 100
Here you define these attributes. They don't need to exist
before you run this code.
How ever you do this, you will run into problems if you try
to access self.actualHealth or self.healthPercent before you
run the overallHealth method. If you set default values, whatever
code is fetching the attribute will get an irrelevant value, and
must be able to distinguish that. If you don't set any default
values, you will get AttributeError is you do something like...
testSuit = mobileSuit(6,6,6,6,6,6,6)
print testSuit.healthPercent
> # report the status with a print else return the result
> if report == 1:
> print "The MS health is: ", self.healthPercent
> else:
> return self.healthPercent
But if this is the only way you intend to use "self.actualHealth"
and "self.healthPercent", you don't need the "self."-part, i.e.
you shouldn't make them attributes of the instance. Instance
attributes are only used when you want a value to persist between
method calls.
>testSuit = mobileSuit(6,6,6,6,6,6,6)
If I understand your intent correctly, you can simply do
class mobileSuit:
def __init__(self,lArm, rArm, head, lLeg, rLeg, back, maxHealth):
self.leftArmHealth = lArm
self.rightArmHealth = rArm
self.headHealth = head
self.leftLegHealth = lLeg
self.rightLegHealth = rLeg
self.backHealth = back
self.maxHealth = maxHealth
#request overall health
def overallHealth(self, report):
#determine actualHealth
actualHealth = (self.leftArmHealth + self.rightArmHealth +
self.headHealth + self.leftLegHealth + self.rightLegHealth +
self.backHealth) / 6.0 # Use a float unless you want to truncate.
#find percent of health
healthPercent = (actualHealth / self.maxHealth) * 100
# report the status with a print else return the result
if report:
print "The MS health is: ", healthPercent
else:
return healthPercent
If you _do_ want the values calculated in overallHealth to persist,
I suggest that you call overallHealth in __init__ unless that leads
to bad performance. (Many million health records?) That way you will
allways have a reasonable value in those attributes.
Of course, if you change a used attribute, you need to call
overallHealth again.
x = mobileSuit(6,6,6,6,6,6,6)
x.overallHealth(1)
The MS health is: 100.0
print x.healthPercent
100.0
x.leftArmHealth = 3
print x.healthPercent
100.0
x.overallHealth(1)
The MS health is: 91.6666666667
print x.healthPercent
91.666666666666657
There are ways of calling overallHealth automagically whenever
an attribute in the class is changed, but that's not for today's
lecture...
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se
From magnus@thinkware.se Thu Jan 9 07:11:18 2003
From: magnus@thinkware.se (Magnus Lycka)
Date: Thu Jan 9 07:11:18 2003
Subject: [Tutor] help understanding part of the tutorial...
In-Reply-To:
Message-ID: <5.1.0.14.0.20030109125147.02c2d548@www.thinkware.se>
At 08:24 2003-01-09 +0000, Guess Who? Me wrote:
>I don't understand how this if loop returns a value using true and false
There is no such thing as an "if loop". The indented code block following an
if statement is executed once if the value of the expression between "if"
and ":" is true, and it will be skipped if the value of the expression was
false. The concepts of true and false has nothing to do with any names of
variables in the program. As far as Python is concerned, the fact that there
is a varaible called true with the value 1, and a variable false with the
value 0 is completely irrelevant. They could have been called stilton and
cheddar instead.
From the Language Reference Manual, section 5.10:
"In the context of Boolean operations, and also when expressions are used by
control flow statements, the following values are interpreted as false:
None, numeric zero of all types, empty sequences (strings, tuples and
lists), and empty mappings (dictionaries). All other values are interpreted
as true."
1 and 0 are often used for true and false, but 5 and "" would also work.
In this case, the function called check_question will return 1 or 0. If it
returns 1 (true) the expression "right = right + 1" will be executed, if it
returns 0 (false) it will be skipped, and right will remain unchanged. In
other words, right is only incremented if you give the right reply to the
question.
> - I know that true=1 and false=0, but I don't get how right=right+1
> works out - does it mean that if the statement returns a false answer,
> the rest of the if loop doesn't get carried out?
The next line won't get executed. The while loop continues.
># This will run through all the questions
>def run_test(questions):
> if len(questions) == 0:
> print "No questions were given."
> # the return exits the function
> return
> index = 0
> right = 0
> while index < len(questions):
> #Check the question
> if check_question(questions[index]): <<< right = right + 1
> #go to the next question
> index = index + 1
> #notice the order of the computation, first multiply, then divide
> print "You got ",right*100/len(questions),"% right out of",len(questions)
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se
From magnus@thinkware.se Thu Jan 9 07:15:02 2003
From: magnus@thinkware.se (Magnus Lycka)
Date: Thu Jan 9 07:15:02 2003
Subject: [Tutor] Kill A Fuction Call?
In-Reply-To:
Message-ID: <5.1.0.14.0.20030109131643.02c22a08@www.thinkware.se>
At 07:47 2003-01-09 +0000, Hy Python wrote:
>If all you want is to wait "a certain amount of time", you do not need to
>kill the thread. When your main thread terminates, all the other thread
>will die automatically.
But if you have a long running program in your main thread,
you might not like to have big, CPU intensive jobs that you
stopped waiting for running in another thread... For a
server this might be a killer.
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se
From janos.juhasz@VELUX.com Thu Jan 9 07:16:03 2003
From: janos.juhasz@VELUX.com (janos.juhasz@VELUX.com)
Date: Thu Jan 9 07:16:03 2003
Subject: [Tutor] OOP class declaration question
Message-ID:
Dear Magnus,
You wrote:
There are ways of calling overallHealth automagically whenever
an attribute in the class is changed, but that's not for today's
lecture...
So, I am waiting the next lecture :)
Best regards,
-----------------------
Juh=E1sz J=E1nos
IT department
=
From magnus@thinkware.se Thu Jan 9 07:33:02 2003
From: magnus@thinkware.se (Magnus Lycka)
Date: Thu Jan 9 07:33:02 2003
Subject: [Tutor] OOP class declaration question
In-Reply-To:
Message-ID: <5.1.0.14.0.20030109133445.02c27de0@www.thinkware.se>
At 13:15 2003-01-09 +0100, janos.juhasz@VELUX.com wrote:
>Dear Magnus,
>
>You wrote:
>There are ways of calling overallHealth automagically whenever
>an attribute in the class is changed, but that's not for today's
>lecture...
Untested...
def __setattr__(self, attr, value):
self.__dict__[attr] = value
self.overallHealth()
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se
From VirginiaW@cortland.edu Thu Jan 9 08:16:00 2003
From: VirginiaW@cortland.edu (Virginia Wright)
Date: Thu Jan 9 08:16:00 2003
Subject: [Tutor] remove me from list
Message-ID:
This is a multi-part message in MIME format.
------_=_NextPart_001_01C2B7E1.1CE00E79
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
Please remove me from the python list. Thank you.
=20
Jean
------_=_NextPart_001_01C2B7E1.1CE00E79
Content-Type: text/html;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
Please remove me =
from the=20
python list. Thank you.
Jean
------_=_NextPart_001_01C2B7E1.1CE00E79--
From glingl@aon.at Thu Jan 9 08:51:25 2003
From: glingl@aon.at (Gregor Lingl)
Date: Thu Jan 9 08:51:25 2003
Subject: [Tutor] help understanding part of the tutorial...
References: <5.1.0.14.0.20030109125147.02c2d548@www.thinkware.se>
Message-ID: <3E1D7DF3.2000409@aon.at>
Magnus Lycka schrieb:
> At 08:24 2003-01-09 +0000, Guess Who? Me wrote:
>
>> I don't understand how this if loop returns a value using true and false
>
>
> There is no such thing as an "if loop".
....
> In
> other words, right is only incremented if you give the right reply to the
> question.
You may check this in an interactive session. After you have run the program
once (from IDLE), the following is possible:
>>> questions = get_questions()
>>> right = 0
>>> if check_question(questions[0]):
right = right + 1
What color is the daytime sky on a clear day?blue
Correct
>>> right
1
>>> if check_question(questions[0]):
right = right + 1
What color is the daytime sky on a clear day?red
Incorrect, correct was: blue
>>> right
1
>>> if check_question(questions[1]):
right = right + 1
What is the answer to life, the universe and everything?1
Incorrect, correct was: 42
>>> right
1
>>> if check_question(questions[1]):
right = right + 1
What is the answer to life, the universe and everything?42
Correct
>>> right
2
>>>
Another way to get some more insight in the working of your
program is to insert some additional print-statements, for
instance - as you already know (from the code of the
check-question-function) that the conditional statement
may have an else-branch - the following:
while index < len(questions):
#Check the question
if check_question(questions[index]): #<<<>>
What color is the daytime sky on a clear day?blue
Correct
right incremented to 1
What is the answer to life, the universe and everything?1
Incorrect, correct was: 42
sorry, right remains 1
What is a three letter word for mouse trap?cat
Correct
right incremented to 2
You got 66.6666666667 % right out of 3
>>>
Of course, after you have done your work and
understand the code, delete or comment out those
print-statements, you dindn't intend to be in
the program.
Regards, Gregor
From Janssen@rz.uni-frankfurt.de Thu Jan 9 09:13:04 2003
From: Janssen@rz.uni-frankfurt.de (Michael Janssen)
Date: Thu Jan 9 09:13:04 2003
Subject: [Tutor] help understanding part of the tutorial...
In-Reply-To:
Message-ID:
On Thu, 9 Jan 2003, Guess Who? Me wrote:
[snip - unpythonic written tutorialcode ;-)]
> if check_question(questions[index]): <<< right = right + 1
[snip - upwtc]
> I don't understand how this if loop returns a value using true and false - I
> know that true=1 and false=0, but I don't get how right=right+1 works out -
> does it mean that if the statement returns a false answer, the rest of the
> if loop doesn't get carried out?
Yes, you're right (but don't call it "if loop" as Magnus has stated).
> Because it seems to me right=right+1 would
> give you a minimum of three right answers, because you asked three questions
> - I'm obviously missing some concept, could somebody fill me in?
maybe you've missed, that you can use:
if 1: # no testing, this if_condition is always true
...do something...
if a_variable_you_have_defined_earlier == 5: # a test
...do something...
if a_function_that_returns_something(): # takes the
# returnvalue of this
# function as if_condition
...do something...
In my opinion this code isn't very helpfull even for learning purpose
because its comments simply duplicate the programm logic. It's not
helpful to prevent the learner from understanding the smallest part of
code on his own and instead make him read everything as comments.
On the other hand this code obfusciate a bit in using "true" and "false"
were a simple 0 or 1 would be enough. The while loop should be a "for elem
in question" loop. The intention for both might be to write code as
similar to non-programmer thinking as possibly. But I'm wondering if the
author of the tutorial really want to provide a section about "using 1 and
0 for true and false in the (common) case it is completly sufficient" to
lead the expierenced learners to a deeper insight what kind programming
is ;-)
Do not start learning with learning bad habits.
Michael
>
> Thanks!
> Travis
>
>
>
> _________________________________________________________________
> The new MSN 8 is here: Try it free* for 2 months
> http://join.msn.com/?page=dept/dialup
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From aztech1200@yahoo.com Thu Jan 9 09:16:03 2003
From: aztech1200@yahoo.com (Aztech Guy)
Date: Thu Jan 9 09:16:03 2003
Subject: [Tutor] Python style: if/else vs. exceptions?
In-Reply-To: <20030108162236.78572.qmail@web9806.mail.yahoo.com>
Message-ID: <20030109141435.92388.qmail@web9801.mail.yahoo.com>
Hello list,
As a matter of good coding style, what are your
opinions on when to use if/elif/else sequences versus
when to use exceptions, i.e. try/except/finally ?
TIA
Az
__________________________________________________
Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now.
http://mailplus.yahoo.com
From glingl@aon.at Thu Jan 9 12:40:50 2003
From: glingl@aon.at (Gregor Lingl)
Date: Thu Jan 9 12:40:50 2003
Subject: [Tutor] OT: 42?
Message-ID: <3E1D88C8.5090202@aon.at>
What's so special about 42?
Gregor
From alan.gauld@bt.com Thu Jan 9 12:44:49 2003
From: alan.gauld@bt.com (alan.gauld@bt.com)
Date: Thu Jan 9 12:44:49 2003
Subject: [Tutor] wxPython newbie
Message-ID: <7497DCA1C240C042B28F6657ADFD8E0974DA83@i2km11-ukbr.domain1.systemhost.net>
>
>When in doubt print it out is my motto.
>
> And my motto is "When in doubt, learn the right way
> to do it!" ;)
Sure but a good way to find out whats happening
in Python code is via python... Its one of its strongest
features that almost anything can be printed.
> > res = d.ShowModal()
> > print res
>
> Because it will just be a stupid digit that doesn't
> mean anything to whoever reads the code.
Well, it might be, but then again it could be a string
"Yes" or "No" which is, ISTR, how TKinter dialogs respond...
> >See what gets printed and substitute in your program...
> Better to use wxID_YES, wxID_NO, wxID_OK or wxID_CANCEL.
Absolutely. If there are defined constats then use the
definitions - or at least define your own if they don't
already exist. But when you don't even know what type of
response youll get, print is the best solution.
Alan g.
From op73418@mail.telepac.pt Thu Jan 9 12:45:55 2003
From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Thu Jan 9 12:45:55 2003
Subject: [Tutor] is this code dangerous?
Message-ID: <004501c2b72f$8e6d2a20$97190dd5@violante>
----- Original Message -----
From: "Gonçalo Rodrigues"
To:
Sent: Wednesday, January 08, 2003 4:02 PM
Subject: Re: [Tutor] is this code dangerous?
>
> ----- Original Message -----
> From: "Alfred Milgrom"
> To:
> Sent: Wednesday, January 08, 2003 1:14 PM
> Subject: [Tutor] is this code dangerous?
>
>
> > Hi:
> >
> > Can someone please tell me the best way to override class methods for
> > specific instances?
> >
> > I want to have a general class, such as Person, with general methods.
Some
> > of the instances of the Person class may have different methods, and I
> want
> > to be able to override the base method (such as the speak method for the
> > cranky person in the example below).
> >
> > Do I need to define a new class for each instance where there is a
> > different method? Is there overhead associated with having a large
number
> > of classes?
> >
>
> Using the example you give below you can also do:
>
> >>> class Person:
> ... def __init__(self, name):
> ... self.name = name
> ... def speak(self):
> ... print "%s says: my name is %s" % (self.name, self.name)
> ...
> >>> Person
>
> >>> cranky = Person('someone else')
> >>> def crankyspeak(self):
> ... print "%s says: I don't tell anyone my name" % (self.name)
> ...
> >>> cranky.speak = crankyspeak
>
> But you have to notice though that speak is not a method but a plain
> function object: self is not automatically passed, e.g.
>
> >>> cranky.speak()
> Traceback (most recent call last):
> File "", line 1, in ?
> TypeError: crankyspeak() takes exactly 1 argument (0 given)
> >>> cranky.speak(cranky)
> someone else says: I don't tell anyone my name
>
> There are ways of course to override this - e.g. using something like the
> template pattern. You could code something like
>
> class Person:
>
>
> def speak(self):
> __speak = self.et('my_speak')
This should read:
__speak = self.__dict__.get('my_speak')
[rest snipped]
With my best regards,
G. Rodrigues
From ramrom@earthling.net Thu Jan 9 17:10:24 2003
From: ramrom@earthling.net (Bob Gailer)
Date: Thu Jan 9 17:10:24 2003
Subject: [Tutor] Best way to convert a type into string
Message-ID: <5.2.0.9.0.20030109145611.03c0ec28@66.28.54.253>
--=======1C032CC7=======
Content-Type: text/plain; x-avg-checked=avg-ok-1BA33EF8; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit
>>> type(1)
What's the best way to get the string "int" from this? My goal is to
construct a string similar to:
'pysqlite_pragma expected_types = int,str,int,float'
by applying type() to a series of values.
repr(type(1))[7:-2] does it; I was hoping for something simpler.
Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=======1C032CC7=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1BA33EF8
Content-Disposition: inline
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003
--=======1C032CC7=======--
From aztech1200@yahoo.com Thu Jan 9 17:15:05 2003
From: aztech1200@yahoo.com (Aztech Guy)
Date: Thu Jan 9 17:15:05 2003
Subject: [Tutor] Python style: if/else vs. exceptions? [Thanks]
In-Reply-To: <5.1.0.14.0.20030109154401.02c6b2e8@www.thinkware.se>
Message-ID: <20030109164728.20516.qmail@web9807.mail.yahoo.com>
Thanks a lot, Magnus.
That was a good amount of useful info.
Az
--- Magnus Lycka wrote:
> Use whatever makes the code easier to read and
> maintain, in the long run...
..
> assumes less about calculate...
>
__________________________________________________
Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now.
http://mailplus.yahoo.com
From phil@xfr.co.uk Thu Jan 9 17:17:06 2003
From: phil@xfr.co.uk (Philip Kilner)
Date: Thu Jan 9 17:17:06 2003
Subject: [Tutor] OT: 42?
In-Reply-To: <3E1D88C8.5090202@aon.at>
References: <3E1D88C8.5090202@aon.at>
Message-ID:
Hi Gregor
In article <3E1D88C8.5090202@aon.at>, Gregor Lingl wrote:
> What's so special about 42?
>
Well, it's the answer to the question of life, the universe and
everything in Douglas Adams' "Hitchhikers Guide to the Galaxy"
four-or-more part trilogy...
Why do you ask?
Regards,
PhilK
Thu, 09 Jan 2003 19:11 GMT @ Vaio
Email: phil@xfr.co.uk / Voicemail & Facsimile: 07092 070518
Tell me and I forget.
Show me and I remember.
Involve me and I understand.
- Chinese saying
From gp@pooryorick.com Thu Jan 9 17:22:22 2003
From: gp@pooryorick.com (Poor Yorick)
Date: Thu Jan 9 17:22:22 2003
Subject: [Tutor] instance variables and the instance dictionary
Message-ID: <3E1DA943.9030102@pooryorick.com>
In an instance, are the following statements equivalent? Are there any
caveats to setting an instance variable the second way?
self.var1 = 5
self.__dict__.__setitem__('var1', 5)
Poor Yorick
gp@pooryorick.com
From dyoo@hkn.eecs.berkeley.edu Thu Jan 9 17:23:10 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jan 9 17:23:10 2003
Subject: [Tutor] OT: 42?
In-Reply-To: <3E1D88C8.5090202@aon.at>
Message-ID:
On Thu, 9 Jan 2003, Gregor Lingl wrote:
> What's so special about 42?
Hi Gregor,
###
>>> def to_binary(n):
... "Given a positive integer n, returns its binary representation."
... if n == 0: return ""
... return to_binary(n/2) + str(n%2)
...
>>> to_binary(42)
'101010'
###
So it's quite a symmetric number.
There's a nice web site that summarizes sightings of the number 42
throughout history:
http://www.empirenet.com/~dljones/
Hope this helps!
From dyoo@hkn.eecs.berkeley.edu Thu Jan 9 17:23:19 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jan 9 17:23:19 2003
Subject: [Tutor] help understanding part of the tutorial...
In-Reply-To:
Message-ID:
On Thu, 9 Jan 2003, Guess Who? Me wrote:
> # This will run through all the questions
> def run_test(questions):
> if len(questions) == 0:
> print "No questions were given."
> return
> index = 0
> right = 0
> while index < len(questions):
> if check_question(questions[index]):
> right = right + 1
> index = index + 1
> print "You got ",right*100/len(questions),"% right out
> of",len(questions)
Hi Travis
Hmmm... this code can be improved. There are a few things we can do:
1. Use a for loop instead of a while loop. As far as I can tell,
there's no need for a separate "index" variable if we use a 'for'
loop here. Since we're "iterating" or going through a list of
questions, it's much more natural to use a "for" loop.
2. Yank our the question asking section into a separate function:
this might help us better understand the flow of the program if
the body of each function is tiny.
3. Rename "check_question()" to something more obvious like
"is_question_answered_correctly()". check_question() does not
give much clue as to what will be returned if a question is
answered correctly or not: what are we "checking" for?
If we rename the function to "is_question_answered_correctly()",
that makes it more clear that we'll get a true value if the
user is hitting the right buttons. *grin*
Programs are not chisled into stone: they can be revised, just like essays
or creative writing. We shouldn't be afraid to break up the code into
pieces. We may find that doing a "refactoring" can often help to make the
code less inscrutable. *grin*
Here's one way we can revise that run_test() function:
###
# (assume that check_question() has been renamed to
# is_question_answered_correctly())
def run_test(questions):
"""Asks all questions of a test, and tallies up a percentage of
correct answers."""
if len(questions) == 0:
print "No questions were given."
return
right = count_right_answers(questions)
print "You got ", right*100/len(questions),
print "% right out of",len(questions)
def count_right_answers(questions):
"""Given a list of questions, asks each question in turn, and returns
the number of correctly answered questions."""
number_correct = 0
for question in questions:
if is_question_answered_correctly(question):
number_correct = number_correct + 1
return number_correct
###
Is this easier to understand?
From dyoo@hkn.eecs.berkeley.edu Thu Jan 9 17:23:32 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jan 9 17:23:32 2003
Subject: [Tutor] remove me from list
In-Reply-To:
Message-ID:
On Thu, 9 Jan 2003, Virginia Wright wrote:
> Please remove me from the python list. Thank you.
>
> Jean
Hi Jean,
You can unsubscribe yourself by visiting that mailing list page that you
used to subscribe to Tutor:
http://mail.python.org/mailman/listinfo/tutor
If you go down to the bottom of that page, you should see something about
"Edit Options", which you can use. The unsubscription button is linked up
from your Options page.
If you run into other problems while unsubscribing, please feel free to
email the administrative address "tutor-admin@python.org". That way, you
can instantly get in touch with the list admins.
Hope this helps!
From dyoo@hkn.eecs.berkeley.edu Thu Jan 9 17:23:47 2003
From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
Date: Thu Jan 9 17:23:47 2003
Subject: [Tutor] weird edit menu
In-Reply-To: <5.1.0.14.0.20030109121749.02c493c8@www.thinkware.se>
Message-ID:
On Thu, 9 Jan 2003, Magnus Lycka wrote:
> At 18:22 2003-01-08 -0600, David Richardson wrote:
> >visited http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html
> >to start toying with IDLE (python GUI)
> >
> >The edit menu to python 2.2.2 does not look like the images. In fact I
> >can't find run script anywhere! Did I screw up something during install?
>
> No, just look further!
>
> At least in my 2.2.1, it's further down. Nine more menu items have been
> inserted between Select All and Check Module.
Hmmm! David, if you see any other significant changes in 2.2's IDLE and
the one on the IDLE intro, please feel free to email me about them; I'll
try to update those images when I get back home.
From ramrom@earthling.net Thu Jan 9 17:26:07 2003
From: ramrom@earthling.net (Bob Gailer)
Date: Thu Jan 9 17:26:07 2003
Subject: [Tutor] OT: 42?
In-Reply-To: <3E1D88C8.5090202@aon.at>
Message-ID: <5.2.0.9.0.20030109120753.03bb2d58@66.28.54.253>
--=======97119F5=======
Content-Type: text/plain; x-avg-checked=avg-ok-1BA33EF8; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit
At 03:35 PM 1/9/2003 +0100, Gregor Lingl wrote:
>What's so special about 42?
>Gregor
It's the ONLY integer whose prime factors are 2*3*7!
Bob Gailer
mailto:ramrom@earthling.net
303 442 2625
--=======97119F5=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-1BA33EF8
Content-Disposition: inline
---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.438 / Virus Database: 246 - Release Date: 1/7/2003
--=======97119F5=======--
From joney@clara.co.uk Thu Jan 9 17:30:03 2003
From: joney@clara.co.uk (john gennard)
Date: Thu Jan 9 17:30:03 2003
Subject: [Tutor] comments in python
Message-ID: <20030109181310.GA318@Leary>
I've had to suspend my learning for a while - health problems.
Now I'm back and have decided that, for me personally, the best
way to learn may be to 'take apart' some programs and study the
syntax that way (I do know they work, so the 'problem' is why do
they?).
Now, I find that what must be 'narrative' appears in three ways:-
a. #blah blah blah
This of course is no problem, but then I've seen:-
b. """
blah blah blah
"""
and also:-
c. ''' blah blah blah '''
b. and c. only seem to be used in the 'meat' of the programs,
usually after the exhortation 'do not alter below here'
I can find in O'Reilly reference to the use of triple quotes under
'strings' but what I see in the programs appears to be quite
different to this.
Will someone say if I'm just being thick? Perhaps I don't understand
what a 'string' is in plain language!
Any help will be much appreciated.
Regards, John.
From op73418@mail.telepac.pt Thu Jan 9 17:33:10 2003
From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Thu Jan 9 17:33:10 2003
Subject: [Tutor] OT: 42?
References: <3E1D88C8.5090202@aon.at>
Message-ID: <000701c2b817$e0b126e0$b31a0dd5@violante>
----- Original Message -----
From: "Gregor Lingl"
To:
Sent: Thursday, January 09, 2003 2:35 PM
Subject: [Tutor] OT: 42?
> What's so special about 42?
Hitchiker's guide to the galaxy. There is a computer built especially to
spit out the answer to the question, what is the meaning of life? After a
straining and stressing time it answers 42.
> Gregor
>
With my best regards,
G. Rodrigues
From carroll@tjc.com Thu Jan 9 17:34:02 2003
From: carroll@tjc.com (Terry Carroll)
Date: Thu Jan 9 17:34:02 2003
Subject: [Tutor] OT: 42?
In-Reply-To: <3E1D88C8.5090202@aon.at>
Message-ID:
On Thu, 9 Jan 2003, Gregor Lingl wrote:
> What's so special about 42?
http://www.42webdesign.com/why42.html
--
Terry Carroll |
Santa Clara, CA | "The parties are advised to chill."
carroll@tjc.com | - Mattel, Inc. v. MCA Records, Inc.,
Modell delendus est | no. 98-56577 (9th Cir. July 24, 2002)
From jeff@ccvcorp.com Thu Jan 9 17:56:03 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu Jan 9 17:56:03 2003
Subject: [Tutor] OT: 42?
References: <3E1D88C8.5090202@aon.at>
Message-ID: <3E1DCEF4.9080605@ccvcorp.com>
Gregor Lingl wrote:
> What's so special about 42?
It's the Answer to the Ultimate Question about Life, the Universe, and
Everything. Of course, it's still not clear just how that answer was
reached, or what it means, or (most importantly) just what that Ultimate
Question *is*, but at least we know the Answer, right?
At least, so saith Douglas Adams, in The Hitchhiker's Guide to the Galaxy.
Jeff Shannon
Technician/Programmer
Credit International
From jeff@ccvcorp.com Thu Jan 9 17:56:12 2003
From: jeff@ccvcorp.com (Jeff Shannon)
Date: Thu Jan 9 17:56:12 2003
Subject: [Tutor] Kill A Fuction Call?
References: <20030109004334.504ca019.syrinx@simplecom.net>
Message-ID: <3E1DD0E8.5000703@ccvcorp.com>
Scott wrote:
>Is it possible to call a function, and kill it if it doesn't complete in
>a certain amount of time?
>
>
Sort of, but not easily, and the method of doing so depends on whether
you're writing the function yourself. If you *are*, then the simplest
way is to have the function code periodically check a timer and abort
itself if it's taken too long. (This can be combined with threads --
have the function's worker thread check a simple 'abort' flag, and have
a timer or other function set that flag as needed.)
If you do not have control over the function, then this is a very
difficult thing. Threads won't work, because Python won't let you kill
threads from outside, as you already know. You *can* run the function
in a separate process, using standard IPC mechanisms like pipes, because
processes (unlike threads) can be killed -- but processes are also
rather heavier and more awkward to use. Depending on just what it is
that you're doing, there may be some way around the limitations, too --
if you're waiting on a socket connection, say, there's a timeoutsocket
module available that will do this for you.
Jeff Shannon
Technician/Programmer
Credit International
From magnus@thinkware.se Thu Jan 9 17:56:24 2003
From: magnus@thinkware.se (Magnus Lycka)
Date: Thu Jan 9 17:56:24 2003
Subject: [Tutor] OT: 42?
In-Reply-To: <3E1D88C8.5090202@aon.at>
Message-ID: <5.1.0.14.0.20030109235713.02c29bb0@www.thinkware.se>
At 15:35 2003-01-09 +0100, Gregor Lingl wrote:
>What's so special about 42?
It's the answer to Life, the Universe and Everything.
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se
From op73418@mail.telepac.pt Thu Jan 9 18:04:01 2003
From: op73418@mail.telepac.pt (=?iso-8859-1?Q?Gon=E7alo_Rodrigues?=)
Date: Thu Jan 9 18:04:01 2003
Subject: [Tutor] instance variables and the instance dictionary
References: <3E1DA943.9030102@pooryorick.com>
Message-ID: <004a01c2b834$395d6f30$54180dd5@violante>
----- Original Message -----
From: "Poor Yorick"
To: