This rule raises an issue when a loop with an ``++else++`` clause doesn't contain any ``++break++`` statement in its body.

== Why is this an issue?

The ``++else++`` clause of a loop is skipped when a ``++break++`` is executed in this loop. In other words, a loop with an ``++else++`` but no ``++break++`` statement will always execute the ``++else++`` part (unless of course an exception is raised or ``++return++`` is used). If this is what the developer intended, it would be much simpler to have the ``++else++`` statement removed and its body unindented. Thus having a loop with an ``++else++`` and no ``++break++`` is most likely an error.

== How to fix it

Add a ``++break++`` statement to the loop body containing an ``++else++`` clause or remove the ``++else++`` clause.

=== Code examples

==== Noncompliant code example

[source,python,diff-id=1,diff-type=noncompliant]
----
from typing import List

def foo(elements: List[str]):
    for elt in elements:
        if elt.isnumeric():
            return elt
    else:  # Noncompliant: no break in the loop
        raise ValueError("List does not contain any number")

def bar(elements: List[str]):
    for elt in elements:
        if elt.isnumeric():
            return elt
    else:  # Noncompliant: no break in the loop
        raise ValueError("List does not contain any number")
----


==== Compliant solution

[source,python,diff-id=1,diff-type=compliant]
----
from typing import List

def foo(elements: List[str]):
    for elt in elements:
        if elt.isnumeric():
            break
    else:
        raise ValueError("List does not contain any number")
    return elt

def bar(elements: List[str]):
    for elt in elements:
        if elt.isnumeric():
            return elt
    raise ValueError("List does not contain any number")
----


== Resources

=== Documentation

* Python documentation - https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops[Break and continue Statements, and else Clauses on Loops]



ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

Add a "break" statement or remove this "else" clause.


'''
== Comments And Links
(visible only on this page)

=== on 14 Apr 2020, 09:49:58 Pierre-Yves Nicolas wrote:
I would expect the compliant solution to suggest something like:

----
for i in range(50): 
  if i == 42:
    print('Magic number in range')
print('Magic number not found')
----
That behaves the same way as the noncompliant example but it doesn't contain the suspicious `else`.

endif::env-github,rspecator-view[]
