0

I keep getting an error saying 'Unnecessary "else" after "return"'

What is it trying to tell me, and what would be a more elegant way to code this logic?

for selected_node in NODES: if pm.nodeType(selected_node) == 'file': msg = 'correct type of nodes selected' LOGGER_TEXTURE_SWAP.debug(msg) return True else: msg = 'incorrect type of nodes selected' LOGGER_TEXTURE_SWAP.debug(msg) return False 
7
  • 7
    You have a for loop that can only ever run one iteration. It returned during the first loop whether the condition is true or not. It's not clear what you are trying to do. Commented Aug 4, 2020 at 3:55
  • 3
    What is giving you an error for the else:? I don't think this is an error, it is redundant as you don't need it. Just remove it and unindent the body. The loop is unnecessary as well. Commented Aug 4, 2020 at 4:02
  • Error is the wrong word to use. PyLint is throwing that warning, and I an trying to figure out how to better code that logic Commented Aug 4, 2020 at 4:04
  • 1
    This will only loop once... what are you actually trying to do? Commented Aug 4, 2020 at 4:05
  • i am looping through a list of nodes to check if their type is valid, and if not, return False. removing the else and unindenting seems to have fixed the issue though. Commented Aug 4, 2020 at 4:07

1 Answer 1

1

I try to recreate the logic of your snippet and I use the latest python 3.8.3

nodes = ['file', 'folder', 'directory'] for node in nodes: if node == 'file': print(node) return True else: print('something else') return False 

and I get SyntaxError: 'return' outside function. Which is understandable since return should be an output of a function.

So, then I make it as a function, as follow.

nodes = ['file', 'folder', 'directory'] def myprogram(): for node in nodes: if node == 'file': print(node) return True else: print('something else') return False myprogram() 

Now I got 'file' printed and 'True' output. So, python works as expected.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.