- What the if-else statement is ā two-way decision making
- Syntax of if-else ā how to write conditional statements
- Flowchart of if-else ā visualizing the flow
- Simple examples ā comparing numbers
- Even or Odd ā classic example
- Multiple conditions ā combining with logical operators
- Common mistakes ā and how to avoid them
What is the if-else Statement?
The if-else statement takes decision making to the next level. While the if statement only executes code when a condition is true, the if-else statement provides two paths ā one for when the condition is true, and another for when it's false.
š” Key insight: Think of if-else as a fork in the road. You choose one path if the condition is true, and the other path if it's false. There's no going back ā every condition has a path.
The if-else statement adds an additional step in the decision-making process compared to the basic if statement. The starting of the if-else statement is similar to the basic if statement, but it includes an else block that handles the false condition.
Syntax of if-else Statement
# Syntax of if-else Statement
if condition:
# Execute this block if condition is true
# Statements for true condition
else:
# Execute this block if condition is false
# Statements for false condition
# Example
age = 16
if age >= 18:
print("You can vote!")
else:
print("You cannot vote yet!")
# Output: You cannot vote yet!
š Breaking it down: Python evaluates the condition. If it's True, the if block executes and the else block is skipped. If it's False, the if block is skipped and the else block executes. Either way, exactly one block runs.
ā ļø Important: The else block is optional but powerful. It ensures that every condition has a response, making your program more robust and user-friendly.
Flowchart of if-else Statement
Let's visualize how the if-else statement works using a flowchart:
Flowchart:
āāāāāāāāāāāāāāā
ā START ā
āāāāāāāā¬āāāāāāā
ā¼
āāāāāāāāāāāāāāā
ā Condition ā āāāā Test the condition
ā (True?) ā
āāāāāāāā¬āāāāāāā
ā
True ā False
ā¼ ā¼
āāāāāāāāāāāāāāā āāāāāāāāāāāāāāā
ā Execute ā ā Execute ā
ā Body of if ā ā Body of ā
ā (True) ā ā else (False)ā
āāāāāāāā¬āāāāāāā āāāāāāāā¬āāāāāāā
ā ā
āāāāāāāāāā¬āāāāāāāāā
ā¼
āāāāāāāāāāāāāāā
ā END ā
āāāāāāāāāāāāāāā
What happens:
1. The flow enters the if-else statement
2. The condition is tested
3. If True ā body of if executes
4. If False ā body of else executes
5. Program continues with the next statement after if-else
Simple Example
Let's compare two numbers using if-else:
# Find the smaller of two numbers using if-else
p = 8
q = 6
if p < q: # Test condition
print(p, "is smaller than", q)
else: # When condition is false
print(q, "is smaller than", p)
# Output:
# 6 is smaller than 8
š Explanation: In this example, we used a single if-else statement. The condition p < q evaluates to False (8 is not less than 6), so the if block is skipped and the else block executes, displaying 6 is smaller than 8. This is cleaner than using two separate if statements.
Even or Odd Example
Here's the classic example using if-else:
# Python script to find if a number is even or odd using if-else
x = int(input("Enter Any Number: "))
if x % 2 == 0:
print(x, "is Even")
else:
print(x, "is Odd")
# Output:
# Enter Any Number: 5
# 5 is Odd
š Explanation:
1. x = int(input("Enter Any Number: ")) ā accepts user input and converts it to an integer.
2. if x % 2 == 0: ā checks if the remainder when divided by 2 is 0. If true, the number is even.
3. else: ā if the condition is false, the number is odd.
4. Since 5 % 2 = 1, the condition is false, so the else block executes and displays 5 is Odd.
Multiple Conditions
You can combine multiple conditions using logical operators ā and, or, and not:
# Multiple conditions with if-else
age = 25
has_license = True
if age >= 18 and has_license:
print("You can drive!")
else:
print("You cannot drive!")
# Another example with or
is_weekend = True
is_holiday = False
if is_weekend or is_holiday:
print("You can relax!")
else:
print("It's a workday!")
# Output:
# You can drive!
# You can relax!
Common Mistakes to Avoid
ā Mistake 1: Using = instead of ==
# WRONG (assignment instead of comparison)
if x = 5: # This will cause a SyntaxError!
print("x is 5")
else:
print("x is not 5")
# CORRECT (comparison)
if x == 5:
print("x is 5")
else:
print("x is not 5")
ā Mistake 2: Missing Colon
# WRONG
if x > 0 # Missing colon!
print("Positive")
else
print("Negative")
# CORRECT
if x > 0:
print("Positive")
else:
print("Negative")
ā Mistake 3: Incorrect Indentation
# WRONG (inconsistent indentation)
if x > 0:
print("Positive") # IndentationError!
else:
print("Negative")
# CORRECT (consistent indentation)
if x > 0:
print("Positive")
else:
print("Negative")
Try It Yourself!
Experiment with the if-else statement directly in your browser. Modify the code and see the results in real time.
IF-ELSE STATEMENT
========================================
1. COMPARE TWO NUMBERS
6 is smaller than 8
2. EVEN OR ODD
7 is Odd
3. VOTING ELIGIBILITY
You cannot vote yet!
4. MULTIPLE CONDITIONS
You can drive!
ā Explore different if-else conditions!
š You've Mastered Python if-else Statement!
You understand the if-else statement, syntax, flow, and how to handle two-way decision making. This is essential for building robust programs!
Quick Quiz ā Test Your Knowledge
Let's see what you've learned about the if-else statement:
else block do in an if-else statement?if-else statement?if x > 0: print("Positive") else: print("Negative"), what prints if x = -5?if 5 > 3: print("A") else: print("B")?else block mandatory in an if-else statement?Frequently Asked Questions
š¤ What is the difference between if and if-else?
if only executes code when the condition is true. if-else provides two paths ā one for true and one for false. if-else ensures every condition has a response.
š§ Can I have multiple statements in if and else blocks?
if and else blocks can contain multiple statements. Just make sure they're all indented at the same level.
š Can I nest if-else statements?
if-else inside another if or else block. This is called nesting. However, deep nesting can make code hard to read.
š Can I use logical operators in if-else conditions?
and, or, and not. For example: if age >= 18 and has_license:.
ā” What happens if I forget the else block?
else block, it becomes a simple if statement. Nothing executes when the condition is false. This is valid syntax and sometimes intentional.
šÆ Which is better: two if statements or one if-else?
if-else when you have two mutually exclusive paths. Use two if statements when the conditions are independent and both could be true.
š Where to Go From Here
Now that you've mastered the if-else statement, here are the next topics to explore:
š The if-elif-else Ladder
Handle multiple conditions with the if-elif-else ladder.
š Nested if Statements
Master complex decision making with nested if statements.
š Shorthand if-else
Learn the ternary operator for concise conditional expressions.
Learn More ā