Considering migrating to Python from Visual Basic 6 for engineering applications

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Mon Feb 22 03:50:07 EST 2016


BartC writes:

> On 21/02/2016 21:52, Jussi Piitulainen wrote:

[...]

>>>>> def istriangle(*threeintegers):
>>          a,b,c = sorted(threeintegers)
>>          return a*a + b*b == c*c
>
> (That detects right-angled triangles. I think 'return a+b>c' is the
> correct test for any triangle. It becomes trivial when you have sort
> available, but that's part of the point of the exercise.)

Sorry about that. (Non-positive sides should also be ruled out.)

[...]

> Reading stuff from an interactive console or terminal, is such an
> important part of the history of computing, still being used now, that
> you'd think a language would provide simple, ready-to-use methods ways
> to do it.

I think it does. Do you at least agree that it provides a reasonably
simple way to ask for a single line of text?

stuff = input()

Is that already too obscure or advanced for you? Because surely not?

It can be used piecemeal:

print("a b c = ")
stuff = input()
parts = stuff.split()
a = int(parts[0])
b = int(parts[1])
c = int(parts[2])

The same can be done in one statement:

a, b, c = map(int, input("a b c = ").split())

Here's a simpler user interface:

a = int(input("a = "))
b = int(input("b = "))
c = int(input("c = "))

These building blocks can be used to define more complex dialogues in
obvious ways, probably using exception handling.

def please(*types, *, prompt = None):
    """Repeatedly prompts the console user for space-separated values in
    one line until an input line matches the given types. Returns the
    corresponding values. At end of input, raises UpsetException."""
    ...

a, b, c = please(int, int, int, prompt = "a b c = ")

def readWithDWIM(source, *types):
    """Reads and returns whitespace-separated values from text source.
    Parses each as the corresponding type by calling the type on it. For
    invalid or missing values, substitutes the value of calling the type
    without arguments, or None if even that fails. May or may not
    discard the remaining part of the line that contained the last
    value. Use at your own risk!"""
    ...

from itertools import repeat
with open("f.txt" as f:
    a, b, c = readWithDWIM(f, int, int, int))
    xs = readWithDWIM(f, *repeat(float, b))

If there really is demand for these, they should be all over the web
already. I don't see why there should be demand. The simple case is
simple enough, more complex specifications are either still simple
enough to write from scratch, or too specific, or insane.

[...]


More information about the Python-list mailing list