substitute for c/java's ?:

Ype Kingma ykingma at accessforall.nl
Tue Jun 12 15:47:06 EDT 2001


Jochen Riekhof wrote:
> 
> Hi...
> 
> as a newcomer to python (like it a lot!) I found almost everything great
> except two things:
> 1. (most important)
> I am missing something like the c/Java ?: operator. This is so convenient in
> many places and saves a lot of typing.
> It works like
> result = option ? value1 : value2;
> which is equivalent to
> if option:
>     result = value1
> else:
>     resultl = value2
> 
> Is there anything I overlooked?
> 

You can play tricks with the 'and' and 'or' operators in python.
I looked into this briefly and then found these tricks so ugly that
I prefer to avoid these operators outside pure boolean expressions.
Instead I usually write:

if option: result = value1
else: result = value2

just dropping the newlines. It's more verbose than

result = option ? value1 : value2

but at least it's clean.

> 2. switch (not important)
> if elif else is not a proper substitute for switches, as the variable in
> question has to be retyped in each if/elif clause.
> One can shorten the code by assigning to a temporary variable, but I
> consider switch more elegant. The ability
> to specify limits like 0 <=x <=10 is cool, however.

There is no real equivalent of 'switch' in python.
IIRC a few weeks ago there was a thread about using classes to
get a similar effect. This requires a separate method for each
of the bits of code between the 'case's, so it is not a real
substitute. But it's worthwhile to keep this alternative in mind
when you find yourself writing long 'if elif elif elif'
sequences. Adding a few small (sub)classes can really improve
readability.

> 
> Otherwise, one of the coolest languages I learned so far!!
> 

It only gets better.

Now if I could only teach my editor to add
a ':' each time I type 'def' or 'class' or 'for' or 'while'
or 'if' or ... or ...


Have fun,
Ype

-- 
email at xs4all.nl



More information about the Python-list mailing list