![]() |
B.3 Conditionals |
So far, our programs have run from top to bottom. But what if we want our code to make choices? That's where conditionals come in. They allow your program to ask questions and perform different actions based on the answers. Let's learn how by checking the status of a video game character.
The most basic conditional is the IF/THEN
statement. It
checks if a condition is true, and if it is, it runs a block of
code. Let's check if our hero's health is critically low.
Because `health` is less than 10, the message is printed. If you changed `health` to 25, nothing would be printed.
What if the condition is false? An ELSE
statement lets
you run a different block of code in that case.
Sometimes you have more than two possibilities. You can chain
conditions together using ELSE IF
to create more complex
logic.
In SheerPower, a condition inside an `IF` must evaluate to
exactly true
(1) or false
(0). Unlike
some languages, you can't use just any non-zero number.
Wrong: x = 5
(This will fail)
if x then ...
Correct: x = 5
(This works because
if x <> 0 then ...x <> 0
evaluates to `true`)
When you need to check a single variable against
many possible values, a long `IF/ELSE IF` chain can get messy. The
SELECT CASE
statement is a cleaner and more efficient
way to handle this. Let's check our character's status effect.
IF
for a single condition.ELSE
to handle the "false" path.ELSE IF
for multiple, related conditions.SELECT CASE
for checking one variable
against many different values. It's cleaner and more readable.
Hide Description
|
|
Enter or modify the code below, and then click on RUN |
Looking for the full power of Sheerpower?
Check out the Sheerpower website. Free to download. Free to use. |