Emulating Pascal input

Giles Brown giles_brown at hotmail.com
Sat May 25 09:10:29 EDT 2002


Andrei Kulakov <ak at silmarill.org> wrote in message news:<slrnaetlin.6dh.ak at ak.silmarill.org>...
> In article <mailman.1022065417.1277.python-list at python.org>,
> Michael Williams wrote:
> > Hi,
> > 
> > We're currently running a trial implementation of a teaching course in
> > Python here at the University of Oxford Physics department. The current
> > course uses Pascal and, although it works well, is obviously sub-optimal
> > for a modern undergraduate education.
> > 
> > Details of the results of the trial will be posted to EDU-sig when it is
> > complete, but for now we're trying to address what we see as a
> > limitation of Python for introductory programming, namely input.
> > 
> > Consider the following Pascal code:
> > 
> > (******** Pascal code **********)
> > (* Pascal ascii input of numbers: stdin and file *)
> > readln(x, y);
> > readln(fin, x, y);
> > 
> > The first line is for stdin, the second for from file. The variables
> > x and y will then contain the first two white space separated numbers
> > the program encounters when that function is called.
> > 
> > Here's how we're currently getting students to do the equivalent in
> > Python:
> > 
> > ######### Python code ###########
[OP code snipped]

Heres another variant where you specify the types of the input as a list
of conversion functions.

def readln(file_, converters, *splitargs):
    fields = file_.readline().split(*splitargs)
    assert len(fields) == len(converters)
    result = []
    for field, converter in zip(fields, converters):
        result.append(converter(field))
    return result

# Example usage
x, y = readln(open("myfile.txt"), [int, float])
a, b, c = readln(sys.stdin, [str, float, long], ',')



More information about the Python-list mailing list