Python if else Statement

In the last lesson you learned the if Statement, where a block of code runs only when a condition is true. That is great. But what about the other side? Right now, when the condition is false, your program just does nothing and moves on. Often you want it to do something else instead. That is exactly what else is for.

πŸ€” Why You Need else

Imagine a gate at a theme park. If a visitor is tall enough, the gate opens. But if they are not tall enough, you do not want silence. You want a clear β€œSorry, you cannot go on this ride” message.

So with only if, you cover one case and leave the other one empty:

  • The β€œtall enough” case is handled. The gate opens, the visitor is happy.
  • The β€œnot tall enough” case slips through with no response. The program just stays quiet.
  • That silence feels like a bug. The visitor is left standing there, not knowing what happened.

The fix is simple. The else block gives you that missing path. It runs when the if condition is false. So your program always does one thing or the other. Never nothing.

🧩 What if else Really Means

Think of if else as a fork in the road. You walk up to it and there are two paths. You can only take one. Which one you take depends on the answer to a single yes-or-no question.

  • If the answer is yes (the condition is true), you take the if path.
  • If the answer is no (the condition is false), you take the else path.

There is no way to take both. There is no way to take neither. One path always wins. This is what we call a two-way choice.

Here is the key thing to notice. The else keyword has no condition of its own. It does not ask a question. It simply catches every case where the if was false. It is the β€œeverything else” path.

Here is that same idea as a picture. Read it top to bottom.

Yes

No

Check the condition

Is it True?

Run the if block

Run the else block

Continue the rest of the program

See how the two arrows out of the diamond never meet in the middle? You go down one side or the other. Then both sides join back up and the program keeps going. That is the whole shape of if else.

🧱 The Syntax

Here is the shape of an if else block. Read it slowly.

if condition:
# runs when the condition is True
pass
else:
# runs when the condition is False
pass

Let us walk through the parts.

  • The if condition: line asks the yes-or-no question. It ends with a colon.
  • The indented lines under if run only when the condition is true.
  • The else: line has no condition. Just the word else and a colon.
  • The indented lines under else run only when the condition is false.

Notice that else lines up directly under if. They are at the same level. The colon after else is required. And the body under it must be indented, just like the if body.

The colon and the indentation are not decoration

This part trips up a lot of people coming from other languages, so let us slow down on it.

  • The colon at the end of if condition: and else: tells Python β€œa block is starting now”. You cannot skip it.
  • The indentation (the spaces at the start of the line) tells Python which lines are inside the block. Most languages use curly braces { } for this. Python uses indentation instead.
  • The standard is 4 spaces per level. Pick that and stick with it everywhere.

So what happens if you forget the colon? Python stops right away and tells you the line looks wrong.

if age >= 18
print("Allowed")

Output

File "vote.py", line 1
if age >= 18
^
SyntaxError: expected ':'

And if you forget to indent the body? Python expects an indented line and does not find one, so it raises an IndentationError.

if age >= 18:
print("Allowed")

Output

File "vote.py", line 2
print("Allowed")
^
IndentationError: expected an indented block after 'if' statement on line 1

So the colon and the indentation are doing real work. They are how Python knows where a block begins and ends.

πŸ”Ž How the Condition Is Checked

Before we look at examples, let us be clear about what a condition actually is. A condition is anything that ends up as either True or False. Those two are special values in Python called booleans. That is the only thing if cares about.

Most conditions use a comparison. The comparison runs first, then if reads the True or False result. Here are a couple you will use all the time.

age = 20
print(age >= 18) # is 20 greater than or equal to 18?
password = "secret"
print(password == "secret") # is the password exactly "secret"?

Output

True
True

So age >= 18 is not magic. It is a question that Python answers with True or False first. Then if takes that answer and picks a path. Notice the == in the second one. That is a comparison, β€œare these two equal?”. A single = means something completely different, and we will come back to that in Common Mistakes.

βœ… A Clear Example

Let us check whether someone is old enough to vote. The rule is simple. Age 18 or above is allowed. Anything below that is not.

age = 20
if age >= 18:
print("You are allowed to vote.")
else:
print("You are not allowed to vote.")

Here age is 20. The condition age >= 18 asks β€œis 20 greater than or equal to 18?” The answer is yes. So the if path runs.

Output

You are allowed to vote.

Now watch what happens when we change the age. Same code, just a younger value this time.

age = 15
if age >= 18:
print("You are allowed to vote.")
else:
print("You are not allowed to vote.")

This time age is 15. The condition age >= 18 asks β€œis 15 greater than or equal to 18?” The answer is no. So Python skips the if body and runs the else body instead.

Output

You are not allowed to vote.

See the pattern? One value gave us the first message. The other value gave us the second. The program always says something. That is the whole point of else.

Tip

Only one of the two blocks ever runs. Python checks the condition once, picks a path, and ignores the other path completely.

πŸ–₯️ More Real Examples

One example is never enough to make a thing stick. So let us run through a few that you would actually meet in real code.

Pass or fail on a score

A student wrote a test. Say 40 marks or more is a pass. Below that is a fail.

score = 72
if score >= 40:
print("Result: Pass")
else:
print("Result: Fail")

The score is 72, and 72 >= 40 is true, so the if block runs.

Output

Result: Pass

Login allowed or denied

Now Riya is logging into an app. We check her password against the correct one. Then we greet her or stop her.

correct_password = "openSesame"
entered_password = "openSesame"
if entered_password == correct_password:
print("Welcome back, Riya!")
print("You are now logged in.")
else:
print("Wrong password.")
print("Please try again.")

Notice each path here has two lines, not one. That is fine. A block can hold as many lines as you want, as long as they are all indented the same way. The entered password matches the correct one, so the condition is true and the if block runs.

Output

Welcome back, Riya!
You are now logged in.

If someone typed the wrong password, the condition would be false. Then both else lines would run instead. The login flow always gives feedback, so it never feels half-finished.

Even or odd number

Here is a classic. We want to know if a number is even or odd. The trick is the % operator, which gives the remainder after dividing. If a number divided by 2 leaves no remainder, it is even.

number = 7
if number % 2 == 0:
print("That is an even number.")
else:
print("That is an odd number.")

7 % 2 is 1, and 1 == 0 is false, so the else block runs.

Output

That is an odd number.

Ticket price for adult or child

One more. A cinema charges a different ticket price for adults and children. Anyone under 12 pays the child price.

age = 9
if age < 12:
price = 8
print("Child ticket:", price)
else:
price = 12
print("Adult ticket:", price)

The age is 9, and 9 < 12 is true, so the child branch runs and sets the price to 8.

Output

Child ticket: 8

🟒 if Also Runs on Truthy Values

Here is something handy to know. The thing after if does not have to be a comparison. if will happily take a plain value too, and decide on its own whether it counts as true or false. Python calls these truthy and falsy values.

The rule is short:

  • Empty things are falsy: an empty string "", the number 0, an empty list [].
  • Anything with content is truthy: a non-empty string like "Alex", any number that is not zero, a list with items in it.

So you can check β€œdid the user actually type a name?” just by handing the name to if.

name = "Alex"
if name:
print("Hello,", name)
else:
print("You did not enter a name.")

name holds "Alex", which is a non-empty string, so it counts as truthy and the if block runs.

Output

Hello, Alex

If name had been an empty string "", it would count as falsy, and the else block would run instead. Keep this simple for now. Just remember that empty means false and non-empty means true.

⚠️ Common Mistakes

A few small slips trip up almost everyone when they start with else. Here is what to watch for.

The biggest one of all is using = instead of == in a condition. A single = means β€œput this value into the variable”. A double == means β€œare these two equal?”. Inside an if you almost always want ==.

# ❌ Avoid: single = tries to assign, not compare
if age = 18:
print("Exactly eighteen")
# βœ… Good: double == compares
if age == 18:
print("Exactly eighteen")

The wrong version is not even allowed inside a condition, so Python stops with a SyntaxError.

Output

File "vote.py", line 2
if age = 18:
^^^^^^^^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

Now the rest of the slips, the small ones:

  • Putting a condition after else. The word else stands alone. It never takes a question.
# ❌ Avoid: else cannot have a condition
if age >= 18:
print("Allowed")
else age < 18:
print("Not allowed")
# βœ… Good: else stands alone
if age >= 18:
print("Allowed")
else:
print("Not allowed")
  • Forgetting the colon after if or else. Both lines must end with a colon, or Python raises a SyntaxError.
# ❌ Avoid: missing colon after else
else
print("Not allowed")
# βœ… Good: colon is there
else:
print("Not allowed")
  • Not indenting the body. The lines under else must be indented. If they sit at the same level as else, Python cannot tell they belong to it and raises an IndentationError.
# ❌ Avoid: body not indented
else:
print("Not allowed")
# βœ… Good: body is indented
else:
print("Not allowed")
  • Mixing tabs and spaces. To your eyes a tab and four spaces can look the same. To Python they are different. If you indent one line with spaces and the next with a tab, Python gets confused and raises a TabError. So pick spaces, four of them, and never switch.
# ❌ Avoid: first line spaces, second line a tab
if age >= 18:
print("Allowed")
print("Welcome")
# βœ… Good: every line uses the same 4 spaces
if age >= 18:
print("Allowed")
print("Welcome")
  • Writing else without a matching if above it. An else cannot stand on its own. It always needs an if right before it to attach to.

βœ… Best Practices

Small habits keep your if else blocks clean and easy to read.

  • Always use four spaces to indent, and keep it the same everywhere. Most editors do this for you if you set the tab key to insert spaces. This one habit kills tab-versus-space bugs for good.
  • Keep the two paths balanced. If the if handles one outcome, let else handle the opposite outcome clearly. The reader should see both sides at a glance.
  • Use else only when you truly have a fallback. If nothing should happen when the condition is false, a plain if on its own is the cleaner choice.
  • Line up if and else at the same indentation. This makes the fork in the road obvious to anyone reading the code.
  • Keep each block short. If a path grows large, that is usually a sign to move that work into a function later on.

🧩 What You’ve Learned

βœ… The else block runs when the if condition is false, so your program always picks one path or the other.

βœ… if else is a two-way choice. One block runs and the other is skipped, never both and never neither.

βœ… The colon and the indentation are how Python marks a block. A missing colon gives a SyntaxError, and a missing indent gives an IndentationError.

βœ… A condition is anything that ends up True or False. Even plain values work, because empty things are falsy and non-empty things are truthy.

βœ… Use == to compare, not =. And use four spaces everywhere, never mixed tabs and spaces.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    When does the code inside an else block run?

    Why: The else block runs exactly when the if condition turns out to be false.

  2. 2

    What is special about the else line compared to if?

    Why: else takes no condition; it simply catches every case where the if was false.

  3. 3

    Which of these values is falsy in an if condition?

    Why: Empty things are falsy: an empty string, 0, and an empty list all count as false.

  4. 4

    Given age = 16, what does `if age >= 18: print('Allowed')` `else: print('Not allowed')` print?

    Why: Since 16 is not greater than or equal to 18, the condition is false and the else block runs.

πŸš€ What’s Next?

You can now handle two paths. But what about three or more, like a grade of A, B, or C? For that you chain conditions together, and Python has a neat keyword for it.

elif Statement

Share & Connect