[Tutor] Is it pythonesque

Robert Berman bermanrl at cfl.rr.com
Sun Jan 24 20:10:41 CET 2010


Thank you for the snippet and the insight.


Robert

-----Original Message-----
From: tutor-bounces+bermanrl=cfl.rr.com at python.org
[mailto:tutor-bounces+bermanrl=cfl.rr.com at python.org] On Behalf Of Alan
Gauld
Sent: Sunday, January 24, 2010 12:17 PM
To: tutor at python.org
Subject: Re: [Tutor] Is it pythonesque


"Robert Berman" <bermanrl at cfl.rr.com> wrote

> def getuserinput():
>    while True:
>        s1 = raw_input('Enter fraction as N,D or 0,0 to exit>>')
>        delim = s1.find(',')
>        if delim < 0:
>            print 'invalid user input'
>        else:
>            n = int(s1[0:delim])
>            d = int(s1[delim+1::])
>            return n,d

Personally I'd do this with

try:
     n,d = s1.split(',')
     return int(n),int(d)
except ValueError:
     print 'invalid user input'
     continue


Note ValueError works for both the int conversion and the split() 
assignment

> def main():
>    while True:
>        n,d = getuserinput()
>        if n == 0 or d == 0: return 0

> correct. Please note there is no true ending return for getuserinput() as 
> it
> is hung off an if statement and if by some  chance it breaks, it should
> return None which will abort the program.

Since you are inside an infinite loop you should only break if you get an
uncaught exception which will generate a stack trace anyhow

That seems fair enough to me...

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 


_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list