What is an if-else
Statement?
An if-else statement allows us to handle both possibilities:
- If the condition is true, run the if block
- Else, run the else block
It is used when we want to choose between two paths.
Syntax:
if condition:
# block if true
else:
# block if false
Note: Indentation is important in Python!
Example 1: Even or Odd Number
num = 7
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
Output:
Odd number
Explanation:
Here, the number num
is 7.
The if
checks if num
divided by 2 gives remainder 0 (meaning even).
Since 7 is not divisible by 2, the condition is false.
So, the else
part runs and prints "Odd number".
Example 2: Check Pass or Fail
marks = 45
if marks >= 40:
print("Pass")
else:
print("Fail")
Output:
Pass
Explanation:
Here, marks are 45.
The if
checks if marks are 40 or more.
Since 45 is greater than 40, the condition is true.
So, it prints "Pass".
Flow of Execution:
- First, the condition is checked.
- If it is True, the if-block runs.
- If it is False, the else-block runs.
Where is it Used?
- When we need two-way decisions.
- To check login access (Correct β allow, Incorrect β deny).
- To determine discount eligibility (If amount > 500 β apply discount).
Summary
- if-else handles two possibilities: true and false.
- Syntax must follow indentation rules, which means using proper spaces or tabs at the start of lines to show which code belongs together.
- Used for decision making in real-life logic & programs.