[Tutor] Is it pythonesque

Alan Gauld alan.gauld at btinternet.com
Sun Jan 24 18:17:26 CET 2010


"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/ 




More information about the Tutor mailing list