I have a few lines of code in a cell which I only want to execute when a certain condition is true - I need something like this
A line of code here;
Another line of code;
if myCondition == true then;
first line of conditional code;
...
last line of condtional code;
end if;
more lines of code follow;
Is this possible? I can only find reference to If[condtion,result if true,result if false] and I don’t see how I could use that for what I want.
Not sure whether the confusion was about how to combine multiple statements together or how to use If without an “else” branch. The answer I gave above explains the latter, but assumed an understanding of CompoundExpression which is how to achieve the former.
The semi-colon is just syntactic sugar for CompoundExpression. The comma is how to separate arguments. So, in an If expression, commas separate the branches and semi-colons will “chunk” pieces together into a single branch.
It (my confusion) was the former - how to combine multiple statements together. It just looks a bit alien when you are used to the if then … else … end if construct as in, for example, Visual Basic
I must have lost the plot somewhere along the line … I have this
fileName = SystemDialogInput["FileOpen",pFilename, WindowTitle -> StringJoin["Select the ",pFileDescrip," containing dissociation constants"]];
If[fileName == $Canceled,fileName = "Canceled", fileName = "File has been found"];
When the dialog shows, if I click on “Cancel” or close the dialog without selecting a file, fileName is returned as “Canceled”, as it should, BUT if I select a file and click on “Open” fileName is returned as the name and path of the file instead of “File has been found”/
The issue here is the semantics of Equal. In the cancelled case, the expression fileName == $Canceled is comparing a symbol with a symbol (the same symbol) and so it can resolve to True. In the other case, it’s comparing a symbol with a string, and that is indeterminate (according to the designed semantics of Equal anyway). So that If cannot be resolved because the condition cannot be resolved to either True or False.
There are several possible fixes. One is to use the 4-argument form of If:
If[
fileName == $Canceled,
fileName = "Canceled",
fileName = "File has been found",
fileName = "File has been found"]
In this form, the last argument is the one that gets executed if the condition doesn’t resolve to either True or False.
Another fix is to use SameQ rather than Equal.
If[
fileName === $Canceled,
fileName = "Canceled",
fileName = "File has been found"]
SameQ checks for structural identity, and so it always resolves to True/False.