[Edu-sig] Re: Python @ Education: What are your problems?

Burley, Brent Burley, Brent" <Brent.Burley@disney.com
Fri, 31 May 2002 15:56:46 -0700


> From: Kirby Urner <urnerk@qwest.net>
...
> def readln():  # defined once
>     return [eval(i) for i in raw_input().split()]
> 
> x,y = readln()  # used elsewhere
> 
> is a quickie workaround.

Clever, and concise!

Here's a more robust (albeit verbose) version that checks the number
and types of the arguments:

def readln(spec, prompt=""):
    types = { 'i' : int, 'f' : float, 's' : str }
    while 1:
        words = raw_input(prompt).split()
        if len(words) != len(spec):
            print 'You must input', len(spec), 'items, please try
again'
            continue
        try:
            return [types[s](w) for s,w in zip(spec, words)]
        except KeyError:
            print 'Invalid type specifier passed to readln:', s
            print "  You must pass in a string of i's, f's, or s's"
            return
        except ValueError, e:
            print 'Invalid input, please try again'
            print '  ', e

>>> print readln('ifs', 'input (int float string): ')
input (int float string): 
You must input 3 items, please try again
input (int float string): a b c
Invalid input, please try again
   invalid literal for int(): a
input (int float string): 1 2 3
[1, 2.0, '3']
>>>

Or, if you only care about inputting numbers, you can use this simpler
version:

def readnumbers(num, prompt=""):
    while 1:
        words = raw_input(prompt).split()
        if len(words) != num:
            print 'You must input', num, 'numbers, please try again'
            continue
        try:
            return [float(w) for w in words]
        except ValueError, e:
            print 'Invalid input, please try again'
            print '  ', e

>>> readnumbers(3, 'x y z? ')    
x y z? 1 2
You must input 3 numbers, please try again
x y z? 1 2 z
Invalid input, please try again
   invalid literal for float(): z
x y z? 1 2 3
[1.0, 2.0, 3.0]


	Brent