Skip to main content

Conditional Statements

Ah, the mighty conditional statements! Imagine you're the captain of a ship. As a captain, you make decisions like, “If there’s a storm, then steer away; otherwise, sail on!” These decision-making moments in programming are handled by the IF-THEN statements.

IF-THEN: Making Choices

The Basics

In pseudo-code, it looks like this:

IF Age > 18 THEN
OUTPUT "You are an adult."
ENDIF

And in Python:

if Age > 18:
print("You are an adult.")

Pretty straightforward, right? You check a condition (e.g., Age > 18), and if it’s true, you take an action.

A Real-World Scenario

Let’s say you’re planning a party (and yes, snacks are mandatory):

DECLARE Age : INTEGER
INPUT Age
IF Age >= 18 THEN
OUTPUT "Welcome to the party!"
ENDIF

Translated to Python:

Age = int(input("Enter your age: "))
if Age >= 18:
print("Welcome to the party!")

Now run this and see what happens if you try sneaking in underage!


ELSE: The Fork in the Road

But wait, what if someone doesn’t meet the criteria? You can’t just leave them hanging! This is where ELSE comes in:

IF Age >= 18 THEN
OUTPUT "Welcome to the party!"
ELSE
OUTPUT "Sorry, this party is for adults only."
ENDIF

In Python:

Age = int(input("Enter your age: "))
if Age >= 18:
print("Welcome to the party!")
else:
print("Sorry, this party is for adults only.")

It’s like a magical fork in the road: if the first path doesn’t work, the second one comes to the rescue.


ELSEIF: Handling Multiple Choices

Now, sometimes you have more than two options. Imagine you’re running a food stall, and the customer has three choices:

  • Chips
  • Burgers
  • Pizza

Here’s how you handle it:

DECLARE Choice : STRING
INPUT Choice
IF Choice = "Chips" THEN
OUTPUT "Here are your chips!"
ELSEIF Choice = "Burger" THEN
OUTPUT "Enjoy your burger!"
ELSEIF Choice = "Pizza" THEN
OUTPUT "Pizza coming right up!"
ELSE
OUTPUT "Sorry, we don’t have that."
ENDIF

In Python:

Choice = input("What would you like? Chips, Burger, or Pizza? ")
if Choice == "Chips":
print("Here are your chips!")
elif Choice == "Burger":
print("Enjoy your burger!")
elif Choice == "Pizza":
print("Pizza coming right up!")
else:
print("Sorry, we don’t have that.")

Go ahead, run this, and see if your code gets hungry!