Re: [Tutor] trouble with if

2007-10-26 Thread Alan Gauld
"Bryan Fodness" <[EMAIL PROTECTED]> wrote

>I cannot get this to work either.

Brian, when you post please tell us exactly what does not work.
If there is an error message send the whole error there is a lot
of useful information in them. Otherwise we have to read your
code and guess what might be happening. We need both code
and error text. The easier you make it for the tutors the more
likely you are to get a response!

> woffaxis = 7
>
> if woffaxis != 0:
> woaf_pos = input("What is Wedge Direction (N/A, Lateral, Towards 
> Heal,
> Towards Toe)?")

Use raw_input() and convert the result rather than input().
Especially when the input is a string anyhow. Otherwise
you are leaving yourself open to scurity breaches and even
accidental damage to your data due to mistyping. This is
because input() tries to interpret its value as a Python
expression. Thus if the user enters a string Pyhon tries to
evaluate that string. Unless the usser has put quotes
around their input it will probably fail. I suspect that is
your problem but without an error message I can't be sure.

> if woaf_pos == 'Towards Toe':
> woffaxis = woffaxis
> elif woaf_pos == 'Towards Heal':
> woffaxis = (woffaxis * -1)
> else:
> woffaxis = 0

Incidentally, you could replace this set of if statements
with a dictionary lookup:

responses = {"Towards Toe": 1, "Towards Head": -1}
woffaxis *= responses.get(woaf_pos,0)

Another tip is that when comparing user input to a
string its usually better to have the master strings
as all uppercase or all lowercase and then convert
the input string to all lower case or all upper case
as appropriate, and then compare.

It reduces user frustration over simple typos.

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


Re: [Tutor] about Tix

2007-10-26 Thread Alan Gauld
Linda,

>I run the following code in Python 2.5 and got the error (when I do
> "import Tix", no error).

Congratulations I think this might just be the first Tix question
on the tutor list! :-)

> Traceback (most recent call last):
>  File "2.py", line 54, in 
>tkRoot = Tix.Tk( )
>  File 
> "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tix.py",
> line 210, in __init__
>self.tk.eval('package require Tix')
> _tkinter.TclError: can't find package Tix

This looks to me like the Tix DLL hasn't been installed or it's
installed in a folder where it can''t be found. The Tix module
is just a wrapper round the Tix DLL so you need both.

It works OK for me:

>>> import Tix as t
>>> tk = t.Tk()
>>> w = t.Toplevel(tk)
>>> b = t.Label(w, text="Hello")
>>> b.pack()
>>> t.mainloop()

However,

> from __future__ import with_statement   # <-- Python 2.5 ONLY
> import Tix
> import time
>
> class SplashScreen( object ):
...
> #
> # Now putting up splash screens is simple
>
> # Create the tkRoot window
> tkRoot = Tix.Tk( )
>
> with SplashScreen( tkRoot, 'splashImage.jpg', 3.0 ):

I'm not sure you need the with statement here.
(Although this might also be the first tutor example of a
custom context manager! Two firsts in one mail...:)

Couldn't you just call the SplashScreen directly?
Then initialise and build the GUI? Its what I usually
do and it seems to work. I'm trying to work out what
advantage the with gives?

>   initializeMyApplication( )
>   buildTheGUI( tkRoot )
>
> tkRoot.mainloop( )

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


Re: [Tutor] How to implement function like this?

2007-10-26 Thread Kent Johnson
Ricardo Aráoz wrote:
> Kent Johnson wrote:
>> funcB(len(a)-L) does not do what the OP requested. For example if len(a)
>> is 10, L will be 3 and you will call funcB(7).
>>
> 
> Don't get it. The 3 is because the len(a) is 3, notice that a is hard
> coded and not a parameter. If you change 'a' then you should change the
> code accordingly.

Right, my mistake.

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


Re: [Tutor] Looking for suggestions for improving chessTimer.py code

2007-10-26 Thread Dick Moores
At 09:33 AM 10/25/2007, Dick Moores wrote:
>Please give me constructive criticism of
>

Hmm. Nothing. One problem may be that only people using Windows can 
run the script.

I've developed chessTimer a bit further: 


I'm still hoping for some constructive criticism. But I also thought 
I'd mention the points I have doubts about:
1. Is wrapping the long lines where I have done so OK?
2. I've used 1 for White player, -1 for Black player, and (-1)*player 
to alternate players. Is there a better way?
3. I've used a lot of variables. Too Many?
4. Should more of the code be in functions?
5. Is there a way to collapse lines 107-114:
if player == 1: # player is White
 whiteMoveCounter += 1
 print "Black to make move %d" % (blackMoveCounter)
 remainingWhiteTime -= timeUsedThisMove
elif player == -1: # player is Black
 blackMoveCounter += 1
 print "White to make move %d" % (whiteMoveCounter)
 remainingBlackTime -= timeUsedThisMove


Thanks,

Dick Moores


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


Re: [Tutor] Using dictionary to find the mode of a list

2007-10-26 Thread Kent Johnson
Conor Leister wrote:
> I'm just trying to get the mode of a list.
> Here's the code I have that gathers the data and sorts it.  i just need 
> to be able to get the mode of a using a dictionary and i can't seem to 
> figure out anything. i'm completely lost. this code works fine, i just 
> need to add to it and i'm not great with dictionaries.

OK. The mode is the number that appears the most times, so you need to 
count how many times each number appears. A dict works well for this; 
the dict key is the number and the dict value is the count. Can you 
write a loop through your list that accumulates counts? The next step is 
to find the largest count.

Kent

> 
> #gather data
> a=[]
> prompt='Enter numbers, blank line to finish:'
> inVal=raw_input(prompt)
> while inVal:
> a.append(int(inVal))
> inVal=raw_input(prompt)
> print 'The values you entered:'
> print a
> 
> #Bubble Sort
> i=0
> while i j=1
> while j if a[j-1]>a[j]:
> temp=a[j]
> a[j]=a[j-1]
> a[j-1]=temp
> j=j+1
> i=i+1
> print 'Values sorted: ' ,a
> 
> 
> 
> 
> ___
> 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] Looking for suggestions for improving chessTimer.py code

2007-10-26 Thread bhaaluu
Greetings,

On 10/26/07, Dick Moores <[EMAIL PROTECTED]> wrote:
> At 09:33 AM 10/25/2007, Dick Moores wrote:
> >Please give me constructive criticism of
> >
>
> Hmm. Nothing. One problem may be that only people using Windows can
> run the script.

The first thing I saw when I looked at the code was that it was
for MS-Windows only, so I didn't waste anymore time with it.

Recently, I ran across some code that tried MS-Windows, except
if the user wasn't running MS-Windows, it assumed they were
running some *nix variant, and loaded those modules instead.
That certainly makes code more platform independent.

This is what it looked like:
try:
# windows or dos
import msvcrt
getkey = msvcrt.getch
except ImportError:
# assume unix
import tty, termios

Since Python doesn't come bundled with MS-Windows, out-of-the-box,
I don't think we should presume that "everyone" has Python on their
MS-Windows computer? OTOH, Python is usually part of the base or
core system on a GNU/Linux install. I'm not sure about Mac OS X.x?

Of course, if you only want MS-Windows users to run your code, then
nevermind! 8^D

I'm still working my way through Python tutorials, and as yet, haven't
written any code that makes use of any platform specific libraries.
However, when I DO, and IF I forget to try:except: so other platforms
can run my code, Please Slap Me, and show me THIS post! =)

That being said:
Besides msvcrt/curses, what other libraries are there that we should
be aware of? I'd like to see them as pairs, if possible this looks
like a perfect thing for a dictionary! =)

I certainly think this is something that Newbies (like myself) should learn.
But without a MS-Windows computer handy, I don't know? Is there a
place that has this information?

Happy Programming!
-- 
b h a a l u u at g m a i l dot c o m
http://www.geocities.com/ek.bhaaluu/index.html


>
> I've developed chessTimer a bit further:
> 
>
> I'm still hoping for some constructive criticism. But I also thought
> I'd mention the points I have doubts about:
> 1. Is wrapping the long lines where I have done so OK?
> 2. I've used 1 for White player, -1 for Black player, and (-1)*player
> to alternate players. Is there a better way?
> 3. I've used a lot of variables. Too Many?
> 4. Should more of the code be in functions?
> 5. Is there a way to collapse lines 107-114:
> if player == 1: # player is White
>  whiteMoveCounter += 1
>  print "Black to make move %d" % (blackMoveCounter)
>  remainingWhiteTime -= timeUsedThisMove
> elif player == -1: # player is Black
>  blackMoveCounter += 1
>  print "White to make move %d" % (whiteMoveCounter)
>  remainingBlackTime -= timeUsedThisMove
>
>
> Thanks,
>
> Dick Moores
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How can isfile really do what it claims

2007-10-26 Thread Sandip Bhattacharya
$ ls -l /usr/lib/xulrunner/libfreebl3.so
lrwxrwxrwx 1 root root 20 2007-10-20 12:13 /usr/lib/xulrunner/libfreebl3.so -> 
../nss/libfreebl3.so

$ python
Python 2.5.1 (r251:54863, Oct  5 2007, 13:36:32) 
[GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os.path
>>> os.path.isfile("/usr/lib/xulrunner/libfreebl3.so")
True
>>> print os.path.isfile.__doc__
Test whether a path is a regular file


Is this because isfile follows symlinks? If that is the case, 
how can I NOT make it do that?

- Sandip

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


Re: [Tutor] How can isfile really do what it claims

2007-10-26 Thread Kent Johnson
Sandip Bhattacharya wrote:
> $ ls -l /usr/lib/xulrunner/libfreebl3.so
> lrwxrwxrwx 1 root root 20 2007-10-20 12:13 /usr/lib/xulrunner/libfreebl3.so 
> -> ../nss/libfreebl3.so
> 
> $ python
> Python 2.5.1 (r251:54863, Oct  5 2007, 13:36:32) 
> [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 import os.path
 os.path.isfile("/usr/lib/xulrunner/libfreebl3.so")
> True
 print os.path.isfile.__doc__
> Test whether a path is a regular file
> 
> 
> Is this because isfile follows symlinks?

Yes; from the full docs:
isfile( path)
 Return True if path is an existing regular file. This follows 
symbolic links, so both islink() and isfile() can be true for the same 
path.

  If that is the case,
> how can I NOT make it do that?

def isfile(path):
 return not os.path.islink(path) and os.path.isfile(path)

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


[Tutor] Pythonic way to "try a few times, then raise exception"?

2007-10-26 Thread Allen Fowler
Hello,

I have a block of code buried deep in a module  that I expect to fail 
periodically. (Calls to other machines over slow network, and such.)

Generally, though,  trying it a second / third will work.

Is there clean way to write this on Python?

Thanks

 __
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com ___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Looking for suggestions for improving chessTimer.py code

2007-10-26 Thread Alan Gauld

"bhaaluu" <[EMAIL PROTECTED]> wrote

> I certainly think this is something that Newbies (like myself) 
> should learn.
> But without a MS-Windows computer handy, I don't know? Is there a
> place that has this information?

The Module documentation tells you which platforms are supported.
But its more than modules. Some functions within modules work
differently (or not at all!) on different OS platforms.

Anything that is OS specific like sound, video, input/output
handling etc will likely have platform restrictions. However many
of these differences can be avoided by using higher level toolkits
like PyGame, PIL, wxWindows etc. They abstract the interfaces
to a common form and hide the differences internally. But usually
at the cost of some flexibility, power or resource usage(memory/speed)

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


Re: [Tutor] Pythonic way to "try a few times, then raise exception"?

2007-10-26 Thread Alan Gauld
"Allen Fowler" <[EMAIL PROTECTED]> wrote

> I have a block of code buried deep in a module  
> that I expect to fail periodically. 
> (Calls to other machines over slow network, and such.)
> 
> Generally, though,  trying it a second / third will work.
> 
> Is there clean way to write this on Python?

There was a thread on this a few days ago but I can't find it now...

In general if you only have a few (eg hundreds) things to 
check you can run a loop inside a loop and exit it with break
if it works. Pdeudo code:

for item in list:
for attempt in range(3):
 result = accessItem(item)
 if result == OK: break
 else: sleep(T)   # optional pause to regroup if needed...
else: logError(item)

But I'm not sure if that's what you count as clean!

If the volumes being processed it is usually better to 
gather the failures up for seondary processing after 
getting through the successful ones. This is a much 
more efficient way of handling high data volumes.

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


Re: [Tutor] Pythonic way to "try a few times, then raise exception"?

2007-10-26 Thread johnf
On Friday 26 October 2007 03:17:47 pm Alan Gauld wrote:
> "Allen Fowler" <[EMAIL PROTECTED]> wrote
>
> > I have a block of code buried deep in a module
> > that I expect to fail periodically.
> > (Calls to other machines over slow network, and such.)
> >
> > Generally, though,  trying it a second / third will work.
> >
> > Is there clean way to write this on Python?
>
> There was a thread on this a few days ago but I can't find it now...
>
> In general if you only have a few (eg hundreds) things to
> check you can run a loop inside a loop and exit it with break
> if it works. Pdeudo code:
>
> for item in list:
> for attempt in range(3):
>  result = accessItem(item)
>  if result == OK: break
>  else: sleep(T)   # optional pause to regroup if needed...
> else: logError(item)
>
> But I'm not sure if that's what you count as clean!
>
> If the volumes being processed it is usually better to
> gather the failures up for seondary processing after
> getting through the successful ones. This is a much
> more efficient way of handling high data volumes.
>
> HTH

What about placing the "try" in a function and call the function from a loop 
passing the variable to check (computer name).  Then each failure will not 
cause the app to stop processing.  Use a counter in the calling procedure to 
the number of attempts.

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


Re: [Tutor] Looking for suggestions for improving chessTimer.py code

2007-10-26 Thread Dick Moores
At 05:00 AM 10/26/2007, bhaaluu wrote:
>Greetings,
>
>On 10/26/07, Dick Moores <[EMAIL PROTECTED]> wrote:
> > At 09:33 AM 10/25/2007, Dick Moores wrote:
> > >Please give me constructive criticism of
> > >
> >
> > Hmm. Nothing. One problem may be that only people using Windows can
> > run the script.
>
>The first thing I saw when I looked at the code was that it was
>for MS-Windows only, so I didn't waste anymore time with it.
>
>Recently, I ran across some code that tried MS-Windows, except
>if the user wasn't running MS-Windows, it assumed they were
>running some *nix variant, and loaded those modules instead.
>That certainly makes code more platform independent.
>
>This is what it looked like:
>try:
> # windows or dos
> import msvcrt
> getkey = msvcrt.getch
>except ImportError:
> # assume unix
> import tty, termios

OK, here's a short script, which runs fine on Windows. What do I add 
to have it run on unix as well?

#!/usr/bin/env python
#coding=utf-8

try:
 # windows or dos
 import msvcrt
 while True:
 if msvcrt.kbhit():
 key = msvcrt.getch()
 if key == "h":
 print "Hello, World!"
 break
 print "Bye, World!"

except ImportError:
 # assume unix
 import tty, termios

Dick

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


[Tutor] Error 403 when accessing wikipedia articles?

2007-10-26 Thread Alex Ryu
Hi all
I'm trying to use python to automatically download and process a (small)
number of wikipedia articles.  However, I keep getting a 403 (Forbidden
Error), when using urllib2:

>>> import urllib2
>>> ip = urllib2.urlopen("http://en.wikipedia.org/wiki/Pythonidae";)
which gives this:

Traceback (most recent call last):
  File "", line 1, in 
ip = urllib2.urlopen("http://en.wikipedia.org/wiki/Pythonidae";)
  File "G:\Python25\lib\urllib2.py", line 121, in urlopen
return _opener.open(url, data)
  File "G:\Python25\lib\urllib2.py", line 380, in open
response = meth(req, response)
  File "G:\Python25\lib\urllib2.py", line 491, in http_response
'http', request, response, code, msg, hdrs)
  File "G:\Python25\lib\urllib2.py", line 418, in error
return self._call_chain(*args)
  File "G:\Python25\lib\urllib2.py", line 353, in _call_chain
result = func(*args)
  File "G:\Python25\lib\urllib2.py", line 499, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 403: Forbidden

Now, when I use urllib instead of urllib2, something different happens:

>>> import urllib
>>> ip2 = urllib.urlopen("http://en.wikipedia.org/wiki/Pythonidae";)
>>> st = ip2.read()

However, st does not contain the hoped-for page - instead it is a page of
html and (maybe?) javascript, which ends in:

>If reporting this error to the Wikimedia System Administrators, please
include the following >details:\n\nRequest: GET
http://en.wikipedia.org/wiki>/Pythonidae,
from 98.195.188.89 via sq27.wikimedia.org (squid/2.6.STABLE13) >to
>()\nError: ERR_ACCESS_DENIED, errno [No Error] at Sat, 27 Oct 2007
06:45:00 >GMT\n\n\n\n\n\n'

Could anybody tell me what's going on, and what I should be doing
differently?
Thanks for your time
Alex
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor