[Date Index] [Thread Index] [Author Index]
Re: If without else
On 10/11/10 at 5:17 AM, sschmitt at physi.uni-heidelberg.de (Sebastian Schmitt) wrote: >I have a question to the usage of the If condition. >In := x = 2; b = 3; >In := If[b > 2, x = 10,]; x If you are not going to have an else condition, there is no need for the last comma. That is If[b > 2, x = 10]; x produces exactly the same result. Also, note when writing If[b > 2, x = 10,] the final comma is red indicating Mathematica is expecting more input after the comma. >Is it good-practice to leave the "else" empty? Is This is really a question of programming style and programming robustness. Like C++, if the test condition evaluates to False, then the body isn't executed and nothing is returned. So, in that sense there is no problem leaving the else empty. What could possibly catch you by surprise is what happens when Mathematica cannot determine whether the result is True of False. Consider: In:= Clear[b]; If[b < 2, x = 10] Out= If[b<2,x=10] If Mathematica cannot determine whether the test is true of not, the expression is returned unevaluated which is often not what you want or may not be expecting. >x := 10 /; b > 2 >what I'm looking for? Possibly. You haven't made it clear what you want to accomplish with the If statement. Most likely, this is simply another way to accomplish the same end with no practical difference.