Re: [Tutor] What exactly is [::-1]?

2007-07-25 Thread John Fouhy
On 26/07/07, Luke Paireepinart <[EMAIL PROTECTED]> wrote:
> Wow, it was actually quite a bit harder to Google than I thought :)
> well, some experimentation leads me to believe this is the syntax for
> list slicing:
[...]

It's in the docs, albeit rather tersely:
http://www.python.org/doc/current/lib/typesseq.html

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What exactly is [::-1]?

2007-07-25 Thread wesley chun
when you use the 3rd element, it's called the extended slice syntax.
here are a few more examples:

>>> x = 'python programming'
>>> x[::-1]
'gnimmargorp nohtyp'
>>> x[2:12:2]
'to rg'
>>>

ironically, this feature has been available in the interpreter for
many years, but it wasn't until circa 2.3 that it was available via
Python syntax.  it was also odd that i could use the extended slice
syntax with Jython (formerly JPython) 1.1 when it wasn't available in
the standard C Python back in the day.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What exactly is [::-1]?

2007-07-25 Thread Luke Paireepinart
Dick Moores wrote:
> At 08:38 PM 7/25/2007, Luke Paireepinart wrote:
>> > I would like to know what exactly the index notation of [::-1] is, 
>> where
>> > it comes from and if there are other variants.
>> >
>> This is called list slicing.  Look into it to figure out what all this
>> stuff means.
>> I could send you a link but I'd just google 'python list slicing' to
>> find it, so I'll leave that as an exercise for the reader.
>
> I don't find Google of help with this. Could someone supply a link?
Wow, it was actually quite a bit harder to Google than I thought :)
well, some experimentation leads me to believe this is the syntax for 
list slicing:

x[ i : j ] slices from i to j
x[ i : ] slices from i to the end of the list
x[ : j ] slices from the beginning of the list to j
x[ : ] slices from the beginning of the list to the unspecified 
parameter (the end of the list)  in other words, you can use this to 
make a copy.
x[ : : ]  This seems to work the same as the above.
(note that in both cases, : and ::, the list is just a one-level-deep 
copy.  so the list [[1,2,3],[4,5,6]] can't be copied fully with this.)
however,
x[ : : k ] is a copy (same as above) that uses k as a step.
Here are some examples that should make it make sense.
 >>> x = [1,2,3,4,5,6,7,8,9]
 >>> x[::1]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
 >>> x[::2]
[1, 3, 5, 7, 9]
 >>> x[::5]
[1, 6]
 >>> x[::-5]
[9, 4]
 >>> x[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]


To summarize, the negative/positiveness of this parameter k denotes 
whether the step is from beginning to end, or from end to beginning.
so if it's negative, the step will start at the last element, then step 
|k| toward the beginning, then grab that element ( if such an element 
exists) and proceed in this manner.

This is all gleaned from experimentation, so it shouldn't be taken as 
the Word.
HTH,
-Luke

>
> Dick Moores
>
>
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] What exactly is [::-1]?

2007-07-25 Thread Dick Moores
At 08:38 PM 7/25/2007, Luke Paireepinart wrote:
> > I would like to know what exactly the index notation of [::-1] is, where
> > it comes from and if there are other variants.
> >
>This is called list slicing.  Look into it to figure out what all this
>stuff means.
>I could send you a link but I'd just google 'python list slicing' to
>find it, so I'll leave that as an exercise for the reader.

I don't find Google of help with this. Could someone supply a link?

Dick Moores


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Livewires questions

2007-07-25 Thread Luke Paireepinart


As promised, here's some comments on your code.


from livewires import *
begin_graphics()
allow_moveables()
def place_player():
global player_x
global player_y
global player_shape
player_y = random_between(0,47)
player_x = random_between(0,63)
player_shape = circle(10*player_x, 10*player_y, 5, filled=1)
  

In general, you should try to avoid global usage like this.
You'd want to  have a player class, probably.
However, the way this tutorial is going, it seems like this is what it 
expects you to do.
It mentions classes further near the end of the tutorial, so don't worry 
about it.

for now, we'll just go with what you've got.

def place_robot():
global robot_x
global robot_y
global robot_shape
robot_y = random_between(0,47)-0.5
robot_x = random_between(0,63)-0.5
  

I'm not too clear why you're subtracting 0.5 here.
Doesn't this make the robot's center on the grid lines, rather than 
having the robot occupy a full square on the grid?

I guess that's the intended behavior, huh?

robot_shape = box(10*robot_x, 10*robot_y,10*robot_x+10,10*robot_y+10)
def move_player():
while 1:
global player_x
global player_y
  
if 't' in keys:

place_player()
break
  
You can't reuse your place_player function here, because you put the 
initialization (the creation) of the graphics that represent the player 
_inside_ of the place_player function.  Well, technically you could, but 
it would be better instead to use move_to(player_shape, x, y) because 
this doesn't overwrite the old player_shape circle.

Also, will this work if the player presses "T"?

if '8' in keys:
move_to(player_shape,player_x*10 ,player_y*10 + 10)
player_y = player_y + 1
if player_y > 47:
player_y = player_y -1
else:
pass
  

'if' statements don't have to have an 'else' clause.
else:
   pass
is just a waste of 2 lines.  'pass' does nothing, and since the 'else' 
is not required, you may as well leave it off.

break
if '7' in keys:
move_to(player_shape,player_x*10 - 10,player_y*10 +10)
player_x = player_x -1
player_y = player_y + 1
if player_x < 1 or player_y > 47:
player_x = player_x+1
player_y = player_y-1
else:
pass
break
if '9' in keys:
move_to(player_shape,player_x*10 + 10,player_y*10 + 10)
player_x = player_x +1
player_y = player_y +1
if player_x > 63 or player_y >47:
player_x = player_x -1
player_y = player_y -1
else:
pass
break
if '4' in keys:
move_to(player_shape,player_x*10 - 10,player_y*10)
player_x = player_x - 1
if player_x < 1 :
player_x = player_x+1
else:
pass
break
if '5' in keys:
break
if '6' in keys:
move_to(player_shape,player_x*10+10,player_y*10)
player_x = player_x + 1
if player_x > 63:
player_x = player_x-1
else:
pass
break
if '1' in keys:
move_to(player_shape,player_x*10-10,player_y*10-10)
player_x = player_x -1
player_y = player_y -1
if player_x < 1 or player_y < 1:
player_x = player_x +1
player_y = player_y +1
else:
pass
break
if '2' in keys:
move_to(player_shape,player_x*10,player_y*10-10)
player_y = player_y -1
if player_y < 1:
player_y = player_y+1
else:
pass
break
if '3' in keys:
move_to(player_shape,player_x*10+10,player_y*10-10)
player_x = player_x +1
player_y = player_y -1
if player_x > 63 or player_y < 1:
player_x = player_x -1
player_y = player_y +1
else:
pass
break
  

This big block of movement code can be shortened into a few lines.
I am not sure how much python you know, so if any of this doesn't make 
sense, let me know.

Think of it this way:
step 1: look to see if they pressed a key that we want to process.
step 2: if so, figure out how we need to move the player (based on input)
step 3: check if this movement will move him out of bounds.
step 4: perform the movement.

Now that we have this pattern of evaluating our problem, we can reduce 
the code.

First, what kind of data structures are we going to need?
This is how I'm going to do it:
movement = {}
for x in range(3):
  for y in range(1,4):
   #this goes from 0 - 9, I was just too lazy to puzzle out a more 
efficient

   #way to do it.
   

Re: [Tutor] What exactly is [::-1]?

2007-07-25 Thread Luke Paireepinart
cuell wrote:
> In order to reverse the order of an array, I discovered that I'm 
> supposed to use [::-1]. 
>   
I don't know if 'supposed to' is the correct term.
You could just as easily get away with using ['a','b','c'].reverse().
However, below you're using 'array' and I'm not sure exacly what this is.
Does it have to do with the built-in array  module or one of the 
numeric/numpy variants?
>  >>> a = array([1., 2., 3.])
>  >>> a
> array([ 1.,  2.,  3.])
>  >>> a[::-1]
> array([ 3.,  2.,  1.])
>  >>>
>
> I would like to know what exactly the index notation of [::-1] is, where 
> it comes from and if there are other variants.
>   
This is called list slicing.  Look into it to figure out what all this 
stuff means.
I could send you a link but I'd just google 'python list slicing' to 
find it, so I'll leave that as an exercise for the reader.
> Thank you for your help.  I lurk about on this list and have learned a 
> fair bit.
>   
Good to hear :)
-Luke

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] What exactly is [::-1]?

2007-07-25 Thread cuell
In order to reverse the order of an array, I discovered that I'm 
supposed to use [::-1]. 

 >>> a = array([1., 2., 3.])
 >>> a
array([ 1.,  2.,  3.])
 >>> a[::-1]
array([ 3.,  2.,  1.])
 >>>

I would like to know what exactly the index notation of [::-1] is, where 
it comes from and if there are other variants.

Thank you for your help.  I lurk about on this list and have learned a 
fair bit.

-- 
Charles Cuell
[EMAIL PROTECTED]
http://math.usask.ca/~cuell

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Livewires questions

2007-07-25 Thread Luke Paireepinart
Tonu Mikk wrote:
> Thanks for offering to help!  I am following the Livewires exercise 
> (attached file "5-robots.pdf").  I have gotten as far as page 7.  
> Attached is also my code so far in robotsarecoming-teleport.py.
> Question 1.  I was checking for collision of a robot and player first 
> in this way:
>
> def check_collisions():
>if player_x == robot_x+0.5 and player_y == robot_y+0.5:
>   print 'You have been caught'
>
> This was working fine.  I then tried to create a definition like this:
>
> def collided():
>player_x == robot_x+0.5 and player_y == robot_y+0.5
I haven't looked at your code yet, but this doesn't seem like a very 
good way to check for collisions,
unless the player moves on a grid of 0.5 at a time, and you guarantee 
that you can check if the player collided with a robot on every move.
even so, doesn't this only collide with the robot if the player hits the 
bottom-right corner?
>
> and then check for collisions in this way (as in my code):
> def check_collisions():
>if collided() == 1:
>print 'You have been caught'
The reason this isn't working is because your function 'collided' 
doesn't return anything.
Consider this example:

def foo():
"Hello"

What do you expect to happen when you call foo()?
1) "Hello" won't be printed, because there is no 'print' statement here.
2) "Hello" won't be returned, because you have no return statement.
So what does happen, then?
well, foo() creates a string in memory with "Hello" stored in it, but 
there are no variables referenced to it, so nothing happens.
Basically, the only thing foo() accomplishes is that it wastes memory 
until "Hello" is garbage collected and deleted.

Now consider this:
def foo():
a == b and b == c

What do you expect to happen here?
It's similar to the above example.
a == b is evaluated.
if it's true, b == c is evaluated.
if it's true, then the value True is there, but it's not assigned to any 
variables, so it just disappears.
Can you see now why your code doesn't work?

Here's an example of a function you'd want to look at to give you an 
idea of what to do:

def foo():
  return a < b
> But this isn't printing out anything when the player and robot 
> collide.  I think I need to pass a variable of collided somehow, but I 
> am not sure how.  I also tried following:
> def check_collisions():
>if collided()
>   print 'You have been caught'
> but this isn't working either.
This is because collided() is not returning anything.
Try this:
print collided()
you will get this output:
None
>
> Question 2.  I created a if statement to check if the "t" key is 
> pressed on a keyboard.  If it is, I want the player to be placed on 
> another location on the grid.  However nothing happens when I press 
> the "t" key.  I am not sure why.
Instead of changing the player's location, print "YOU PRESSED T" 
instead, and if you see that in the console, you know there's a problem 
with your repositioning code.  If you don't see that, you know it's a 
problem with your input code.
If you can't diagnose further than that, let us know.
>
> Question 3.  I think there is something strange about how I check that 
> my player is within the boundaries of the grid.  When it gets close to 
> the edges of the grid, it can sometimes disappear past it even though 
> I thought I had prevented this from happening.
It's probably similar to the thing I was mentioning above.
Imagine that you have this case:
you're checking if the player is hitting 0.5, 0.5
now if the player can move by acceleration, etc... and you can't 
guarantee that it moves exactly in .5 increments, the player may very 
well move to the position .51,.51 and from there, to .49, .49 which 
would negate your test.
Even if you check a range of values (for example, 0.0 - 0.5 in the x 
axis and 0.0 - 0.5 in the y axis)
the player could theoretically jump right over this boundary (unless you 
restrict his maximum movement speed.)
The best way to check would be:
Say you have the player's coordinates
playerx, playery
and your player-permitted space is 0,0 to 1024, 768
I would suggest something like this:
newx, newy = (playerx + movex, playery + movey)
if newx >= 0 and newx < 1024:
playerx = newx
if newy >= 0 and newy < 768:
playery = newy

This will only allow the player to move to wherever he's moving IFF he's 
not moving out of bounds.
Otherwise, he just stays where he is.
Alternatively, you could check the boundaries, and if he's outside, set 
him to the boundary.
That way you could have the player walk right up to the wall, which 
isn't allowed in my code (depending how fast the player moves)
For example, if the player moves at 1.5, and he's at the position 1.4, 
he won't be able to move any closer to the wall.

>
>
> Thank you again for looking at this.  The attached bit of code has 
> taken a long time to create.  I admire all who can program :-).
Hey, I'm going to send this e-mail now, so everyone on the list (you 
included) will be able to rea

Re: [Tutor] How to determine if every character in one string is inanother string?

2007-07-25 Thread Kent Johnson
Alan Gauld wrote:
> "Terry Carroll" <[EMAIL PROTECTED]> wrote
> 
>>   if Y in X:
> 
> FWIW I believe that 'in' did only work for single characters up until
> version 2.X so your ideas may have been based on experiences with
> an earlier Python version.

Yes, it changed in Python 2.3.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Livewires Python course

2007-07-25 Thread Luke Paireepinart
Kent Johnson wrote:
> Tonu Mikk wrote:
>   
>> I also 
>> began reading and coding the Livewires course exercises 
>> (http://www.livewires.org.uk/python/).  I have gotten through the first 
>> 4 exercise, but got stuck with the last one where we build a robot 
>> game.  The Livewires coding exercise uses modules that can be downloaded 
>> from their website.  Would anyone be willing to install Livewires 
>> modules on their computer and assist me with the coding?  I have 
>> specific questions, but the code could be difficult to read because it 
>> takes advantage of the imported modules.
>> 
>
> Go ahead and post your questions. I have tried LiveWires (long ago!) and 
> there may be others on the list.
>   
Yes, but please next time you start a thread don't do it as a reply to 
another thread.
My e-mail client threw your e-mail in with the  'function declaration 
problems' thread,
which, if I had decided I didn't need to watch that thread anymore, 
would've resulted in your question getting overlooked.
So overall your questions get less exposure that way, as well as 
breaking the threading of some mail clients.

Let us know what specific questions you have.
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to determine if every character in one string is inanother string?

2007-07-25 Thread Alan Gauld

"Terry Carroll" <[EMAIL PROTECTED]> wrote

>   if Y in X:
>
> Which is much more elegant/pythonic; but I didn't know you could do 
> that
> with one string over another.  For some reason, I had thought Y 
> would have
> to exactly match one iterable element in X (e.g., one element of a 
> list,
> or one character of a string) for that to work.

FWIW I believe that 'in' did only work for single characters up until
version 2.X so your ideas may have been based on experiences with
an earlier Python version.

Alan G. 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to determine if every character in one string is inanother string?

2007-07-25 Thread Terry Carroll
On Tue, 24 Jul 2007, wesley chun wrote:

> i don't have any time myself either (getting ready for OSCON talk),
> but i'm not sure what terry's OP was about... looking for a
> well-written piece of code, a faster-performing snippet, or both?  i
> think he was just unsatissfied with his 1st attempt.

Exactly.  It worked fine, but just seemed unpythonic to me.

To use an analogy, not long ago I thought the best way to see if string X 
contained string Y was:

   if X.find(Y) != -1

Which works just fine.  But another poster pointed out:

   if Y in X:

Which is much more elegant/pythonic; but I didn't know you could do that
with one string over another.  For some reason, I had thought Y would have
to exactly match one iterable element in X (e.g., one element of a list,
or one character of a string) for that to work.

Similarly, I was thinking that while that first attempt of mine worked, 
its apparent-to-me lameness suggested that there was a more idiomatic 
approach, and I wanted to find out what that was.  

Seeing the different approaches put forward by the various contributors
was pretty interesting, though, I must say.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] function declaration problems perhaps?

2007-07-25 Thread Tiger12506
> By the way, this is an important and fundamental subject about
> Python.  When I teach classes on Python, I always need to explain
> Python's execution model, and I always struggle with it.  So,
> anything you can tell me that would help me teach this will be much
> appreciated.
>
> Dave

The way I keep it clear is simple. If python needs the value of the name (it 
has to look it up) then it had better be defined. Otherwise ~ It doesn't 
matter!

Think of it like assignment.
x = 1

Does python need to know the current value of x? No. Then x does not have to 
be previously defined.

f()

Does python need to know the current value of f? Yes. It has to know that f 
is a function, and where the address is, etc.

def f1():
  f()

Does python need to know the current value of f? No. Not until f1 is 
executed.

Does this help? Only one rule to remember. ;-) ~Does python need to know the 
value of _this_ variable?~

JS 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Livewires Python course

2007-07-25 Thread Kent Johnson
Tonu Mikk wrote:
> I also 
> began reading and coding the Livewires course exercises 
> (http://www.livewires.org.uk/python/).  I have gotten through the first 
> 4 exercise, but got stuck with the last one where we build a robot 
> game.  The Livewires coding exercise uses modules that can be downloaded 
> from their website.  Would anyone be willing to install Livewires 
> modules on their computer and assist me with the coding?  I have 
> specific questions, but the code could be difficult to read because it 
> takes advantage of the imported modules.

Go ahead and post your questions. I have tried LiveWires (long ago!) and 
there may be others on the list.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Livewires Python course

2007-07-25 Thread Tonu Mikk
Hello, I am at a very beginning on trying to learn Python.  So far I 
have read first few chapters of Alan Gauld tutorials, and completed all 
the exercises of Guido van Robot (http://gvr.sourceforge.net/).  I also 
began reading and coding the Livewires course exercises 
(http://www.livewires.org.uk/python/).  I have gotten through the first 
4 exercise, but got stuck with the last one where we build a robot 
game.  The Livewires coding exercise uses modules that can be downloaded 
from their website.  Would anyone be willing to install Livewires 
modules on their computer and assist me with the coding?  I have 
specific questions, but the code could be difficult to read because it 
takes advantage of the imported modules.

Thank you,
Tonu
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Logging module

2007-07-25 Thread Tiger12506
> I found the problem.  It was rather simple actually. I didn't have remote
> logging enabled for syslog.  Even though I was logging to localhost, for
> some reason, it wouldn't work until I gave syslogd a -r at startup. 
> Thanks

localhost is still remote, in that sockets are used to reach it. The 
implementation doesn't know the difference between 127.0.0.1 and 241.12.31.7 
because it's easier than making a special case.

JS 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Text matching and replacing

2007-07-25 Thread Tiger12506
> Cheers for the critique I'll take you points on board .especially
> this schoolboy error

It's not an error, really. It will work. Just... not intuitive
Errors are things that do not work.

> One thing to note about the re expression is that the products are not
>  these were just substitutes. In reality these are product
> names with no commonality e.g. ('baked beans'|'tuna'|'salad')
>
> So with that in mind is the way I have set the re way the best way or is
> there an another more pythonic way.

I can't tell you one way or the other, (and I have a hard time determining 
that which makes something more or less pythonic) but i have noticed that 
using re expressions for fixed patterns like that (no special identifiers, 
etc.) is considered overkill. It is easier to use string methods.

> As an aside I don't believe there were any tips in there to help solve
> the problems I have...again any help would be warmly appreciated.

However, the answer to your problem may be that you could rely on re 
expressions more than you are. What I like about regular expressions is the 
sheer power. Watch.

import re

teststring = """
Name: Jacob Schmidt
Address: 1234 Fake Street
City: Nowhere
State: Indiana
Zip Code: 14241

Name: Tiger Power
Address: 4321 Mysterious Lane
City: Jersey
State: Indiana
Zip Code: 14051-1390
"""

pat = re.compile(r".*Name: (.*)\nAddress: (.*)\nCity: (.*)\nState: (.*)\nZip 
Code: (\d{5}(?:-\d{4})?).*")

lst = pat.findall(teststring)
for x in lst:
print x
##


I'm sure this will help you some. :-)
JS



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] function declaration problems perhaps?

2007-07-25 Thread Bob Gailer
Alan Gauld wrote:
> "Kent Johnson" <[EMAIL PROTECTED]> wrote
>
>   
>>> Perl executes differently to Python in that it does a compilation
>>> stage before executing. Therefore Perl knows about all the function
>>> definitions prior to executing any code. Python compiles modules 
>>> which it imports
>>> but not scripts which it executes.
>>>   
>> Python compiles all scripts to bytecode.
>> 
>
> Doh! Yes of course it does, stoopid me.
>
>   
>> scripts. However this has no bearing on the current thread; for both
>> imported modules and executed scripts, a function must be defined 
>> before
>> it can be called.
>> 
>
> Yes, the bearing is in the way that Perl compiles its code.
> Perl builds a name tree from the entire file before executing
> so it doesn't rely on the order of definition, Python seems
> to compile and execute code in a sequential manner and
> therefore relies on the sequence being right.
>
> I'm not sure if the undefined name errors come from the compilation
> or from the execution - does anyone else. I confess i've never looked
> deeply into how Python actually does its complile/execute cycle.
>   
Compiling to bytecode raises syntax, deprecation and indentation errors. 
All others AKAIK are raised during execution
> Alan G. 
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


-- 
Bob Gailer
510-978-4454 Oakland, CA
919-636-4239 Chapel Hill, NC


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] function declaration problems perhaps?

2007-07-25 Thread Dave Kuhlman
On Wed, Jul 25, 2007 at 06:21:08PM +0100, Alan Gauld wrote:
> 
> I'm not sure if the undefined name errors come from the compilation
> or from the execution - does anyone else. I confess i've never looked
> deeply into how Python actually does its complile/execute cycle.
> 

A couple of points that might help:

1. In python it's all execution.  Yes, Kent is right that Python is
   compiled to byte code.  But, Alan is right to ignore that in
   trying to understand what happens.  In particular, "class" and
   "def" statements execute, and when they do they bind a name to a
   class or function object in the local namespace.

2. It's all about look-up.  Every variable reference causes Python
   to do a look-up in the current namespace (and enclosing
   namespaces, which is another subject).  So, you need to ask
   whether at that time a given name has been created in the
   current namespace.

Some examples ...

The following works because func2 is not called (looked up) until
func1 is executed, which is after func2 is defined:

# Test 1

def func1():
func2()

def func2():
print 'hello'

func1()

The following does *not* work, because func1 executes *before*
func2 is defined, which means that func2 is needed before it is
defined:

# Test 2

def func1():
func2()

func1()

def func2():
print 'hello'

And, (admittedly a rare case), the following does *not* work
because when the statement "class A(B)" executes, B is not yet
defined and is needed.  This is an example of a name (B) being
needed when another object (A) is defined (when the "class A(B)" is
executed):

# Test 3

class A(B):
pass

class B(object):
pass

By the way, this is an important and fundamental subject about
Python.  When I teach classes on Python, I always need to explain
Python's execution model, and I always struggle with it.  So,
anything you can tell me that would help me teach this will be much
appreciated.

Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] function declaration problems perhaps?

2007-07-25 Thread Kent Johnson
Alan Gauld wrote:
> "Kent Johnson" <[EMAIL PROTECTED]> wrote
>> scripts. However this has no bearing on the current thread; for both
>> imported modules and executed scripts, a function must be defined 
>> before
>> it can be called.
> 
> Yes, the bearing is in the way that Perl compiles its code.
> Perl builds a name tree from the entire file before executing
> so it doesn't rely on the order of definition, Python seems
> to compile and execute code in a sequential manner and
> therefore relies on the sequence being right.

It executes code in a sequential manner, and names are bound during 
execution, not compilation. That is the key difference. I guess you 
could say that the compiler doesn't forward any names to the execution 
phase; when a module starts executing, the only names in the module 
namespace are
['__builtins__', '__doc__', '__file__', '__name__']

You can see this if you import a module whose contents are just
print dir()

Any other names must be bound by executing code.

> I'm not sure if the undefined name errors come from the compilation
> or from the execution - does anyone else. I confess i've never looked
> deeply into how Python actually does its complile/execute cycle.

They come from execution. See my separate post about def, etc. being 
executable statements.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] function declaration problems perhaps?

2007-07-25 Thread Alan Gauld

"Kent Johnson" <[EMAIL PROTECTED]> wrote

>> Perl executes differently to Python in that it does a compilation
>> stage before executing. Therefore Perl knows about all the function
>> definitions prior to executing any code. Python compiles modules 
>> which it imports
>> but not scripts which it executes.
>
> Python compiles all scripts to bytecode.

Doh! Yes of course it does, stoopid me.

> scripts. However this has no bearing on the current thread; for both
> imported modules and executed scripts, a function must be defined 
> before
> it can be called.

Yes, the bearing is in the way that Perl compiles its code.
Perl builds a name tree from the entire file before executing
so it doesn't rely on the order of definition, Python seems
to compile and execute code in a sequential manner and
therefore relies on the sequence being right.

I'm not sure if the undefined name errors come from the compilation
or from the execution - does anyone else. I confess i've never looked
deeply into how Python actually does its complile/execute cycle.

Alan G. 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] function declaration problems perhaps?

2007-07-25 Thread Bob Gailer
Alan Gauld wrote:
> "nibudh" <[EMAIL PROTECTED]> wrote
>
>   
>> in perl this works:
>>
>> #!/usr/bin/env perl
>> hello("World");
>>
>> sub hello {
>>print "Hello ". $_[0] . "\n";
>> }
>> 
>
>
> Perl executes differently to Python in that it does a compilation 
> stage
> before executing. Therefore Perl knows about all the function 
> definitions
> prior to executing any code. Python compiles modules which it imports
> but not scripts which it executes.
>   
Not exactly. When Python imports a module that is new* it "compiles" it 
into bytecode. No recognition of names or objects takes place in this 
step. The bytecode is saved in a file with extension .pyc. Then Python 
executes the bytecode. Any function definitions that get executed create 
function objects that are available to subsequently executed code.

Running a script does exactly the same thing, except the bytecode is not 
saved in a file.

The bottom line is: a function definition must be executed before the 
function can be used. This is true of ANY Python object.

*new means that no .pyc file exists or the modification time of the .py 
is more recent than that of the .pyc.
>   
>> I have a vague recollection that ASP works in a similar way to 
>> python hence
>> the "hunch" i had earlier but i could be wrong. It's been a while 
>> since i've
>> done programming.
>> 
>
> Most interpreted languages work this way.
> Even the original versions of C worked that way although I thiunk more
> recent (ANSI/ISO compliant?) versions no longer need the strict 
> ordering,
> and Pascal also does it that way even though they are pure compiled
> languages. In the case of Pascal it is because Pascal is designed to
> be a single pass comilation language - which is why Borland's Object
> Pascal comiles so quickly in Delphi!
>
>   


-- 
Bob Gailer
510-978-4454 Oakland, CA
919-636-4239 Chapel Hill, NC


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] function declaration problems perhaps?

2007-07-25 Thread Kent Johnson
Alan Gauld wrote:
> "nibudh" <[EMAIL PROTECTED]> wrote
> 
>> in perl this works:
>>
>> #!/usr/bin/env perl
>> hello("World");
>>
>> sub hello {
>>print "Hello ". $_[0] . "\n";
>> }
> 
> 
> Perl executes differently to Python in that it does a compilation 
> stage
> before executing. Therefore Perl knows about all the function 
> definitions
> prior to executing any code. Python compiles modules which it imports
> but not scripts which it executes.

Python compiles all scripts to bytecode. For imported modules it saves 
the compiled bytecode in a .pyc file, but not for directly-executed 
scripts. However this has no bearing on the current thread; for both 
imported modules and executed scripts, a function must be defined before 
it can be called.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Logging module

2007-07-25 Thread jay

Thanks for the reply Kent.

I found the problem.  It was rather simple actually. I didn't have remote
logging enabled for syslog.  Even though I was logging to localhost, for
some reason, it wouldn't work until I gave syslogd a -r at startup.  Thanks

jay

On 7/25/07, Kent Johnson <[EMAIL PROTECTED]> wrote:


jay wrote:
> Hello,
>
> I'm trying to setup simple Syslog logging in python using the logging
> module.  I would like to use a config file, but so far haven't been able
> to get the correct configuration.  Actually, I don't get any warnings or
> errors, program runs fine, but nothing is logged anywhere.  I have my
> syslog LOCAL6 setup to go to /var/log/scripts.log, and that worked fine
> during testing of the syslog module.  But logging gives me more
> flexibility, I'd rather use that.
>
> Anyone with some experience using this module?  The documentation, at
> least to me, is a bit confusing, and I haven't found a good example on
> the web yet.

I haven't used logging config files, but I don't see anything obviously
wrong here. A couple of ideas to try:
- make sure logging.conf can be found by
   print os.path.exists('logging.conf')
- turn on console logging in the config file and see if that works
- try to configure the syslog handler in code instead of in a file, then
translate the successful configuration to a file.

Kent

>
> ---main.py---
> #!/usr/bin/env python
>
> import logging, logging.config
>
> logging.config.fileConfig('logging.conf')
>
> log = logging.getLogger()
> log.info('here we go, testing logger')
> --- end main.py ---
>
> --- logging.conf ---
> [formatters]
> keys: detailed,simple
>
> [handlers]
> keys: console,syslog
>
> [loggers]
> keys: root
>
> [formatter_simple]
> format: %(name)s:%(levelname)s:  %(message)s
>
> [formatter_detailed]
> format: %(name)s:%(levelname)s %(module)s:%(lineno)d:  %(message)s
>
> [handler_console]
> class: StreamHandler
> args: []
> formatter: simple
>
> [handler_syslog]
> class: handlers.SysLogHandler
> args: [('localhost', handlers.SYSLOG_UDP_PORT),
> handlers.SysLogHandler.LOG_LOCAL6 ]
> formatter: detailed
>
> [logger_root]
> level: INFO
> handlers: syslog
>
>  end logging.conf ---
>
> Thanks for any help!
>
> jay
>
>
> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] function declaration problems perhaps?

2007-07-25 Thread Alan Gauld
"nibudh" <[EMAIL PROTECTED]> wrote

> in perl this works:
>
> #!/usr/bin/env perl
> hello("World");
>
> sub hello {
>print "Hello ". $_[0] . "\n";
> }


Perl executes differently to Python in that it does a compilation 
stage
before executing. Therefore Perl knows about all the function 
definitions
prior to executing any code. Python compiles modules which it imports
but not scripts which it executes.

> I have a vague recollection that ASP works in a similar way to 
> python hence
> the "hunch" i had earlier but i could be wrong. It's been a while 
> since i've
> done programming.

Most interpreted languages work this way.
Even the original versions of C worked that way although I thiunk more
recent (ANSI/ISO compliant?) versions no longer need the strict 
ordering,
and Pascal also does it that way even though they are pure compiled
languages. In the case of Pascal it is because Pascal is designed to
be a single pass comilation language - which is why Borland's Object
Pascal comiles so quickly in Delphi!

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] comparing lists, __lt__ and __gt__

2007-07-25 Thread Kent Johnson
Andrew Purdea wrote:
> Hello!
>   I can see that lists have implemented these methods in jython..
>   But i can not find any documentation on this. It looks like python 
> compares each element, and and when it finds a difference, it returns.
>   Where can  i find documenation on this? Will this behaviour remain in 
> python for future releases?

Good question! The only doc I can find on this behavior is this:
http://docs.python.org/lib/comparisons.html

which just says that the comparison operation exists. There doesn't seem 
to be any documentation on how comparison works with sequences.

I think it is pretty safe to count on the current behaviour of < and > 
for lists. I'll put in a documentation bug on this - the meaning of 
these operations (and ==) should be explicit in the docs.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] comparing lists, __lt__ and __gt__

2007-07-25 Thread Bob Gailer
Andrew Purdea wrote:
> Hello!
>   I can see that lists have implemented these methods in jython..
>   But i can not find any documentation on this. It looks like python 
> compares each element, and and when it finds a difference, it returns.
>   Where can  i find documenation on this?
In python 2.5 reference 3.4.1:

*__lt__*(   self, other)


*__le__*(   self, other)


*__eq__*(   self, other)


*__ne__*(   self, other)


*__gt__*(   self, other)


*__ge__*(   self, other)

New in version 2.1. These are the so-called ``rich comparison''
methods, and are called for comparison operators in preference to
__cmp__() below. The correspondence between operator symbols and
method names is as follows: |xy| call
|x.__ne__(y)|, |x>y| calls |x.__gt__(y)|, and |x>=y| calls
|x.__ge__(y)|. These methods can return any value, but if the
comparison operator is used in a Boolean context, the return value
should be interpretable as a Boolean value, else a TypeError will be
raised. By convention, |False| is used for false and |True| for true.

There are no implied relationships among the comparison operators.
The truth of |x==y| does not imply that |x!=y| is false.
Accordingly, when defining __eq__(), one should also define __ne__()
so that the operators will behave as expected.

There are no reflected (swapped-argument) versions of these methods
(to be used when the left argument does not support the operation
but the right argument does); rather, __lt__() and __gt__() are each
other's reflection, __le__() and __ge__() are each other's
reflection, and __eq__() and __ne__() are their own reflection.

Arguments to rich comparison methods are never coerced. A rich
comparison method may return |NotImplemented| if it does not
implement the operation for a given pair of arguments.


> Will this behaviour remain in python for future releases?
I certainly hope so. A LOT of programs would suffer if not. I certainly 
have not seen any PEPs that discuss replacing or eliminating these.

-- 
Bob Gailer
510-978-4454 Oakland, CA
919-636-4239 Chapel Hill, NC


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] location of points in a covariance matrix

2007-07-25 Thread Bob Gailer
Beanan O Loughlin wrote:
> Hi all, I'm a meteorology postgrad working with python for the first time.
>
> I have found the location minimum in a large covariance matrix. this 
> value corresponds to the covariance of two points on a latitude, 
> longitude grid.
>
> I need to find a method to locate these two points on the lat,lon grid.
Usually multi-dimensional arrays are stored in "row-major" order. So the 
subscripts of an array of shape 2,3,4 (planes, rows. columns) would look 
like:
1,1,1  1,1,2  1,1,3 1,1 4  1,2,1  1,2,2  1,2,3  1,2,4  1,3,1  1,3,2  
1,3,3  1,3,4  2,1,1  2,1,2  2,1,3 2,1 4  2,2,1  2,2,2  2,2,3  2,2,4  
2,3,1  2,3,2  2,3,3  2,3,4

When you reshape it to 2,12 the elements remain "in place", and the 
subscripts now are:
1,1  1,2  1,3  1,4  1,5  1,6  1,7  1,8  1,9  1,10  1,11  1,12  2,1  2,2  
2,3  2,4  2,5  2,6  2,7  2,8  2,9  2,10  2,11  2,12

Is that enough of a hint?
>
> this is the code i have used, where 'se' is a 3-D array of data
>
>
> >>> nt,nlat,nlon = shape(se)   
> >>>nt,nlat,nlon# 3-D array of data taken 
> 1464 times, over 41 latitudes and 58 longitudes
> (1464, 41, 58)
> >>>
> >>>
> >>>m=reshape(se,(nt,nlat*nlon))# reshape to (time,latitude 
> longitude data point) where 2378 = 41*58
> >>>
> >>>shape(m)
> (1464,2378)
> >>>
> >>>
> >>>covmat=cov(m)   # calculate covariance matrix
> >>>
> >>>shape(covmat)
> (2378,2378)
>
> >>>def min(R):
>U = triu(R)  #just use one half of 
> the diagonal matrix
>n = U.shape[0]
>U.flat[::n+1] = 10.0#give the diagonal elements a 
> large value so they wont be selected
>k = argmin(U.flat)#find the min value of 
> the flattened array
>i, j = divmod(k,n) #calculate the index of 
> the minimum data
>return i, j, R[i,j]
>
> >>>
> >>> min(covmat)
> (7, 1914, -2.3016361721151051)
>
> so the minimum is found at (7,1914) in the covariance matrix and has a 
> value of - 2.3
>
> This min point corresponds to the covariance between two 'lat,lon' 
> data points in my (41,58) sample grid.
>
> Is there a way i can move back from my (2378,2378) covariance matrix 
> to see where these two points are located on the (41, 58) grid?
>
> Thank you very much in advance
>
> B.
>
> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


-- 
Bob Gailer
510-978-4454 Oakland, CA
919-636-4239 Chapel Hill, NC


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] function declaration problems perhaps?

2007-07-25 Thread nibudh

Hi Kent and Alan,

Thanks for the responses. It really got me thinking!

To test what i thought i knew, i wrote a "hello world" script in perl and
python.

in perl this works:

#!/usr/bin/env perl
hello("World");

sub hello {
   print "Hello ". $_[0] . "\n";
}

but in python:

#!/usr/bin/env python
hello('World')

def hello(name):
   print "Hello" + name

That doesn't.

I have a vague recollection that ASP works in a similar way to python hence
the "hunch" i had earlier but i could be wrong. It's been a while since i've
done programming.

I can see how the property of being executable (defs and imports) could be
handy, but right now I'm still getting to grips with the language proper.

Thanks again for the explanations and I'll keep them in mind as i experiment
some more with python.

nibudh.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Text matching and replacing

2007-07-25 Thread Gardner, Dean
 
Cheers for the critique I'll take you points on board .especially
this schoolboy error 

def findTestDirectories(path):
os.chdir(path)
directory_listing = os.listdir(os.getcwd())
--

Change this to
directory_listing = os.listdir(path)

Why look up the current directory when you have *just* set what it is?



One thing to note about the re expression is that the products are not
 these were just substitutes. In reality these are product
names with no commonality e.g. ('baked beans'|'tuna'|'salad')

So with that in mind is the way I have set the re way the best way or is
there an another more pythonic way.

As an aside I don't believe there were any tips in there to help solve
the problems I have...again any help would be warmly appreciated.

Cheers

Dean

Message: 3
Date: Tue, 24 Jul 2007 14:18:46 -0500
From: "Tiger12506" <[EMAIL PROTECTED]>
Subject: Re: [Tutor] Text matching and replacing
To: 
Message-ID: <[EMAIL PROTECTED]>
Content-Type: text/plain; format=flowed; charset="iso-8859-1";
reply-type=original

def findTestDirectories(path):
os.chdir(path)
directory_listing = os.listdir(os.getcwd())
--

Change this to
directory_listing = os.listdir(path)

Why look up the current directory when you have *just* set what it is?


test_record_directories = []
for directory in directory_listing:
if "TestRecords" in directory:
test_record_directories.append(directory)
--
This whole block could be turned into a list comprehension

test_record directories = [di for di in directory_listing if
"TestRecords" 
in di]

-
return test_record_directories

def findProductFromComments(records_from_record_file):
'''
Attempt to find products run against in the comment field
if we find one. Write it to the newly created product run field
'''

searchText = re.compile(r'(|||)', re.IGNORECASE)
---
Woah! Regular expression could use work.
Try:

re.compile(r'', re.IGNORECASE)

This will match product #s 1-9
If you want to match all product numbers to infinity put a * after \d

--
for record in records_from_record_file:
if searchText.findall(record) !=[]:
---
if searchText.findall(record):

is sufficient
-
print record.split("\n\n")

def amendProductField(dir):
fileList = os.listdir(dir)
currPath =  os.getcwd()+"\\"+dir+"\\"

This could be

currPath = os.path.join(os.getcwd(), dir)

--
dict_of_amended_records = {}
list_of_amended_records = []
for file in fileList:
if "CVS" in file:
pass
else:
f = open(currPath+"\\"+file)
---
And again ~

f = open(os.path.join(currPath,file))
--
if debug:
print "opening %s for reading" %file
fileContents = f.read()
fileContents = fileContents.split("\n\n")
findProductFromComments(fileContents)
for record in fileContents:

record+="\nProductRun:\n\n"
list_of_amended_records.append(record)
dict_of_amended_records[file] = list_of_amended_records
list_of_amended_records = []
#writeUpdatedRecordsToFile(currPath,dict_of_amended_records)


test_dir = findTestDirectories("C:\\Sandbox")
if debug:
print "Opening %s for amending" %test_dir[0]

#for directory in test_dir:
#amendProductField(directory)
amendProductField(test_dir[0])

Current Record:

TestedDate: 2005-04-30
TestId: 001591
Branch: 
Version: 3351
SpecId: Specification--0966
Cpu: Pentium 4
OperatingSystem: Windows 2000
CpuCount: Single
Tester: someone
Comment: Run on 
MinutesTaken: 5
PassOrFail: Pass

Desired Record:

TestedDate: 2005-04-30
TestId: 001591
Branch: 
Version: 3351
SpecId: Specification--0966
Cpu: Pentium 4
OperatingSystem: Windows 2000
CpuCount: Single
Tester: someone
Comment: Run on 
MinutesTaken: 5
PassOrFail: Pass
Product: 


Dean Gardner





DISCLAIMER:
Unless indicated otherwise, the information contained in this message is
privileged and confidential, and is intended only for the use of the
addressee(s) named above and others who have been specifically
authorized to receive it. If you are not the intended recipient, you are
hereby notified that any dissemination, distribution or copying of this
message and/or attachments is strictly prohibited. The company accepts
no liability for any damage caused by any virus transmitted by this
email. Furthermore, the company does not warrant a proper and complete
transmission of this information, nor does it accept liability for any
delays. If you have received this message in error, please contact t

Re: [Tutor] Logging module

2007-07-25 Thread Kent Johnson
jay wrote:
> Hello,
> 
> I'm trying to setup simple Syslog logging in python using the logging 
> module.  I would like to use a config file, but so far haven't been able 
> to get the correct configuration.  Actually, I don't get any warnings or 
> errors, program runs fine, but nothing is logged anywhere.  I have my 
> syslog LOCAL6 setup to go to /var/log/scripts.log, and that worked fine 
> during testing of the syslog module.  But logging gives me more 
> flexibility, I'd rather use that.
> 
> Anyone with some experience using this module?  The documentation, at 
> least to me, is a bit confusing, and I haven't found a good example on 
> the web yet.

I haven't used logging config files, but I don't see anything obviously 
wrong here. A couple of ideas to try:
- make sure logging.conf can be found by
   print os.path.exists('logging.conf')
- turn on console logging in the config file and see if that works
- try to configure the syslog handler in code instead of in a file, then 
translate the successful configuration to a file.

Kent

> 
> ---main.py---
> #!/usr/bin/env python
> 
> import logging, logging.config
> 
> logging.config.fileConfig('logging.conf')
> 
> log = logging.getLogger()
> log.info('here we go, testing logger')
> --- end main.py ---
> 
> --- logging.conf ---
> [formatters]
> keys: detailed,simple
>  
> [handlers]
> keys: console,syslog
>  
> [loggers]
> keys: root
>  
> [formatter_simple]
> format: %(name)s:%(levelname)s:  %(message)s
>  
> [formatter_detailed]
> format: %(name)s:%(levelname)s %(module)s:%(lineno)d:  %(message)s
>  
> [handler_console]
> class: StreamHandler
> args: []
> formatter: simple
>  
> [handler_syslog]
> class: handlers.SysLogHandler
> args: [('localhost', handlers.SYSLOG_UDP_PORT), 
> handlers.SysLogHandler.LOG_LOCAL6 ]
> formatter: detailed
>  
> [logger_root]
> level: INFO
> handlers: syslog
> 
>  end logging.conf ---
> 
> Thanks for any help!
> 
> jay
> 
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] function declaration problems perhaps?

2007-07-25 Thread Kent Johnson
Alan Gauld wrote:
> "nibudh" <[EMAIL PROTECTED]> wrote
> 
>> I looked over my code (all 41 lines!) and couldn't find anything, 
>> then on a
>> hunch i moved the def statement _above_ the rest of my code and hey 
>> presto
>> it worked.
>>
>> I vaguely understand why this is happening, but can someone explain 
>> it to
>> me.
> 
> Its pretty simple.
> Python processes the file top to bottom. If it comes upon
> a name that it doesn't recofgnise it generates an error.

A key concept to understand is that def (and class and import) are 
executable statements that have no effect until they are actually 
executed. The effect of executing a def is to create a function object 
and bind it to the name given in the def. Before the def is executed, 
the name is not bound to anything and can't be used.

This is a shift from less-dynamic languages such as Java and C, where 
functions exist from the time a module is loaded.

One consequence of executable def is that you can, for example, have 
conditional defs:
if has_foo:
   def bar():
 # Implementation of bar using foo
else:
   def bar():
 # Implementation of bar without using foo

Similar techniques can be used with imports. This can be handy for 
writing code that is backwards compatible. For example here is some code 
that tries to import ElementTree from its Python 2.5 library package and 
from the effbot distribution:

try:
 import xml.etree.ElementTree as ET # in python >=2.5
except ImportError:
 try:
 import elementtree.ElementTree as ET # effbot's pure Python module
 except ImportError:
 raise ImportError("Can't import ElementTree")

If this code successfully executes, the ElementTree module will be 
available as ET.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] comparing lists, __lt__ and __gt__

2007-07-25 Thread Andrew Purdea

Hello!
 I can see that lists have implemented these methods in jython..
 But i can not find any documentation on this. It looks like python
compares each element, and and when it finds a difference, it returns.
 Where can  i find documenation on this? Will this behaviour remain in
python for future releases?
 Thanks
   Regards, Andrew
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] function declaration problems perhaps?

2007-07-25 Thread Alan Gauld

"nibudh" <[EMAIL PROTECTED]> wrote

> I looked over my code (all 41 lines!) and couldn't find anything, 
> then on a
> hunch i moved the def statement _above_ the rest of my code and hey 
> presto
> it worked.
>
> I vaguely understand why this is happening, but can someone explain 
> it to
> me.

Its pretty simple.
Python processes the file top to bottom. If it comes upon
a name that it doesn't recofgnise it generates an error.
Thus:


#

print foo(42)

def foo(x):
return x * 2

##

will generate an error because at the point  where the print
statement tries to execute foo(42), foo does not exist!

This is one good reason to avoid putting executable code in the
main body of a file but to always wrap it in a function like so:

##

def main()
print foo(42)

def foo(x):
return x * 2

if __name__ == "__main__": main()

###

Now the code doesn't get executed until the last line of the file
by which time all definitions have been executed and the
program will work correctly.

This also makes the module inherently more reusable since it
can be imported without the main code being executed (the purpose
of the if expression.)

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] function declaration problems perhaps?

2007-07-25 Thread nibudh

Hi list,

I've just been writing a small script to parse some xml files and output tab
separated values into a separate file.

I was surprised to see that my function "processXML(fpart)" was failing with
an error along the lines of "processXML not defined"

I looked over my code (all 41 lines!) and couldn't find anything, then on a
hunch i moved the def statement _above_ the rest of my code and hey presto
it worked.

I vaguely understand why this is happening, but can someone explain it to
me.

If this makes no sense then tell me that too :-)

cheers,

nibudh.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor