[Tutor] getting started
Magnus Lycka
magnus@thinkware.se
Fri Nov 15 18:07:03 2002
At 19:54 2002-11-15 +0100, Gregor Lingl wrote:
>alan.gauld@bt.com schrieb:
>
>>>If you are really desperate to run a few lines at once
>>>in interactive mode, you can do this with a little trick:
>>>
>>> >>> if 1 == 1:
>>> print "aaa"
>>> print "bbb"
>>> print "ccc"
>>
>>I like it Magnus! I hadn't thought of that before...
:) Even if Python is easy to learn, we can always learn more
things. There's no end to the fun!
I've seen the "if 1:" or "if 0:" construct here and there in
code to make it easy to switch blocks in and out during testing
and debugging. An alternative to commenting out code I guess.
>Me too! But why not
>
> >>> if 1:
> print "aaa"
> print "bbb"
Actually, this is what I would do myself, but it seemed more
obvious that "if 1==1:" has to be true every time. "if 1:"
assumes that you understand Python's notion about true and
false, and I didn't want to explain too many concepts at the
same time. (I did mention it in the end of the mail though...)
While (heh?) we're at it, it's a common Python idiom to
code like this:
while 1:
bla
bla
if some_condition:
break
maybe more bla bla bla
This corresponds more or less to
do {
bla;
} while condition;
in C and derivates or
repeat
bla;
bla;
until condition;
in Pascal and its derivates.
It is sometimes argued that Python should have such a construct,
so that we could stop this "while 1:" lie. (We don't intend to run
the loop for ever, so why claim that?) I think the reason that
this hasn't happened is that it can't be done in a pretty way in
Python. The clear and consistent block structure by indentaion
would be broken if we did:
do:
bla
bla
while x
since that last line shouldn't be in the loop. And if we did
do:
bla
bla
while x
we would also get confusing and ugly code. First of all, the
while statement doesn't stick out much. But secondly, you could
also want to do:
do:
bla
bla
while x:
foo()
bar()
while y
Now it starts to look wierd, and if you happen to forget the
colon after the x, you will probably get a very confusing
error message from the poor interpreter, which thinks that
the indentation is incorrect in the "foo()" line.
I bet that a proposal to introduce either of these syntaxes
would have a more or less equal following of people who would
prefer it the other way around. I also think that the majority
would agree that this very disagreement shows us that do/while
doesn't really fit smoothly into Python.
Conceptually, it's a typical feature of Python that block just
end, without any particular ta-da in the end. No "}" and no
"end;". The do/while or repeat/until idiom seems to go against
that.
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se