Emulating Pascal input
Jeff Shannon
jeff at ccvcorp.com
Fri May 24 14:44:52 EDT 2002
In article <acjjmf$rgf$0 at 216.39.172.122>, Bengt Richter says...
> If you pass a _string_ containing an ordered arg name list
> (e.g., comma-separated as below), you can get the names bound
> in the global name space to converted values.
Just skimming, so I may have missed something, but ISTM that this
method of doing things is very fragile. You can use this to
rebind *global* variables... but once you put those variables
(and the input call) inside of another function, suddenly it
breaks for no apparent reason. This will be very surprising to
students who probably won't understand all of the hidden
complexities of global vs local namespaces.
As Bengt says, this is shoehorning ideas that don't fit well into
Python. I think that it is better for the students if they learn
Python conventions instead of Pascal conventions poorly
translated into Python. (If you really want them to learn the
Pascal conventions, then keep teaching them Pascal. <wink>)
My loose translation of the readin() function would be something
like this:
def readin(prompt, numtype=int):
data = raw_input(prompt)
numbers = data.split()
return map(numtype, numbers)
This will allow any number of whitespace-separated numbers to be
entered, and will return all of them in a list. It defaults to
returning ints, but can be used to return floats or longs or
complex by using the optional second argument. I would argue
that this teaches *better* programming practice than the Pascal
version, since it doesn't depend on side-effects to the
function's arguments. <wink>
Some modification could be made to this to allow it to read from
a file, too. Personally, though, I'd be tempted to separate the
(string) input retrieval from the processing. This makes it a
two-step operation, but it's clear what's going on.
def process_input(data, numtype=int):
numbers = data.split()
return map(numtype, numbers)
x, y = process_input(raw_input("Enter two numbers: "))
I, j, k = process_input(infile.readline())
(As a disclaimer, I'm not really familiar with Pascal, so please
take all my comments regarding it in the lighthearted vein in
which they are intended.)
--
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list