Back to Python Notes
Topic #199

If Else in Python

By the end of this lesson, you will be able to control program flow using Python's conditional statements: if, elif, else, nested structures, and ternary expressions.

What it is

Conditional logic allows a program to make decisions. Instead of executing every line sequentially, Python evaluates a boolean expression (True or False). If the condition is True, the indented block of code runs; otherwise, it skips to the next condition or block. The core keywords are if for the initial check, elif (short for "else if") for subsequent checks, and else for the default case when no conditions are met. Related terms include "boolean expressions," "indentation blocks," and "control flow."

Why it matters

  • Dynamic Behavior: Programs can react differently based on user input, data values, or system states.
  • Error Handling: You can prevent crashes by checking if a value exists or is valid before processing it.
  • Efficiency: Skipping unnecessary code execution saves time and resources in complex applications.
  • Readability: Proper use of elif chains makes logic easier to follow than multiple independent if statements.

Syntax or steps

Python relies on indentation (whitespace) rather than braces to define code blocks. The basic structure is: 1. Start with if condition:. 2. Indent the code that runs if true. 3. Optionally add elif another_condition: followed by indented code. 4. Optionally add else: followed by indented code for all other cases. For simple assignments, use the ternary operator: value = true_value if condition else false_value.

Example

def check_access(age, has_ticket):
    # Standard if-elif-else chain
    if age < 18:
        status = "Minor"
    elif not has_ticket:
        status = "No Ticket"
    else:
        status = "Granted"
    
    # Ternary expression for concise assignment
    message = f"Access {status}" if status == "Granted" else "Access Denied"
    
    return message

# Test cases
print(check_access(25, True))   # Output: Access Granted
print(check_access(17, True))   # Output: Access Denied
print(check_access(20, False))  # Output: Access Denied
Explanation: The function first checks if the user is under 18. If not, it checks if they lack a ticket. If both fail, access is granted. The variable message uses a ternary expression to assign a string based on whether status equals "Granted". This demonstrates how to combine multi-line logic with single-line conditional assignments.

Common mistakes

  • Missing Colons: Forgetting the colon (:) at the end of if, elif, or else lines causes a SyntaxError.
  • Inconsistent Indentation: Mixing tabs and spaces or failing to indent the block under the condition leads to IndentationError.
  • Using Assignment (=) instead of Comparison (==): Writing if x = 5: is invalid syntax in Python (unless using walrus operators in specific contexts), whereas if x == 5: is correct.
  • Unreachable Code: Placing a broad condition like if True: or else: before more specific elif blocks prevents the specific logic from ever running.

When to use it

Use standard if/elif/else blocks when you need to execute multiple lines of code or perform side effects (like printing or modifying lists). Use ternary expressions only for simple value assignments where readability remains high.
FeatureIf/Elif/Else BlockTernary Expression
ComplexityHigh (multi-line)Low (single line)
Side EffectsSupportedNot recommended
ReadabilityClear for complex logicClear for simple choices

Practice

Guided Exercise: Write a script that takes a number as input. Print "Positive" if greater than 0, "Negative" if less than 0, and "Zero" if equal to 0. Use an if-elif-else structure. Challenge: Refactor your solution to use a ternary expression to assign the result to a variable named label, then print label. Hint: You may need nested ternaries or stick to the block structure for three-way branching clarity.

Quick check

Question: What happens if you omit the else block in an if-elif chain and none of the conditions evaluate to True? Answer: The program simply continues execution after the entire conditional block without running any of the internal code. No error occurs unless variables defined inside the block are accessed later.

Summary

Conditional logic is fundamental to programming, allowing Python to branch execution based on dynamic data. Mastering the distinction between multi-line if/elif/else blocks for complex actions and ternary expressions for simple assignments ensures your code is both functional and readable. Always pay attention to indentation and colons to avoid common syntax errors.

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

If Else in Python – FAQs

Quick answers about learning If Else in Python in Python.

This free note from Coding Now Tech Institute explains If Else in Python in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including If Else in Python, is 100% free with no signup required.
With focused practice, most students grasp If Else in Python in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now