if...else Statement in Python
What is an if...else Statement? In Python, the if...else statement is used for decision making — to execute certain code only when a condition is true, and optionally, another code when it is false.
The if…elif…else statement is used in Python when we want the code block should be executed when the specified condition met otherwise it should skip the code.
Syntax
if condition:
# Code to execute if the condition is True
else:
# Code to execute if the condition is False Key Points
- The condition must return either True or False.
- Indentation (usually 4 spaces) defines which code belongs to the if or else block.
- We can have only one else with an if.
Example: Check if the entered number is even or odd.
Python
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even number")
else:
print("Odd number") Explanation
- % operator gives the remainder.
- If remainder = 0 → number is even.
- Otherwise → number is odd.
Nested if...else We can also use one if statement inside another.
Example: Check if number is positive, negative, or zero.
Python
num = 0
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number") Output: Zero
if...elif...else (Multiple Conditions) When we have more than two possible outcomes, use elif.
Example: Grade evaluation.
Python
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: Fail") Output: Grade: B
Using if...else in One Line (Ternary Operator)
Example: Short form.
Python
age = 20 status = "Adult" if age >= 18 else "Minor" print(status)
Output: Adult
Explanation
- "Adult" executes if the condition is True.
- "Minor" executes otherwise.
Truthy and Falsy Values in Python When you use an expression inside an if statement, Python automatically evaluates it as either True or False. You don’t always have to write == True or == False.
Falsy Values The following values are considered False in a Boolean context (like if, while, etc.):
| Type | Falsy Example | Explanation |
|---|---|---|
| bool | False | Explicit Boolean False |
| NoneType | None | None is treated as False |
| int, float | 0, 0.0 | Zero means False |
| str | "" | Empty string is False |
| list, tuple, set, dict | [], (), {}, {} | Empty collections are False |
Everything else (non-zero numbers, non-empty strings/collections, etc.) is truthy.
Example:
Python
if 10:
print("Positive number is truthy")
if -10:
print("Negative number is truthy")
if "Hello":
print("Non-empty string is truthy")
if [1, 2, 3]:
print("Non-empty list is truthy") Output: Positive number is truthy
Negative number is truthy
Non-empty string is truthy
Non-empty list is truthy