switch
MRAB
python at mrabarnett.plus.com
Thu Dec 10 13:24:28 EST 2009
Steven D'Aprano wrote:
> On Wed, 09 Dec 2009 18:50:29 +0000, Nobody wrote:
>
>> On Tue, 08 Dec 2009 21:02:44 -0800, Kee Nethery wrote:
>>
>>> I string together a bunch of elif statements to simulate a switch
>>>
>>> if foo == True:
>>> blah
>>> elif bar == True:
>>> blah blah
>>> elif bar == False:
>>> blarg
>>> elif ....
>> This isn't what would normally be considered a switch (i.e. what C
>> considers a switch).
>
> Anyone would think that C was the only programming language in
> existence...
>
>
>> A switch tests the value of an expression against a
>> set of constants.
>
> In C. Things may be different in other languages.
>
> For example, I recall the so-called "4GL" (remember when that was the
> marketing term of choice for interpreted programming languages?)
> Hyperscript from Informix. I can't check the exact syntax right now, but
> it had a switch statement which allowed you to do either C-like tests
> against a single expression, or if-like multiple independent tests.
>
> Moving away from obsolete languages, we have Ruby which does much the
> same thing: if you provide a test value, the case expression does a C-
> like test against that expression, and if you don't, it does if-like
> multiple tests.
>
> http://www.skorks.com/2009/08/how-a-ruby-case-statement-works-and-what-
> you-can-do-with-it/
>
>
>
>> If you were writing the above in C, you would need to
>> use a chain of if/else statements; you couldn't use a switch.
>>
>> Compiled languages' switch statements typically require constant labels
>> as this enables various optimisations.
>
> Pascal, for example, can test against either single values, enumerated
> values, or a range of values:
>
> case n of
> 0:
> writeln('zero');
> 1, 2:
> writeln('one or two');
> 3...10:
> writeln('something between three and ten');
> else writeln('something different');
> end;
>
Originally the 'case' statement in Pascal didn't support ranges or a
default; they started as non-standard extensions in some
implementations. Originally, if none of the values matched then that
was a runtime error.
More information about the Python-list
mailing list