Python if else Statement
Table of Contents + β
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
ifpath. - If the answer is no (the condition is false), you take the
elsepath.
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.
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 passelse: # runs when the condition is False passLet us walk through the parts.
- The
if condition:line asks the yes-or-no question. It ends with a colon. - The indented lines under
ifrun only when the condition is true. - The
else:line has no condition. Just the wordelseand a colon. - The indented lines under
elserun 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:andelse: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 1So 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 = 20print(age >= 18) # is 20 greater than or equal to 18?
password = "secret"print(password == "secret") # is the password exactly "secret"?Output
TrueTrueSo 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: PassLogin 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 number0, 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, AlexIf 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 compareif age = 18: print("Exactly eighteen")
# β
Good: double == comparesif 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 wordelsestands alone. It never takes a question.
# β Avoid: else cannot have a conditionif age >= 18: print("Allowed")else age < 18: print("Not allowed")
# β
Good: else stands aloneif age >= 18: print("Allowed")else: print("Not allowed")- Forgetting the colon after
iforelse. Both lines must end with a colon, or Python raises aSyntaxError.
# β Avoid: missing colon after elseelse print("Not allowed")
# β
Good: colon is thereelse: print("Not allowed")- Not indenting the body. The lines under
elsemust be indented. If they sit at the same level aselse, Python cannot tell they belong to it and raises anIndentationError.
# β Avoid: body not indentedelse:print("Not allowed")
# β
Good: body is indentedelse: 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 tabif age >= 18: print("Allowed") print("Welcome")
# β
Good: every line uses the same 4 spacesif age >= 18: print("Allowed") print("Welcome")- Writing
elsewithout a matchingifabove it. Anelsecannot stand on its own. It always needs anifright 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
ifhandles one outcome, letelsehandle the opposite outcome clearly. The reader should see both sides at a glance. - Use
elseonly when you truly have a fallback. If nothing should happen when the condition is false, a plainifon its own is the cleaner choice. - Line up
ifandelseat 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
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
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
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
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.