In this Python tutorial, we will learn about the if-else statement in Python, its syntax, how indentation controls the if and else blocks, and how to write conditions using comparison and logical operators. We will also look at elif, nested if-else statements, and common mistakes beginners make.
Python if-else statement for choosing between two code paths
A Python if-else statement is used when a program has to choose between two possible blocks of code. The if block runs when the condition is True. The else block runs when the same condition is False.
For example, when checking whether a number is even or odd, only one of the two results should be printed. This is a typical use case for an if-else statement.
Python if-else syntax with indentation
The syntax of if-else statement is
if <condition>:
statement(s)
else:
statement(s)
where condition could be an expression that evaluates to a boolean value.
When interpreter enter if-else statement, it first evaluates the condition. If condition is True, statement(s) inside if block execute, or if condition is False, statements(s) inside else block execute.
The colon : after if and else is required. The statements inside each block must be indented consistently. Python does not use curly braces for blocks; indentation decides which statements belong to the if block and which statements belong to the else block.
Python if-else condition values: True, False, and expressions
The condition in an if-else statement can be a direct boolean value, a comparison, or a compound expression. Most beginner programs use comparison operators such as ==, !=, >, <, >=, and <=.
| Operator | Meaning in a Python if-else condition | Example |
|---|---|---|
== | Equal to | age == 18 |
!= | Not equal to | status != "closed" |
> | Greater than | marks > 40 |
< | Less than | temperature < 0 |
>= | Greater than or equal to | score >= 50 |
<= | Less than or equal to | items <= 10 |
You can also combine two or more conditions using and, or, and not. These logical operators are useful when one decision depends on more than one rule.
Python if-else flowchart for True and False branches
The working of if-else statement in Python is shown in the following picture.
The condition is tested first. If the result is True, Python skips the else block. If the result is False, Python skips the if block and executes the else block.
Python if-else examples with output
1. Python if-else program to check if a number is even or odd
In the following program, we write an if-else statement where the condition checks if given number is even.
Example.py
n = 4
if n%2 == 0:
print(f'{n} is even number.')
else:
print(f'{n} is odd number.')
Output
4 is even number.
Note : Observe the indentation and alignment of the statements inside the if-block and else-block. Unlike programming languages like Java or C programming, where the statements are enclosed in curly braces, Python considers the alignment of statements as block representation.
Now, let us take a value for n, such that the condition becomes false.
Example.py
n = 3
if n%2 == 0:
print(f'{n} is even number.')
else:
print(f'{n} is odd number.')
Output
3 is odd number.
Since we have taken a value for n such that the condition n%2 == 0 becomes False, the statement(s) inside else block were executed.
2. Python if-else program to choose a car based on money available
In the following program, we write an if-else statement to choose a car based on the money we have to spend.
Example.py
money = 125000
if money > 100000:
print("Buy Premium Car.")
else:
print("Buy Budget Car.")
Output
Buy Premium Car.
Here, money > 100000 evaluates to True, so the statement inside the if block is executed.
3. Python if-else statement with two conditions using and
Use and when both conditions must be true. In the following example, the user can access the page only when the user is logged in and the account is active.
Example.py
is_logged_in = True
is_active = True
if is_logged_in and is_active:
print("Access allowed.")
else:
print("Access denied.")
Output
Access allowed.
If either is_logged_in or is_active is False, the complete condition becomes False and the else block runs.
4. Python if-else statement with two conditions using or
Use or when at least one condition must be true. In this example, a discount is applied when the customer is a member or the order amount is high enough.
Example.py
is_member = False
order_amount = 2500
if is_member or order_amount >= 2000:
print("Discount applied.")
else:
print("No discount.")
Output
Discount applied.
Python elif with if-else for more than two choices
Use elif when you need to test another condition after the first if condition is false. Python uses elif, not elseif. The else block is optional and is used as the final fallback when none of the earlier conditions are true.
The syntax of an if, elif, and else chain is:
if condition_1:
statement(s)
elif condition_2:
statement(s)
else:
statement(s)
Only one matching block is executed in an if–elif–else chain. Once Python finds a true condition, it runs that block and skips the remaining branches.
Example.py
number = -8
if number > 0:
print("Positive number")
elif number == 0:
print("Zero")
else:
print("Negative number")
Output
Negative number
Python elif versus separate if statements
Use elif when the conditions are part of the same decision and only one result should happen. Use separate if statements when each condition should be checked independently.
In the following example, the grade categories are mutually exclusive, so elif is the right choice.
Example.py
marks = 76
if marks >= 90:
print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Needs improvement")
Output
Grade B
Although marks >= 50 is also true, Python does not execute that branch because the earlier marks >= 75 branch has already matched.
Nested if-else statement in Python
A nested if-else statement is an if-else statement written inside another if block or else block. Use nesting when a second decision should be made only after the first decision is satisfied.
Example.py
age = 20
has_id = True
if age >= 18:
if has_id:
print("Entry allowed.")
else:
print("ID required.")
else:
print("Entry not allowed.")
Output
Entry allowed.
Nested if-else statements are valid, but deep nesting can make code hard to read. When possible, combine simple conditions with and or split the logic into functions.
Python shorthand if-else conditional expression
Python also supports a one-line conditional expression. This is commonly called shorthand if-else or a ternary conditional expression. Use it for simple value selection, not for long blocks of logic.
value_if_true if condition else value_if_false
Example.py
age = 17
message = "Adult" if age >= 18 else "Minor"
print(message)
Output
Minor
This form is useful when assigning a value based on a condition. For multiple statements, prefer the normal multi-line if-else syntax.
Common Python if-else mistakes and fixes
- Missing colon: Write
if condition:andelse:, not justif condition. - Wrong indentation: Keep all statements in the same block aligned with the same number of spaces.
- Using
=instead of==: Use==for comparison. The single equals sign is for assignment. - Writing
elseif: Python useselif. - Adding a condition after
else: Theelsebranch has no condition. Useeliffor another condition.
Python if-else editorial QA checklist
- Does every Python if-else example use a colon after
if,elif, andelse? - Are all statements inside each Python block indented consistently?
- Do output blocks show only the result printed by the corresponding Python program?
- Is
elifused for one decision with multiple possible outcomes? - Are examples with two conditions clear about whether
andororis required?
Frequently asked questions about Python if-else statements
Is it elseif or elif in Python?
Python uses elif. The keyword elseif is not valid Python syntax. Use elif after an if block when you want to check another condition.
What is the difference between elif and else in Python?
elif has a condition and is checked only if the previous if or elif condition is false. else has no condition and runs only when none of the earlier conditions are true.
How do I write a Python if statement with two conditions?
Use and when both conditions must be true. Use or when at least one condition must be true. For example, if age >= 18 and has_id: checks two conditions in the same if statement.
When should I use elif instead of multiple if statements?
Use elif when the conditions belong to the same decision and only one branch should run. Use multiple if statements when each condition must be checked independently.
Can I write an if-else statement inside another if-else statement in Python?
Yes. This is called a nested if-else statement. It is useful when a second decision depends on the result of a first decision, but avoid too many nesting levels because they reduce readability.
Summary of Python if-else statement usage
In this Python Tutorial, we have learnt if-else conditional statement, and how any statement in if or else block could be another if or if-else conditional statements.
Use a Python if-else statement when your program must choose between two branches. Use elif for more than two related choices, logical operators for multiple conditions, and nested if-else statements when one decision depends on another decision.
TutorialKart.com