Understanding Conditional Statements
Conditional statements are used to make decisions in programming. They allow the program to choose different paths of execution based on whether certain conditions are true or false.
Why Do We Need Conditional Statements?
Imagine writing a program to check if someone is eligible to vote. You need to check their age. This is a decision-making scenario — and that's exactly what conditional statements help with.
Types of Conditional Statements
- if — runs a block of code only if a condition is true
- else — runs a block of code if the condition in
if
is false - else if — tests multiple conditions sequentially
- nested if — an
if
inside anotherif
Example 1: Simple if Statement
Let’s check if a number is positive.
set number to 10
if number > 0 then
print "Number is positive"
Output:
Number is positive
What happens if the condition is false?
If the condition is not met, nothing happens unless you provide an else
block.
Example 2: if...else Statement
Let’s extend the previous logic to also say when the number is not positive.
set number to -5
if number > 0 then
print "Number is positive"
else
print "Number is not positive"
Output:
Number is not positive
Question:
What if you want to check for more than two conditions?
Answer:
You can use else if
to test additional conditions.
Example 3: if...else if...else
Check if a number is positive, negative, or zero.
set number to 0
if number > 0 then
print "Positive"
else if number < 0 then
print "Negative"
else
print "Zero"
Output:
Zero
Nested if Statements
Sometimes, one decision depends on another. This is where nested conditions are useful.
Example 4: Nested if
Check if a person is eligible to vote and if they have a voter ID.
set age to 22
set hasVoterID to true
if age >= 18 then
if hasVoterID is true then
print "Eligible to vote"
else
print "Get a voter ID first"
else
print "Not eligible to vote"
Output:
Eligible to vote
Things to Remember
- Conditions are evaluated top-down. The first
true
condition runs. - Use logical operators like AND, OR for combining multiple conditions.
- Always handle the default case with
else
.
Quick Quiz
Q: What will the following code print?
set temperature to 35
if temperature > 40 then
print "Very hot"
else if temperature > 30 then
print "Hot"
else
print "Normal"
A: Since 35 is not greater than 40 but is greater than 30, the output will be:
Hot
Conclusion
Conditional statements are essential in building logic into your programs. By combining if
, else if
, and else
, you can create intelligent decision-making flows that respond to various data inputs in real-time.