If/Else Statement

An if/else statement lets a program make decisions. It checks a condition and runs different code depending on whether that condition is true or false.

        ┌─────────────┐
        │  condition  │
        └──────┬──────┘
          true │ false
       ┌───────┴───────┐
       ▼               ▼
  ┌─────────┐     ┌─────────┐
  │ if block│     │else block│
  └─────────┘     └─────────┘

If#

The simplest form is a single if. The block runs only if the condition is true. If it’s false, nothing happens.

int score = 10;

if (score == 10)
{
    Console.WriteLine("You got a perfect score!");
}
score = 10

if score == 10:
    print("You got a perfect score!")
let score = 10;

if (score === 10) {
    console.log("You got a perfect score!");
}

If/Else#

Adding else gives the program a fallback. If the condition is false, the else block runs instead.

int score = 7;

if (score == 10)
{
    Console.WriteLine("You got a perfect score!");
}
else
{
    Console.WriteLine("You didn't get a perfect score.");
}
score = 7

if score == 10:
    print("You got a perfect score!")
else:
    print("You didn't get a perfect score.")
let score = 7;

if (score === 10) {
    console.log("You got a perfect score!");
} else {
    console.log("You didn't get a perfect score.");
}

Only one block ever runs — never both.

Else If#

When there are more than two possible outcomes, you can chain conditions with else if. Each condition is checked in order. The first one that is true runs, and the rest are skipped.

int score = 7;

if (score == 10)
{
    Console.WriteLine("Perfect score!");
}
else if (score >= 5)
{
    Console.WriteLine("Good score.");
}
else
{
    Console.WriteLine("Keep practicing.");
}
score = 7

if score == 10:
    print("Perfect score!")
elif score >= 5:
    print("Good score.")
else:
    print("Keep practicing.")
let score = 7;

if (score === 10) {
    console.log("Perfect score!");
} else if (score >= 5) {
    console.log("Good score.");
} else {
    console.log("Keep practicing.");
}

You can have as many else if branches as needed. The final else is optional — it acts as a catch-all if none of the conditions above it are true.

Comparison Operators#

Conditions are built using comparison operators:

OperatorMeaning
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

Don’t confuse = (assignment) with == (comparison). Writing score = 10 sets the variable. Writing score == 10 checks if it equals 10.

Resources#