Friday Finking: Contorted loops

Alan Gauld alan.gauld at yahoo.co.uk
Sun Sep 12 13:25:05 EDT 2021


On 12/09/2021 09:11, jak wrote:

> if the only way to terminate a 'while True' loop is by using the 'break' 
> statement, why is it allowed to add the 'else' statement which will only 
> contain dead code?
> 
> while True:
>      break
> else:
>      print('dead code')
> 
Because to the interpreter the condition is not part of the
language. It is syntactically correct.

An optimiser OTOH might welkl determine that the condition
will never fail and therefore the else clause never be reached,
in which case it would remove the dead code (possibly emitting
a warning in the process?).

A linter likewise might identify the redundant code.
I don't use any python linters, does anyone know if they do
detect such dead spots?

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Python-list mailing list