Python Decision Making
Estimated reading: 3 minutes 33 views

🔁 Python if...else Statement – Binary Control Flow Explained

🧲 Introduction – Why if...else Matters

Real-world programs often need to make binary decisions—if something is true, do one thing; otherwise, do another. Python’s if...else structure helps you implement this logic efficiently.

For example:

  • ✅ If a user is logged in, show the dashboard.
  • ❌ Else, redirect to the login page.

Let’s explore how to write and use if...else statements in Python with real-world clarity.


🔑 Syntax of if...else

if condition:
    # code block if condition is True
else:
    # code block if condition is False
  • The if evaluates a condition.
  • If it’s True, the indented block under if runs.
  • Otherwise, the else block runs.

💡 Note: Use proper indentation—Python relies on it!


🧪 Example: Even or Odd Number Checker

num = int(input("Enter a number: "))

if num % 2 == 0:
    print("The number is even.")
else:
    print("The number is odd.")

Output (if num = 7)

The number is odd.

Explanation:

  • The condition num % 2 == 0 checks for evenness.
  • If True, it prints “even”, otherwise “odd”.

🧮 Example: Simple Login Check

username = input("Enter username: ")

if username == "admin":
    print("Welcome, admin!")
else:
    print("Access denied.")

Output:

Access denied.

📘 Best Practice: Use == for comparison, not = (which is assignment).


🧱 Nested if...else Example

age = int(input("Enter your age: "))

if age >= 18:
    if age >= 65:
        print("You are a senior citizen.")
    else:
        print("You are an adult.")
else:
    print("You are a minor.")

Output (if age = 70):

You are a senior citizen.

💡 Tip: Avoid excessive nesting for readability. Use elif if appropriate.


⚠️ Common Errors and Fixes

❌ Error⚠️ Reason✅ Fix
if x = 5:Uses = instead of ==if x == 5:
Missing colonSyntaxErrorAdd : after condition
Incorrect indentationIndentationErrorIndent blocks consistently
Unreachable else blockCondition is always True or FalseRe-check logic

📊 Comparison Table: if vs if...else

Featureif Onlyif...else
Condition TrueExecutes code blockExecutes if block
Condition FalseSkips the block (does nothing)Executes else block
Binary LogicNoYes
Suitable ForOptional executionYes/No decisions

📌 Summary – Python if...else Statement

  • Purpose: To control the flow of a program by executing one block of code when a condition is True, and another when it’s False.
  • 🔠 Syntax:
if condition:
    # run if true
else:
    # run if false

🔍 Key Takeaways

  • if...else enables binary decisions in your Python program.
  • The else block runs only if the if condition fails.
  • Python depends on indentation—not braces {}—to define blocks.
  • Use with logical operators like and, or, not for compound conditions.

⚙️ Real-World Relevance

  • Used in authentication, form validations, workflow branching, and more.
  • Foundation for more advanced decision-making tools like elif and match-case.

❓ FAQ – Python if...else Statement

❓ What is the purpose of else in Python?

else provides an alternate code path when the if condition evaluates to False.

❓ Can I use else without if?

No. else must always follow an if (or elif) statement.

❓ Can I put if...else on one line?

Yes, but it should only be used for simple expressions:

print("Even") if num % 2 == 0 else print("Odd")

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Python If…Else

Or Copy Link

CONTENTS
Scroll to Top