1

I have the following if statements:

if can_move == True:
   
    return "ok"
else:
    return "error"

if can_run
    return "great"
else:
    return "error"

The issue I have is if the else statement is run, then the other if statement doesn't execute. I would like both of them to execute simultaneously.

martineau
  • 119,623
  • 25
  • 170
  • 301
code_legend
  • 3,547
  • 15
  • 51
  • 95
  • 1
    I assume this is part of a function? it would help if the example showed that. In fact something we can run and see a result, plus the result you expected. – tdelaney Jul 05 '20 at 00:12
  • `if the else statement is run, then the other if statement doesn't execute.` the same is true for the first if statement – Alan Kavanagh Jul 05 '20 at 00:13
  • Perhaps `if can_move: return "ok" elif can_run: return "great" else: return "error"`? – Nick Jul 05 '20 at 00:13
  • It's unclear what vaue(s) the function should `return` — please clarify your desired result. – martineau Jul 05 '20 at 00:21
  • 1
    What do you expect `return` to do? What exactly do you want the function to `return` in each case? – Karl Knechtel Jul 05 '20 at 00:39

2 Answers2

3

You can make 2 separate function to handle them. Also, if you have boolean type, you should not return any string, unless it's absolute necessary. You should make 2 separate functions to handle moving, and return immediatelly if the corresponding value is not True.

But if you would like to do this way, you can create a list.

back = []
if can_move:
    back.append('ok')
else:
    back.append('error')
if can_run:
    back.append('great')
else:
    back.append('error')
return back

Easier way, but this is going to return a tuple:

return ('ok' if can_move else 'error', 'great' if can_run else 'error')
nagyl
  • 1,644
  • 1
  • 7
  • 18
  • Thanks, what if I had multiple items I wanted to add under the else statement how would that work in the return – code_legend Jul 05 '20 at 00:25
  • such as let's say I wanted to do if can_move: self.cases.update({key:value)}) return "ok" – code_legend Jul 05 '20 at 00:28
  • If you would like to do multiple operations before returning, I suggest you use the first code above, and do the operations before you return. But also, you can make new functions to controll those operations, and return from them. This way you would not need to handle multiple return statements. – nagyl Jul 06 '20 at 14:27
1

That's because python functions will only return once. You can make it return multiple things at once:

msg = []
if can_move:
    msg.append('ok')
else:
    return "error"

if can_run:
    msg.append('great')
else:
    return "error"
return ', '.join(msg)
Red
  • 26,798
  • 7
  • 36
  • 58