for-else
Shane Geiger
sgeiger at ncee.net
Tue Mar 4 13:07:31 EST 2008
> if a == 0:
> do_task_0()
> elif a == 1:
> do_task_1()
> elif a == 2:
> do_task_2()
> else:
> do_default_task()
The if-elif-else structure that calls functions (like that above) can be
avoided with the code below:
def foo0(): print 'foo0'
def bar0(): print 'bar0'
def foo1(): print 'foo1'
def bar1(): print 'bar1'
def do_default_task(): print 'do_default_task'
do_task = { 0:foo0, 1:foo1, 2:bar0, 3:bar1, }
a = 1
# example of normal usage
if a in do_task.keys(): do_task[a]()
else: do_default_task()
# example of testing all functions in the dict as well as the default
function
for a in do_task.keys() + [8]: # 8 is a non-existent key in the do_task
dict
print "a is ",a,"and it gives this output:",
if a in do_task.keys(): do_task[a]()
else: do_default_task()
Carl Banks wrote:
> On Mar 4, 10:55 am, "BJörn Lindqvist" <bjou... at gmail.com> wrote:
>
>> On Tue, Mar 4, 2008 at 4:17 PM, Carl Banks <pavlovevide... at gmail.com> wrote:
>>
>>> > for ...:
>>> > ...
>>> > exhausted:
>>> > ...
>>> > broken:
>>> > ...
>>>
>>> > The meaning is explicit. While "else" seems to mean little there.
>>> > So I may like something similar for Python 3.x (or the removal of the
>>> > "else").
>>>
>>> I would not be opposed to this on its own merits, but there is a
>>> rationale behind the name "else". If you consider a for loop to be a
>>> rolled-up if...elif...else statement (situations where this is
>>> reasonable tend to be the same ones were else would be useful), then
>>> the "else" clause would remain unchanged on the for loop.
>>>
>>> For instance, if you have a (trivial) if...elif...else like this:
>>>
>>> if a == 0:
>>> do_task_0()
>>> elif a == 1:
>>> do_task_1()
>>> elif a == 2:
>>> do_task_2()
>>> else:
>>> do_default_task()
>>>
>>> You could roll it up into a for...else statement like this:
>>>
>>> for i in range(3):
>>> if a == i:
>>> do_task[a]()
>>> else:
>>> do_default_task()
>>>
>> You forgot the break statement. The else suite will always be executed
>> in this loop. Kind of proves bearophiles point, for-else is really
>> tricky.
>>
>
> Ah ha, but that would have been a mistake with or without the else
> clause....
>
>
> Carl Banks
>
This approach works well for me:
def foo0(): print 'foo0'
def bar0(): print 'bar0'
def foo1(): print 'foo1'
def bar1(): print 'bar1'
def do_default_task(): print 'do_default_task'
do_task = { 0:foo0, 1:foo1, 2:bar0, 3:bar1, }
a = 1
# example of normal usage
if a in do_task.keys(): do_task[a]()
else: do_default_task()
# example of testing
for i in range(len(do_task.keys)):
if a in do_task.keys(): do_task[a]()
else: do_default_task()
--
Shane Geiger
IT Director
National Council on Economic Education
sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net
Leading the Campaign for Economic and Financial Literacy
More information about the Python-list
mailing list