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.
from typing import List
def search_first_number_without_break(elements: List[str]):
for elt in elements:
if elt.isnumeric():
return elt
else: # Noncompliant. This will be executed every time
raise ValueError("List does not contain any number")
from typing import List
def search_first_number_with_break(elements: List[str]):
for elt in elements:
if elt.isnumeric():
break
else:
raise ValueError("List does not contain any number")
return elt
or
from typing import List
def search_first_number_without_else(elements: List[str]):
for elt in elements:
if elt.isnumeric():
return elt
raise ValueError("List does not contain any number")