If, Else and Switch Explained with Pseudocode: Programming Fundamentals (7)
Learn If, Else, ElseIf, Switch, nested and compound conditions with runnable pseudocode, using examples like even numbers and leap years.
A conditional is an instruction that runs a group of lines only when a condition is true. With conditionals, a program stops treating every input the same way and starts making decisions. In this lesson you write programs that choose between two paths, between many paths, and between paths that depend on more than one fact at once.
In this lesson you will:
- Write simple and double conditionals with
If,Then,ElseandEndIf. - Chain many options with nested conditions and
ElseIf. - Pick one case out of many with
Switch. - Combine conditions with
And,OrandNot. - Use
Modto test if a number divides another one.
It takes about 40 minutes. Every example runs in the page.
Why programs need decisions
In the last lesson you built a program that converts seconds to a clock, like 1:2:5. It could not write 01:02:05, because that needs a decision: write a 0 only when the number is less than 10. A sequential program runs every line, every time. It cannot skip one.
Conditionals are also called selective structures or decision structures. They evaluate a condition, which is an expression that is either true or false, and choose what to run next. You learned to write these expressions in operators and expressions: n > 0, grade >= 10, unit = "km".
Most bugs that matter live in these decisions. A condition with > where it needed >= charges the wrong price, or lets in the wrong user. When an AI agent writes the code, you are the one who checks that every branch does what the business needs, including the edge cases nobody mentioned. You cannot check a branch you cannot read.
Simple conditionals
A simple conditional runs its lines when the condition is true, and does nothing when it is false. It starts with If, the condition and Then. It ends with EndIf.
The lines between Then and EndIf are the body. Indent them, so the reader sees which lines belong to the If. After EndIf, the program continues in sequence, whatever the condition was.
Here is a program that says if a number is even. A number is even when it divides by 2 with no remainder, so n Mod 2 = 0. In Operators and expressions this test only printed True or False. Now it decides which lines run.
Run it twice. With 8, the condition is true:
Enter a number:
8 is even
Done
With 7, the condition is false, so the program skips the body and writes only Done:
Enter a number:
Done
Double conditionals
Most of the time you want to do one thing when the condition is true and another thing when it is false. Add Else between the two groups of lines. The first group runs when the condition is true, and the group after Else runs when it is false.
Exactly one of the two groups runs. Never both, never neither.
A flow chart of an If. The program reads n and checks n Mod 2 = 0. When it is true it writes that n is even. When it is false and there is an Else, it writes that n is odd. When it is false and there is no Else, it skips to the next line after EndIf and writes nothing. Exactly one path runs each time.
Output
8 is even
With 7 you see:
Enter a number:
7 is odd
In Python, the same decision looks like this. Python uses indentation instead of EndIf:
n = int(input("Enter a number: "))
if n % 2 == 0:
print(n, "is even")
else:
print(n, "is odd")
Many options with ElseIf
Some problems have more than two answers. Is a number positive, negative or zero? You can put an If inside the Else of another If. This is a nested condition. It works, but each level pushes the code further to the right.
ElseIf writes the same logic as one flat chain. The program checks each condition from top to bottom and runs the first one that is true. If none is true, it runs the Else.
With 15 you see:
Enter the number to check:
The number is positive
Try -3 and 0 too. Each input runs exactly one branch.
Compound conditions
A compound condition joins two or more conditions with logical operators:
A And Bis true only when both are true.A Or Bis true when at least one is true.Not Ais true whenAis false.
A And B False
A Or B True
Not A False
| A | B | A And B | A Or B | Not A |
|---|---|---|---|---|
| True | True | True | True | False |
| True | False | False | True | False |
| False | True | False | True | True |
| False | False | False | False | True |
A classic example from the course is the leap year. A year is a leap year when it is divisible by 4 but not by 100, unless it is also divisible by 400. “Divisible by” means the remainder is zero, so you test it with Mod.
With 1900 you see:
Enter a year:
1900 is not a leap year
1900 divides by 4, but it also divides by 100 and not by 400, so it is not a leap year. Use parentheses when you mix And and Or. They make the order clear to the computer and to the next person who reads the code.
The same rule can also be a chain of questions. Ask the most specific question first.
With 2000 you see:
Enter a year:
2000 is a leap year
Both programs give the same answer for every year. The first is shorter. The second is easier to read one rule at a time. Pick the one your reader will understand faster.
Switch for one value
When every option compares the same variable with a fixed value, Switch is clearer than a long ElseIf chain. You write the variable once, then one case per value. A case can list several values separated by commas. Otherwise runs when no case matches. The whole block starts with Switch variable Do and ends with EndSwitch, and each case is a value followed by a colon.
Here is the calculator from class. The user picks the operation with one character.
With 12, * and 4 you see:
First number:
Operation (+, -, *, /):
Second number:
12 * 4 = 48
Both * and x multiply, because that case lists two values. Type % and the program falls into Otherwise. Switch only compares for equality. For ranges like “between 18.5 and 25”, use If and ElseIf. In Loops this calculator goes inside a loop, so the user can do many operations in a row.
Build a grade report
Now put it all together. This program comes from the course practice guide. It reads three exam grades, calculates the final grade and writes a message. Grades in Venezuela go from 0 to 20, and 10 is the minimum to pass.
1. Decide pass or fail
Start from the rounded average you wrote at the end of the last lesson. Add one If with an Else.
Press Run and type 8, 9 and 11.
You should see:
Grade of exam 1:
Grade of exam 2:
Grade of exam 3:
Average 9: failed
2. Add a scale with nested conditions
The guide asks for a weighted average. The exams weigh 30%, 35% and 35%, so you multiply each grade by its weight. Then it asks for four messages instead of two: 18 or more is “passed with excellence”, 14 or more is “passed”, 10 or more is a sufficient grade, and less than 10 is “failed”. Each Else holds the next question.
Press Run and type Juan Perez, 16, 18 and 20.
You should see:
Name:
Exam I (30%):
Exam II (35%):
Exam III (35%):
Juan Perez passed with excellence (18)
3. Flatten it with ElseIf
Three EndIf in a row are hard to follow. Replace the nesting with an ElseIf chain. The logic stays the same, and the output too.
Press Run and type Ana, 12, 10 and 9.
You should see:
Name:
Exam I (30%):
Exam II (35%):
Exam III (35%):
Ana passed with a sufficient grade (10)
An ElseIf chain checks its conditions from top to bottom and runs only the first one that is true. With the correct order, an average of 19 matches average greater than or equal to 18 and gets passed with excellence. With the wrong order, where greater than or equal to 10 comes first, 19 stops at that first condition and gets passed with a sufficient grade.
-
If average >= 18 Thenresult <- "passed with excellence" true: this runs -
ElseIf average >= 14 Thenresult <- "passed" skipped -
ElseIf average >= 10 Thenresult <- "passed with a sufficient grade" skipped -
Elseresult <- "failed" skipped
result = "passed with excellence"
4. Reject grades out of range
A grade of 25 makes no sense on a scale from 0 to 20. Check the input before you use it. A grade is wrong when it is less than 0 or greater than 20, and the input is wrong when any grade is wrong. That is a compound condition with Or.
Press Run and type Ana, 16, 25 and 20.
You should see:
Name:
Exam I (30%):
Exam II (35%):
Exam III (35%):
Every grade must be between 0 and 20
Common mistakes
If you see A condition has to be Boolean, and this one is Integer: compare explicitly, for example "… <> 0"., it means the condition is a number, not a true or false value. You probably wrote If n Mod 2 Then. Compare the result: If n Mod 2 = 0 Then.
If you see An expression is missing here: I found "<"., it means a comparison lost its left side. n > 0 And < 10 reads well in English, but each comparison needs both sides: n > 0 And n < 10.
If you see "EndIf" is missing: the "If" on line 4 is never closed., add the EndIf. Every If needs exactly one, no matter how many ElseIf it has.
If a grade of 19 says “sufficient”, your ElseIf chain is in the wrong order. The chain stops at the first true condition, and 19 is also >= 10. Put the most demanding condition first. The computer gives no error here. The code runs and the answer is wrong. This is a logic error, and only a person who reads the conditions can find it.
If or Switch
Both choose between paths. Use the one that matches the shape of the question.
| The question is | Use |
|---|---|
| Is something true? | If |
| This or that? | If with Else |
| Which range is the value in? | If with ElseIf |
| Do several facts hold at once? | If with And, Or, Not |
| Which exact value does one variable have? | Switch |
A conditional chooses once. If you need to do something again and again, like asking until the input is valid, that is a loop, the topic of the next lesson.
Practice exercises
Try each one in an empty editor first. The numbers in your output must match. Your messages can differ.
Finish the clock
Go back to the seconds converter from the last lesson. Write each part with two digits. Hint: WriteNoNewline writes without moving to a new line, so you can write a 0 first only when the number is less than 10.
Input 3725 gives:
Enter the number of seconds:
01:02:05
Body mass index
Ask for a name, the height in meters and the weight in kilograms. The body mass index (BMI) is the weight divided by the height squared. Less than 18.5 is underweight. From 18.5 to less than 25 is a normal weight. From 25 to less than 30 is overweight. 30 or more is obesity. Show the BMI with one decimal.
Inputs Juan Perez, 1.8 and 78 give:
Name:
Height (meters):
Weight (kilograms):
Juan Perez has a normal weight and a BMI of 24.1
Even and multiples
Ask for a number. Write every label that applies: “Even”, “Multiple of 3” and “Multiple of 10”. A number can have none, one or all three. This is why you need three separate If, not one ElseIf chain.
Input 30 gives:
Enter a number:
n = 30, Even, Multiple of 3, Multiple of 10
These editors run on StepCode, the pseudocode language I built for my students at UCAB.
What you learned
Ifruns its body only when the condition is true.Elsegives the other path, and exactly one path runs.ElseIfchecks conditions from top to bottom and stops at the first true one, so order matters.Switchpicks a case by the exact value of one variable.Otherwisecatches the rest.And,OrandNotjoin conditions. Use parentheses when you mix them.n Mod d = 0tests ifndivides byd. It powers even numbers, multiples and leap years.
Next steps
Your programs can now decide, but each line still runs at most once. In the next lesson, loops, you repeat instructions with While, Repeat and For, and build programs like a factorial, a multiplication table and a prime number checker.