Just to be, possibly, a little more clear: your if statements are evaluated sequentially.
So for your first observation, Flag will be initially set to "", as ('M' = 'M'). However, Flag is then overwritten by your subsequent if statements, and as ('M' ^= 'F'), Flag is overwritten, and takes the value 'UnkCode'.
In addition to Keni's use of an in statement (which is better than the code I am about to suggest), you could also do the following (which may help you understand if statements better).
if (Variable = 'Gender' and Value = 'M') then Flag = "";
else if (Variable = 'Gender' and Value = 'F') then Flag = "";
else if (variable = 'Gender' and Value = 'O') then Flag = "";
else if (Variable = 'Gender' and Value = 'U') then Flag = "";
else if (Variable = 'Gender') then Flag = 'UnkCode';
I might also suggest that instead of having a variable named 'Variable', with a value of 'Gender', you simply have a variable named 'Gender' with a value of 'F' or 'M'. While there are certainly specific circumstances in which you would not want to create your dataset this way, they are relatively few and far between.