Beginner Chapter 58 · 20 min read · Module 5: Control Flow
if-else Statement
- After this chapter you can write an if-else statement with correct indentation.
- You can explain why exactly one of the two blocks always runs.
- You can combine comparisons with and, or and not in a condition.
- You can use the one-line conditional expression for simple choices.
Programs often have to choose between two actions. Is the exam mark enough to pass? Is the number even? Is the user old enough to enter? The if-else statement is the basic tool for these two-way choices.
In this chapter you will see how the condition is checked, how the else block acts as a catch-all, and how to avoid the mistakes beginners make with indentation and colons. You will also meet the compact conditional expression.
Why we need two paths
A plain if statement runs some code only when a condition is true. When the condition is false, the program simply moves on and does nothing special. Many real decisions need a second path: if the password is right, let the user in, otherwise show an error. The else clause gives your program that second path.
if block runs, otherwise the else block runs. Exactly one of the two blocks always runs.The word else has no condition of its own. It is a catch-all for every case where the if condition was false. It must line up (same indentation) with the if it belongs to, and it must be followed by a colon and an indented block.
marks = 42
if marks >= 40:
print('Pass')
else:
print('Fail')
print('Done')How Python reads the condition
Python evaluates the condition and converts the result to a truth value. Comparisons such as >=, == and != give True or False directly. Other values are also accepted: zero, an empty string, an empty list and None count as false, while most other values count as true. This lets you write short checks such as if name: to test that a string is not empty.
name = ''
if name:
print('Hello', name)
else:
print('Name is missing')
items = [1, 2]
if items:
print('Has', len(items), 'items')
else:
print('Empty list')Using input with if-else
Programs become useful when the decision depends on data from the user. Remember that input() always returns a string, so convert it with int() or float() before you compare numbers. The example below tests whether a number is even by looking at the remainder after dividing by 2.
n = int(input())
if n % 2 == 0:
print(n, 'is even')
else:
print(n, 'is odd')| Condition | Block that runs |
|---|---|
| True | the if block |
| False | the else block |
| Both at once | never possible |
| Neither | never possible |
Combining conditions
You can build bigger conditions with and, or and not. With and both parts must be true. With or at least one part must be true. This is handy for range checks, such as testing that an age is at least 18 and below 65. Python also lets you chain comparisons, so 18 <= age < 65 means the same thing and reads more like normal maths.
age = 30
if 18 <= age < 65:
print('Working age')
else:
print('Outside working age')The conditional expression
When each branch only picks a value, Python offers a one-line form called the conditional expression: value_if_true if condition else value_if_false. It is an expression, so you can use it inside print() or on the right side of an assignment. Keep it for short, simple choices. If the branches need several statements, use the full if-else block because it is easier to read.
temp = 35
label = 'hot' if temp > 30 else 'comfortable'
print(label)
print('even' if 10 % 2 == 0 else 'odd')elif (the next chapter) instead of stacking several separate if statements.Common patterns
- Validation: accept good input, reject bad input with a message.
- Default values: use a fallback when something is missing or empty.
- Binary decisions: even or odd, positive or not, adult or minor, logged in or not.
- Early choices: choose which message, price or label to use before printing it.
A good habit is to write the condition so it reads like a plain English sentence. Names such as is_member or has_discount make if is_member: obvious without comparing to True. Avoid writing if x == True:; just write if x:. Also avoid repeating the opposite check in else, for example if x > 5: followed by else: and then if x <= 5:. The else already means the opposite, so the second check is redundant.
Python syntax
if condition:
statements_when_true
else:
statements_when_falseresult = value_if_true if condition else value_if_falseReal-world applications
- Login checks: correct password or error message.
- Shop programs: apply a discount or charge full price.
- Games: win or lose, alive or game over.
- Forms: accept valid data or ask the user to try again.
Common mistakes
Fix: Both lines must end with a colon, then the block is indented below.
else x > 5:Fix: else never takes a condition. Use elif if you need another test.
Fix: = assigns a value; == compares two values. Python reports a syntax error for
if x = 5:.Fix: input() returns text. Use int() or float() before comparing with numbers.
Fix: Line up else exactly under the if it belongs to.
Important tips
- Read the condition aloud as a sentence to check it.
- Use clear names like is_adult for boolean variables.
- Keep each block short; move long work into functions.
- Test both paths: one input that is true and one that is false.
Key points summary
- else runs when the if condition is false.
- Exactly one of the two blocks runs.
- else has no condition and needs a colon.
- Empty values (0, '', [], None) count as false.
- The conditional expression is
a if cond else b.
Exam and interview points
- Python uses indentation, not braces, to mark the blocks.
- The else clause is optional and never has a condition.
- A conditional expression is an expression and produces a value.
- Chained comparison
a < b < cis allowed in Python. - Falsy values: 0, 0.0, '', [], (), {}, set(), None, False.
Quick revision
- if cond: ... else: ... gives two paths.
- One and only one block runs.
- else = everything the if did not match.
- Convert input() before numeric tests.
- Short choices:
x if cond else y.
Frequently asked questions
Is else required after if?
No. An if can stand alone. Add else only when you need an action for the false case.
Can I put an if-else inside another if-else?
Yes. That is called nesting and is covered in a later chapter.
What is the difference between if-else and two separate if statements?
With if-else the second block runs only when the first condition is false. Two separate ifs are both checked, so both blocks might run.
Does else need to come right after the if block?
Yes. else must follow directly after the if block at the same indentation, with no other statements between them.
Can the conditional expression replace all if-else statements?
No. It only chooses between two values. Use the full statement when you need to run several lines.
Practise this chapter
22 practice questions Take the chapter quiz