3.3. The if-else Statement

Suppose someone asks you if a number is even or odd. You just look at the last digit of the number. If it is 0, 2, 4, 6, or 8, you would say the number is even. Otherwise, if the last digit is 1, 3, 5, 7, or 9, you would say the number is odd. Because the computer doesn't have eyes, it must use other means to deter-mine if a number is even or odd. One simple approach is to have the computer divide the number by 2 and check for a remainder. If there is a remainder, the number is odd; otherwise it is even.

Recalling that the mod operator gives the remainder of one integer divided by another, you can write two tests for a number n like this:

if n mod 2 = 0 then
    display dialog "The number is even"
end if

if n mod 2≠ 0 then
    display dialog "The number is odd"
end if

If the remainder is 0, the program reports that the number is even. If the remainder is nonzero, the program reports that the number is odd. Realize that, in either case, only one of the display dialog statements is executed. That's because the number is either even or odd; it can't be both.

This notion of one condition occurring or not occurring can be handled more succinctly with AppleScript's if-else statement. The general format of this statement is

if Boolean-expression then
    statement
    statement
      ...
else
   statement
   statement
      ...
end if

When this statement is executed, Boolean-expression gets evaluated first. If the result is true, the statements that follow get executed until the else is reached. ...

Get Beginning AppleScript® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.