for ... else ?
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Tue Jun 12 07:39:56 EDT 2007
En Tue, 12 Jun 2007 06:34:49 -0300, exhuma.twn <exhuma at gmail.com> escribió:
> On Jun 12, 6:57 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
> wrote:
>> for number in range(10,100):
>> for divisor in range(2,number):
>> if number % divisor == 0:
>> break
>> else:
>> print number,
>>
>
> Oh my. Would it not be an idea to rename this "else" into a "finally"?
> As Gabriel points out, the else-block gets executed after the for loop
> exits *normally*. In that case, is the "else" not semantically
> misleading? I would surely misunderstand it if I saw it the first time.
No - finally already has a meaning, "do this always, even if an exception
occurred before".
The "else" clause is fired when a condition is not met:
if condition:
do something when condition is true
else:
do something when condition is not true
while condition:
do something when condition is true
else:
do something when condition is not met
for x in iterable:
do something with x
else:
do something when there are no more x
You can think the above as:
while there are still values in iterable:
do something with the next value
else:
do something when there are no more items
--
Gabriel Genellina
More information about the Python-list
mailing list