LessonsBeginner: First stepsLesson 8

Making decisions

Let a program choose what to do with if, then, else and else if.

  • Beginner
  • Lesson 8 of 83
  • About 8 minutes
  • 6 examples

If this, then that

Programs become interesting when they decide. if checks a condition, and runs the lines up to end if only when it is true.

ExampleRun it in the playground
put 72 into tScore
if tScore >= 50 then
   put "You passed"
end if
if tScore >= 90 then
   put "With distinction"
end if
put "Done"
Output
You passed
Done

The condition is anything that is true or false: a comparison, or a variable holding one. The lines inside are indented by three spaces so that you can see at a glance what belongs to the if; the Script Editor does that for you.

Otherwise: else

else gives the lines to run when the condition is false. One of the two always runs, never both.

ExampleRun it in the playground
put 7 into tNumber
if tNumber mod 2 is 0 then
   put tNumber && "is even"
else
   put tNumber && "is odd"
end if
Output
7 is odd

Several choices: else if

To choose between more than two things, chain else if. xTalk checks each condition in turn, from the top, and runs the first one that is true; the final else catches everything else.

ExampleRun it in the playground
put 64 into tTemperature
if tTemperature >= 80 then
   put "Hot"
else if tTemperature >= 60 then
   put "Warm"
else if tTemperature >= 40 then
   put "Cool"
else
   put "Cold"
end if
Output
Warm

Short forms

When there is only one thing to do, the whole if can go on one line, with no end if. An else then goes at the start of the next line.

ExampleRun it in the playground
put 7 into tLives
if tLives > 5 then put "Plenty of lives"
if tLives > 10 then put "Too many lives"
else put "Not too many"
Output
Plenty of lives
Not too many

Decisions inside decisions

An if can hold another if. The indentation shows which else belongs to which.

ExampleRun it in the playground
put true into tSignedIn
put "admin" into tRole
if tSignedIn then
   if tRole is "admin" then
      put "Welcome back, administrator"
   else
      put "Welcome back"
   end if
else
   put "Please sign in"
end if
Output
Welcome back, administrator

Try it yourself

Turn a test score into a grade: 90 or more is A, 80 or more is B, 70 or more is C, and anything lower is D. Try it with a score of 83.

Show a solution
ExampleRun it in the playground
put 83 into tScore
if tScore >= 90 then
   put "A"
else if tScore >= 80 then
   put "B"
else if tScore >= 70 then
   put "C"
else
   put "D"
end if
Output
B

Words in this lesson

Each one finds every lesson that uses it. The Dictionary has the whole story of each, with its syntax and more examples.