Python

Python

By DeepSource

Unnecessary else / elif used after return PYL-R1705

Style
Autofix

The use of else or elif becomes redundant and can be dropped if the last statement under the leading if / elif block is a return statement. In the case of an elif after return, it can be written as a separate if block. For else blocks after return, the statements can be shifted out of else. Please refer to the examples below for reference.

Refactoring the code this way can improve code-readability and make it easier to maintain.

Examples

Bad practice

def classify_number(x):
    if x % 2 == 0:
        return 'Even'
    else:
        return 'Odd'


def what_is_this_number(x):
    if x % 2 == 0 and x >= 0:
        return 'Even'
    elif x % 2 == 0 and x < 0:
        return 'Even and Negative'
    elif x % 2 != 0 and x < 0:
        return 'Odd and Negative.'
    else:
        return 'Odd'

Preferred:

def classify_number(x):
    if x % 2 == 0:
        return 'Even'

    return 'Odd'


def what_is_this_number(x):
    if x % 2 == 0 and x >= 0:
        return 'Even'

    if x % 2 == 0 and x < 0:
        return 'Even and Negative'

    if x % 2 != 0 and x < 0:
        return 'Odd and Negative'

    return 'Odd'