Skip to content
Programming contents

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

Pseudocode
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

Pseudocode
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

SymbolQuestion
=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 hasId
  • Or: true if at least one is. day = "Saturday" Or day = "Sunday"
  • Not: flips it. Not raining

Try it

Exercise

Ask for a number and write whether it's positive, negative or zero. Hint: an Else can hold another If.

Show the solution
Pseudocode
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 True or False.
  • If … Then does something only when it's true; Else is the other path.
  • And, Or and Not combine or flip conditions.