Re: [Tutor] read from standard input

2008-02-13 Thread John Fouhy
On 14/02/2008, Andrei Petre <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I want to read from the standard input numbers until i reach a certain value
> or to the end of the "file".
> What is the simplest, straightforward, pythonic way to do it?
>
> a sketch of how i tried to do it:
> [code]
> while 1 < 2:
> x = raw_input()
> if type(x) != int or x == 11:
> break
> else:
> print x
>  [/code]

This won't work because raw_input() always returns a string.  The
pythonic way to make that code work is:

while True:
  raw_x = raw_input()
  try:
x = int(raw_x)
  except ValueError:
break
  if x == 11:
break
  print x

(actually, you would be better giving x an initial value and then
writing 'while x != 11' ..)

> but don't work. and i'm interest in a general way to read until it is
> nothing to read.

sys.stdin is a file-like object corresponding to standard in.  You can do this:

import sys
special = 11
for line in sys.stdin:
  try:
x = int(line)
  except ValueError:
print 'Bad input.'
break
  if x == special:
print 'Special value reached.'
break
else:
  print 'End of input reached.'

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


[Tutor] read from standard input

2008-02-13 Thread Andrei Petre
Hello,

I want to read from the standard input numbers until i reach a certain value
or to the end of the "file".
What is the simplest, straightforward, pythonic way to do it?

a sketch of how i tried to do it:
[code]
while 1 < 2:
x = raw_input()
if type(x) != int or x == 11:
break
else:
print x
[/code]

but don't work. and i'm interest in a general way to read until it is
nothing to read.


to ilustrate that in C:
[code]
int x;
while( scanf("%d",&x) == 1 && x != 11)
 printf("%d\n", x);
[/code]


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


Re: [Tutor] Binary chop function - this works, but I'm not sure why

2008-02-13 Thread Chris Fuller
On Wednesday 13 February 2008 18:49, Arun Srinivasan wrote:
> I'm trying to learn Python, and I decided to try kata 2  from the
> CodeKate website. It's basically just a challenge to implement a binary
> search in different ways.
>
> I wrote an implementation that works, but I'm confused as to why.
>
> def chop(search_int, sorted_list):

> if len(sorted_list) == 1 or 2:

This condition is always true.  You meant to say:  len(sorted_list) == 1 or 
len(sorted_list) == 2"

or: "len(sorted_list) in 1,2"

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


[Tutor] Binary chop function - this works, but I'm not sure why

2008-02-13 Thread Arun Srinivasan
I'm trying to learn Python, and I decided to try kata 2  from the
CodeKate website. It's basically just a challenge to implement a binary
search in different ways.

I wrote an implementation that works, but I'm confused as to why.

def chop(search_int, sorted_list):
if len(sorted_list) == 1 or 2:
for x in sorted_list:
if x == search_int:
return sorted_list.index(x)
return -1

midpoint = (len(sorted_list) - 1) / 2
mp_value = sorted_list[midpoint]

if mp_value == search_int:
return midpoint
elif mp_value > search_int:
return chop(search_int, sorted_list[:midpoint])
else:
return chop(search_int, sorted_list[midpoint + 1:])

Basically, it only returns the index if it matches in the if statement at
the beginning of the function, but since that is limited to lists of length
2 or 1, why doesn't it return only 0 or 1 as the index? I think there is
something about recursion here that I'm not fully comprehending.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Change dictionary value depending on a conditional statement.

2008-02-13 Thread Terry Carroll
I don't think I saw anyone point this out yet, but, using "list" as a
variable name is a bad idea, because it hides the list method.

>>> x = list("abcdefg")
>>> x
['a', 'b', 'c', 'd', 'e', 'f', 'g']

This works.  You now have a variable named "x" that is a list.

>>> list = list("hijklmnop")
>>> list
['h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']

This works, sort of.  You now have a variable named "list" that is a list. 
But since you reused the name "list," it can no longer point to the list 
function.

>>> y = list("qrstuv")
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'list' object is not callable

And so this fails.




On Tue, 12 Feb 2008, Norman Khine wrote:

> Thank you all, very nice.
> 
> Steve Willoughby wrote:
> > Kent Johnson wrote:
> >> Try
> >>list.append({'id': 'name', 'link': ('YY','XX')[total > 0]})
> > 
> > I'd caution against that, though.  It's clever and cute, sure, but the 
> > meaning of it is obfuscated enough to be unpythonic because [total > 0] 
> > as a subscript doesn't mean anything unless you know you're taking 
> > advantage of an implementation detail that booleans are 0 for false and 
> > 1 for true.  No matter how reliable that fact may be, I don't think that 
> > value should be stuck into a numeric context like that.
> > 
> >> Or, in Python 2.5,
> >>list.append({'id': 'name', 'link': ('XX' if total > 0 else 'YY')})
> > 
> > This is much more clear, and would IMHO be fine.
> > 
> > 
> > 
> > ___
> > 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 maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Understanding the ImageDraw Options

2008-02-13 Thread Alan Gauld

"Wayne Watson" <[EMAIL PROTECTED]> wrote

Caveat, I've never used ImageDraw

>I started getting acquainted with the ImageDraw class (Object). 
>  My question
> here is are there more detailed explanations somewhere
> for the options?

There is an Options section on the page linked which describes
the available options:

Options #
outline
outline integer or tuple

fill
fill integer or tuple

font
font ImageFont instance

> It gives no idea what the choices are for options in the argument 
> list.

I believe its intended to be any of the standard options that are
applicable, for lines that would just be fill. (Although a note 
suggests
a new width option which is not listed under options!)

I agree the documentation is limited but unfortunately thats one of
the common penalties of using open source software. If yopu really
need to know read the module source code... At least thats
possible with open source! :-)

> This contrasts with the more detailed descriptions in
> the document at New Mexico Tech, which goes into considerable
> detail on options for the Tkinter class.

Yes, but Tk and Tkinter have both been around for a very long
time and are widely used. Plenty time for documentation to be
written. PIL has been around for a while but is much less widely
used and ImageDraw is even more recent and more specialised.

Your best bet may be to ask on a PIL mailing list or try
the main comp.lang.python usenet group.

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] Understanding the ImageDraw Options

2008-02-13 Thread Kent Johnson
Wayne Watson wrote:
> I started getting acquainted with the ImageDraw class (Object). 
>   My question here is are 
> there more detailed explanations somewhere for the options? 
> 
> It gives no idea what the choices are for options in the argument list.

There is an Options section on the page you reference. It lists the 
options as outline, fill and font. Outline and fill seem to take color 
arguments. The Colours section tells how to specify colors. The font 
argument is specified as taking an ImageFont value. It doesn't 
explicitly say, but from the example the options seem to be keyword 
arguments.

> This contrasts with the more detailed descriptions in the document at 
> New Mexico Tech, which goes into considerable detail on options for the 
> Tkinter class.

Which really has nothing to do with the ImageDraw docs at all. Different 
projects have docs of different quality...

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


Re: [Tutor] beginner pexpect question

2008-02-13 Thread Nathan McBride
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Anyone have any recomendations?  Seems like it is giving it the
passwords since it finishes cleanly,
but maybe not like I think?

Nate

Nathan McBride wrote:
> Hey guys,
>
> I'm practically still a beginner with python.  I am working on a program
> that originally I used popen for but then switched to pexpect because it
> was easier for me to understand.
> I was hoping someone could help me get this working:
>
> I do a:
>
> child = pexpect.spawn ('cryptsetup --verbose --cipher
> "aes-cbc-essiv:sha256" --key-size 256 --verify-passphrase luksFormat ' +
> self.loopdevice)
> i = child.expect ([pexpect.TIMEOUT, '.*'])
> if i == 0:
> print 'ERROR!'
> print child.before, child.after
> child.sendline ('YES')
> print "Sent YES"
> child.expect ('.*')
> #child.sendline ('Test')
> child.send ('Test\n')
> print "Sent Pass 1"
> child.expect ('.*')
> child.send ('Test\n')
> print "Sent Pass 2"
> #child.sendline ('Test')
>
> This runs without errors but then to test I do a:
>
> [EMAIL PROTECTED] project]# losetup /dev/loop0 /home/user/deleteme
> [EMAIL PROTECTED] project]# cryptsetup luksOpen /dev/loop0 encr-container1
> Enter LUKS passphrase:
> /dev/loop0 is not a LUKS partition
> Command failed: No key available with this passphrase.
>
> I can't understand this at all.  If anyone can help I would appreciate
> it a lot.
>
> Thanks very much,
> Nate
>

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


-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.7 (GNU/Linux)
Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org

iD8DBQFHs2wb/n+duykW6K8RAhcgAJ0T9f5WlxYCFtUtjBirdhxs3jfzzACeJNXr
x8TGYUdeRNbjzw51pG8J+Jg=
=qoOB
-END PGP SIGNATURE-

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


[Tutor] Understanding the ImageDraw Options

2008-02-13 Thread Wayne Watson




I started getting acquainted with the ImageDraw class (Object).  
My question here is are there more detailed explanations somewhere for
the options? Here's a description for line from that source:
===
line
draw.line(xy, options)  <= OPTIONS

Draws a line between the coordinates in the xy list.
The coordinate list can be any sequence object containing either
2-tuples [ (x, y), … ] or numeric values [ x,
y, … ]. It should contain at least two coordinates.
The fill option gives the colour to use for the
line.


It gives no idea what the choices are for options in the argument list.


This contrasts with the more detailed descriptions in the document at
New Mexico Tech, which goes into considerable detail on options for the
Tkinter class. See page 4 of  
by John Shipman. For Tkinter, options are fully detailed. Is there
something similar for ImageDraw?
-- 
   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

  "I know that this defies the law of gravity, but 
   you see, I never studied law." -- Bugs Bunny
 
Web Page: 




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


Re: [Tutor] Various Topics from IDLE to ImageDraw Options

2008-02-13 Thread Alan Gauld

"Wayne Watson" <[EMAIL PROTECTED]> wrote

Hi Wayne, welcome to the tutor list.

One wee point, dont reply to existing messages with a new
subject. Those of us using threaded readers are likely to
miss it unless we are folowing the thread. tHis one popped
up halfway through the long thread on POOP!

Now to your questions:

> I've begun with IDLE and have a few questions about it.
> Although, I've been able to set breakpoints, I see no
> way to clear then all. Is there a way,

I don;t think there is a clear all option.

If you are on Windows I recommend you get the Pythonwin
IDE (in the winall package) it has a much better debugger
and in fact is better in almost every way than IDLE. If you
are on Linux using Eclipse and the PyDev plugin might be
a better option.

Alternatively try WinPdb as a stand alone Pyton debugger.

> and is there a way to tell what line # I'm on when
> examining source

There should be a part of the status bar at the bottom right
that tells you line and column.

> though I have a popular book on Python (Lucas?), I just found a 
> short
> tro to Python OOP on the web that looks like a good quick start into
> e subject. 

Most tutorials should have an OOP tiopic, mine certainly has...

Try the python web site for lots of tutorials and how-tos etc.
Explote the topic guides.

> ttp://infohost.nmt.edu/tcc/help/pubs/tkinter.pdf> by John Shipman.

Again, check the Tkinter section of the web site for lots more links.
My tutorial also has a very basic intro, but it sounds like you are
past it already :-)


-- 
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] beginner pexpect question

2008-02-13 Thread Nathan McBride
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

Hey guys,

I'm practically still a beginner with python.  I am working on a program
that originally I used popen for but then switched to pexpect because it
was easier for me to understand.
I was hoping someone could help me get this working:

I do a:

child = pexpect.spawn ('cryptsetup --verbose --cipher
"aes-cbc-essiv:sha256" --key-size 256 --verify-passphrase luksFormat ' +
self.loopdevice)
i = child.expect ([pexpect.TIMEOUT, '.*'])
if i == 0:
print 'ERROR!'
print child.before, child.after
child.sendline ('YES')
print "Sent YES"
child.expect ('.*')
#child.sendline ('Test')
child.send ('Test\n')
print "Sent Pass 1"
child.expect ('.*')
child.send ('Test\n')
print "Sent Pass 2"
#child.sendline ('Test')

This runs without errors but then to test I do a:

[EMAIL PROTECTED] project]# losetup /dev/loop0 /home/user/deleteme
[EMAIL PROTECTED] project]# cryptsetup luksOpen /dev/loop0 encr-container1
Enter LUKS passphrase:
/dev/loop0 is not a LUKS partition
Command failed: No key available with this passphrase.

I can't understand this at all.  If anyone can help I would appreciate
it a lot.

Thanks very much,
Nate

-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.7 (GNU/Linux)
Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org

iD8DBQFHsxnq/n+duykW6K8RAufNAKDP3BNCDAC/ALFuH8ht8qyETy5/xQCfS4i7
2aA9UoTLBZDRst0LPA9YstM=
=rcB6
-END PGP SIGNATURE-

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


[Tutor] Various Topics from IDLE to ImageDraw Options

2008-02-13 Thread Wayne Watson
I'm just getting started in Python but have begun with a challenging 
project. It's a 2000+ line program that provides works with a GUI for 
essentially a video device. As such, it displays dialogs, still images, 
push buttons, menus, and the like. It uses OOP. Ten years ago I was into 
OOP with C++ and Java for several years. It's been awhile. I'm 
interested in modifying the GUI interface.

I've begun with IDLE and have a few questions about it. Although, I've 
been able to set breakpoints, I see no way to clear then all. Is there a 
way, and is there a way to tell what line # I'm on when examining source 
text? I'm not quite sure why, but when I start the Python shell via 
IDLE, an Open leads me to the Python 2.4.4 folder. This is not where my 
programs are. Is there some way to start in a directory closer where I 
want to be?

Although I have a popular book on Python (Lucas?), I just found a short 
intro to Python OOP on the web that looks like a good quick start into 
the subject.  
Maybe there are others.

I just figured out how to draw a line on one of the still images the 
program. I'm not quite sure how I did that, but it did work. Eventually, 
the line effort will allow me to draw a compass over the image. In any 
case, for that, I started getting acquainted with the ImageDraw class 
(Object).   My question 
here is are there more detailed explanations somewhere for the options? 
For example, I found a rather helpful document at New Mexico Tech, which 
goes into considerable detail on options for Tkinter. See page 4 of 
 by John Shipman.


-- 
   Wayne Watson (Watson Adventures, Prop., Nevada City, CA)

 (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time)
  Obz Site:  39° 15' 7" N, 121° 2' 32" W, 2700 feet

  "I know that this defies the law of gravity, but 
   you see, I never studied law." -- Bugs Bunny
 
Web Page: 

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


Re: [Tutor] designing POOP

2008-02-13 Thread Kent Johnson
Tiger12506 wrote:
> vg = VideoGame()
> howmany = rand.randint(0,100)
> for i in range(howmany):
>   vg.buttonpush()
>   print vg.score#Tear open the case (hope you have a screwdriver)
> 
> OR
> 
> class VideoGame():
>   def __init__(self):
> self.score = 0
>   def updatedisp():
> print self.score
>   def buttonpush():
> self.score += 1
> self.updatedisp()
> 
> vg = VideoGame()
> howmany = rand.randint(0,100)
> for i in range(howmany):
>   vg.buttonpush()#Let the videogame display your score 
> however it wishes
> 
> The second way is preferable for many reasons...

Hmm. Not to me. The second version couples the game state with the 
display. I would rather have

- a Game object that maintains the state of the game and has methods to 
manipulate the state

- a Display object that displays the state of the game

- a Controller object that mediates between user interaction, the Game 
and the Display.

Something like:

class Game(object):
   def __init__(self):
 self.score = 0
   def handleSomethingGood(self):
 self.score += 1

class Display(object):
   def showScore(self, score):
 print score

class Controller(object):
   def __init__(self, game, display):
 self.game = game
 self.display = display
   def handleButton(self):
 self.game.handleSomethingGood()
 self.display.showScore(self.game.score)

Now Game.handleSomethingGood() is decoupled from both the display and 
the actual UI event that signals SomethingGood happened.

This is an example of Model-View-Controller architecture (google it). 
Notice that the Game and Display are now reusable (maybe there are both 
GUI and text interfaces to the game, for example, or versions for 
wxPython and PyQt) and testable independently of each other.

A more advanced design might register the Display as an observer of the 
Game score but I don't want to get into that...

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


Re: [Tutor] designing POOP

2008-02-13 Thread Kent Johnson
Alan Gauld wrote:
> This is fine and dandy but what if we want to find out the 
> current value of a.value without calling inc?
> Thats where hetter/setter/direct access comes into the 
> picture.
> In Java and some other languages the idiomatic thing 
> to do is provide methods prefixed with get/set for each attribute
> 
> class Counter(object):
> def __init__(self, initial=0, delta=1):...
> def inc(self)...
> def state(self):...
> def getDelta(self): return self.delta
> def getValue(self): return self.value
> def setValue(self, val): self.value = val
> def setDelta(self, val): self.delta = val
> 
> Now this is a lot of typing! It also isn't necessary in Python 
> because Python allows you to access the attributes 
> diectly - direct access.

To amplify and clarify a little:

- Other languages can also give direct access to attributes, this is not 
unique to Python. Java and C++, at least (the languages I know), also 
have a way to *restrict* direct access to attributes which Python does 
not really have.

- There is a good reason for using setters and getters in Java and C++ - 
they have no way to convert an attribute access into a method call. So 
if you start with attribute access and then realize you want to add some 
code to the access, you are stuck - you have to change the interface to 
the class. Python does not have this problem - attribute access can be 
converted to a method call using properties. For this reason, there is 
IMO (and as generally accepted usage) no advantage to using getters & 
setters in Python for simple attribute access.

Introduction to properties:
http://personalpages.tds.net/~kent37/kk/8.html

- Python does have a convention for documenting which attributes 
(including methods) are considered part of the public interface and 
which are not. Non-public attribute names are prefixed with _ (single 
underscore). This is a signal to users of the class that the attribute 
is considered an internal implementation detail and to use it at your 
own risk.

This is consistent with the Python philosophy that "we're all consenting 
adults here" - i.e. that the users of a class don't need to be protected 
from shooting themselves in the foot - it is enough to put a warning 
sign on the gun and the foot :-)

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