4

I have this simple test code:

n1 = 0;
n2 = 0;
m = 0;
If[n1 == 0, n2 == 1]

which evaluates as False, as it should. However, if I do:

If[n1 == 0, n2 == 1; m = 1];
m

I get 1 instead of 0 (m value shouldn't change, if the expression evaluates to False). What am I doing wrong?

Silviu
  • 145
  • 4

1 Answers1

9

Translation to make it easier to see. When you write

 If[n1 == 0, n2 == 1]

This translates to

IF n1==0 THEN
   n2==1 (*this gives False*)
END IF

Since last expression of IF is its value, then the above returns False which is what you got.

Now when you write

 If[n1 == 0,  n2 == 1;  m = 1  ];

This translates to

 IF  n1 == 0 THEN
     n2==1; (*this does nothing, it just gives False, but not used*)
     m=1 (*this assigned  m =1, over writing its old value of zero*)
 END IF

The last expression gives 1 now, which is value of m after it was assigned.

Now when you check you find m is 1 as expected.

m value shouldn't change

Why? You assigned 1 to m, so it should change? Mathematica is correct.

what I want to do is, if n1=0 and n2=1 them m=1. I tried using && and "and" instead of the come between n1=0 , n2=1, but they didn't work either

It seems you thought that n1==0 , n2==1 means n1==0 and n2==1 but that is not the case. It translates to n1==0 THEN n2==1. The first comma inside the If means THEN and not logical and and the second comma means ELSE.

So to do what you want use

 If[n1 == 0 && n2 == 1, m = 1]

Now m stays zero

Mathematica graphics

The above can also be written as

 If[And[n1==0,n2==1],m=1]

Which translates to

 IF  n1==0 AND n2==1 THEN
     m=1
 END IF

Appendix

The structure of If is this

If[  booleanValuedExpression , truePart, falsePart ]

Which translates to

IF  booleanValuedExpression THEN
    truePart expressions separated by `;'
ELSE
    falsePart expressions separated by `;' but do not end last one by `;`
END IF

So you see that the first comma inside If translates to THEN and the second comma translates to ELSE and the closing ] translates to END IF.

The above is for the two argument If. Mathematica also also has the three arguments If.

When writing my complicated if then else in Mathematica, I like to do alignment as follows to make it clear to me

If[  booleanValued  ,
   stuff; 
   stuff;
   more stuff

, stuff; stuff; more stuff ]

I use code cell and not input cell when writing in notebooks (for .m files (i.e package files), I use notepad++ so I am free to do any alignment I want).

Using code cell in notebook makes it easier to do the above.

I always put the ELSE (which is the second comma in Mathematica) shifted left to align under the If so it is more clear to me reading the code.

I must admit I old fashioned and prefer explicit THEN, ELSE, END IF in code instead of commas and braces or spaces (as in Python). These make the logic more clear to me.

Nasser
  • 143,286
  • 11
  • 154
  • 359