Sheerpower Logo

B.3  Conditionals


Making Decisions with 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.

1. The Simple `IF/THEN` Statement

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.

health = 9 if health < 10 then print "Health is critical! Use a potion!" end if

Because `health` is less than 10, the message is printed. If you changed `health` to 25, nothing would be printed.

2. Adding an `ELSE` for the Other Path

What if the condition is false? An ELSE statement lets you run a different block of code in that case.

health = 55 if health < 10 then print "Health is critical! Use a potion!" else print "You are healthy enough to continue." end if

Flowchart: How `IF/ELSE` Works

Start
health < 10?
→ TRUE
Print "Critical!"
→ FALSE
Print "Healthy."
End

3. Handling Multiple Conditions with `ELSE IF`

Sometimes you have more than two possibilities. You can chain conditions together using ELSE IF to create more complex logic.

health = 45 if health < 10 then print "Health is critical! Use a potion!" else if health < 50 then print "Warning: Your health is getting low." else print "You are in good shape." end if

Important SheerPower Rule!

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
if x then ...
(This will fail)

Correct: x = 5
if x <> 0 then ...
(This works because x <> 0 evaluates to `true`)

4. Handling Many States with `SELECT CASE`

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.

status$ = "Poisoned" select case status$ case "Normal" print "Character is fine." case "Poisoned" print "Character is taking damage over time!" case "Frozen", "Stunned" print "Character cannot move!" case else print "Unknown status effect." end select

Flowchart: How `SELECT CASE` Works

Start
What is status$?
→ "Poisoned"
Action A
→ "Frozen"
Action B
→ "Normal"
Action C
End
Summary: You now know how to control the flow of your program!
  • Use IF for a single condition.
  • Add ELSE to handle the "false" path.
  • Use ELSE IF for multiple, related conditions.
  • Use 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.