Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Here is simplified version of my code that exhibits the behavior troubling me:

testFn[] := (
  Do[
   Print[i];
   If[i > 3, Print["triggering result for true"]; Return [100]]
   , {i, 1, 5}];
  Return[200];
  )

testFn[]
1
2
3
4
triggering result for true
200

Intuitively, once i is bigger than 3, it should evaluate the 2nd argument of the If and exit testFn, returning 100. However, although the 2nd argument of the If statement is getting evaluated, the function does not exit until it hits the Return[200].

I kind of guessed what might be the problem. The Return[100] is just exiting the Do, which seems to be confirmed by doing:

testFn[] := (
  a = Do[
    Print[i];
    If[i > 3, Print["triggering result for true"]; Return [100]]
    , {i, 1, 5}];
  Print["a=" <> ToString[a]];
  Return[200];
  )

1
2
3
4
a=100
triggering result for true
200

If this is indeed what's happening, how can I make my code actually return from and exit testFn?

share|improve this question

marked as duplicate by m_goldberg, bobthechemist, Michael E2, ubpdqn, RunnyKine Jul 11 '14 at 1:32

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
Do Return[100, Module] Not just Return[100] see mathematica.stackexchange.com/questions/44585/… for more information – Nasser Jul 10 '14 at 17:42
    
Take a look here: mathematica.stackexchange.com/questions/29353/… – Szabolcs Jul 10 '14 at 19:00