Lesson 1.4: Deciding: conditions
A program doesn't always do the same thing. With a condition it chooses what to do based on the data.
The idea
A condition is a yes-or-no question: is the age 18 or more? The answer is True or False, and depending on it the program does one thing or another.
If … Then
If age ≥ 18 Then
Write "You can vote"
EndIf
If the condition is true, it does what's inside. If it's false, it skips it.
What's inside is indented, so you can see what depends on the condition.
Else: the other path
Algorithm Vote
Write "How old are you?"
Read age
If age ≥ 18 Then
Write "You can vote"
Else
Write "You can't vote yet"
EndIf
EndAlgorithm
It always takes one of the two paths, never both.
Comparisons
| Symbol | Question |
|---|---|
= | Are they equal? |
≠ | Are they different? |
< and > | Is it less? Is it greater? |
≤ and ≥ | Is it less or equal? Is it greater or equal? |
Combining conditions
And: true if both are.age ≥ 18 And hasIdOr: true if at least one is.day = "Saturday" Or day = "Sunday"Not: flips it.Not raining
Try it
Ask for a number and write whether it's positive, negative or zero. Hint: an Else can hold another If.
Show the solution
Algorithm Sign
Write "Type a number:"
Read n
If n > 0 Then
Write "Positive"
Else
If n < 0 Then
Write "Negative"
Else
Write "Zero"
EndIf
EndIf
EndAlgorithm
Summary
- A condition is a question that gives
TrueorFalse. If … Thendoes something only when it's true;Elseis the other path.And,OrandNotcombine or flip conditions.