why does pylint complain about this code block?
R1705: Unnecessary "elif" after "return" (no-else-return)
def f(a):
if a == 1:
return 1
elif a == 2:
return 2
return 3
To prevent the error, I had to create a temporary variable, which feels less pleasant.
def f(a):
if a == 1:
b = 1
elif a == 2:
b = 2
else:
b = 3
return b
Solution:
def f(a):
if a == 1:
return 1
if a == 2:
return 2
return 3
The purpose of an else
block is to define code that will not be executed if the condition is true, so execution wouldn't continue on to the next block.
However, in your code, the main conditional block has a return statement, meaning execution will leave the function, so there's no need for an else block: all subsequent code after the return will, by definition, not be executed if the condition is true. It's redundant. It can be replaced with a simple if
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With