Built with Tutify.io

    AIStudyLabs

    Writing Conditional Logic with if, elif, else

    Writing Conditional Logic with if, elif, else

    Introduction

    In this lesson, you will learn how to make your Python programs actually decide things using if, elif, and else. You already know how to build Boolean expressions with comparison and logical operators; now you’ll use those expressions to control which code runs and when. We’ll build decision trees, combine multiple conditions, define fallback behavior, and avoid common pitfalls that often trip up beginners.


    1. Basic Conditional Logic with if

    An if statement lets you run a block of code only when a condition is true. You already know how to produce a Boolean expression; here we attach code to it.

    age = 20
    
    if age >= 18:
        print("You are allowed to enter.")
    print("Program finished.")
    
    # Output:
    You are allowed to enter.
    Program finished.
    

    Explanation:

    Key idea: Only the indented block belongs to the if. Everything at that indentation level or less is outside the conditional.


    2. Adding Alternative Paths with else

    else defines what should happen when the if condition is not true—your fallback behavior.

    password = "abc123"
    
    if len(password) >= 8:
        print("Password length is OK.")
    else:
        print("Password is too short; it must be at least 8 characters.")
    
    # Output:
    Password is too short; it must be at least 8 characters.
    

    Explanation:

    Use else when you want a default action if no earlier condition is satisfied.


    3. Handling Multiple Cases with elif

    When you have more than two possible outcomes, chaining conditions with elif (short for else if) is cleaner than nesting many if statements.

    score = 72
    
    tag = None
    
    if score >= 90:
        tag = "Excellent"
    elif score >= 75:
        tag = "Good"
    elif score >= 60:
        tag = "Pass"
    else:
        tag = "Fail"
    
    print(f"Score: {score}, Result: {tag}")
    
    # Output:
    Score: 72, Result: Pass
    

    How this flows:

    Guidelines:


    4. Combining Conditions for Richer Logic

    You can mix comparison and logical operators (and, or, not) to build more complex decision rules.

    Example: Ticket Pricing Logic

    age = 14
    is_student = True
    
    if age < 5:
        price = 0
    elif age <= 18 and is_student:
        price = 5
    elif age >= 65:
        price = 6
    else:
        price = 10
    
    print(f"Ticket price: ${price}")
    
    # Output:
    Ticket price: $5
    

    Explanation:

    Example: Validating User Login

    username = "alice"
    password = "secret123"
    
    if not username:
        print("Username is required.")
    elif not password:
        print("Password is required.")
    elif len(password) < 8 or " " in password:
        print("Password must be at least 8 characters and contain no spaces.")
    else:
        print("Credentials look valid (not checking against a real database here).")
    
    # Output:
    Credentials look valid (not checking against a real database here).
    

    Highlights:


    5. Avoiding Common Conditional Pitfalls

    5.1 Indentation Errors

    Misaligned indentation changes which lines are controlled by which condition.

    value = 10
    
    if value > 0:
        print("Positive number")
        print("Still inside the if block")
    print("Outside the if block")
    
    # Output:
    Positive number
    Still inside the if block
    Outside the if block
    

    If you accidentally over‑indent or under‑indent, you might:

    5.2 Misusing if Chains vs Independent if Statements

    Remember: in an if/elif/else chain, only one block runs. If you need multiple independent checks, use separate if statements.

    temperature = 30
    
    if temperature > 25:
        print("It's warm.")
    
    if temperature > 30:
        print("It's hot.")
    
    # Output:
    It's warm.
    

    Compare with a chain:

    temperature = 30
    
    if temperature > 25:
        print("It's warm.")
    elif temperature > 30:
        print("It's hot.")
    
    # Output:
    It's warm.
    

    The elif is never considered because the first if is True.

    5.3 Overly Nested Conditionals

    Deep nesting is hard to read and debug. Prefer guard clauses and restructuring.

    Instead of:

    user_age = 19
    has_id = True
    
    if user_age >= 18:
        if has_id:
            print("Access granted.")
        else:
            print("ID required.")
    else:
        print("Too young.")
    

    You can flatten it:

    user_age = 19
    has_id = True
    
    if user_age < 18:
        print("Too young.")
    elif not has_id:
        print("ID required.")
    else:
        print("Access granted.")
    
    # Output:
    Access granted.
    

    This structure is easier to scan: it reads like a clear decision tree.


    6. Practical Example: Simple Grading Helper

    Let’s put everything together in a slightly more complete example.

    score = 87
    attendance_rate = 0.92  # 92%
    
    if score < 0 or score > 100:
        message = "Score must be between 0 and 100."
    elif attendance_rate < 0.75:
        message = "Fail due to low attendance."
    elif score >= 90:
        message = "Grade: A"
    elif score >= 80:
        message = "Grade: B"
    elif score >= 70:
        message = "Grade: C"
    elif score >= 60:
        message = "Grade: D"
    else:
        message = "Grade: F"
    
    print(message)
    
    # Output:
    Grade: B
    

    What’s happening:

    This pattern—input validation, special rules, then main logic—is very common in real-world code.


    Summary / Key Takeaways

    In this lesson Writing Conditional Logic with if, elif, else, you have learned:

    Python Programming – Complete Course with Practical Examples — Operators, Expressions, and Control Flow

    Getting Started with Python and the Course

    Python Syntax, Indentation, and Core Concepts

    Variables, Data Types, and Type Conversion

    Operators, Expressions, and Control Flow

    Loops and Iteration Patterns

    Working with Strings in Depth

    Collections: Lists, Tuples, Sets, and Dictionaries

    Functions and Program Structuring

    Functional Programming Concepts in Python

    Modules, Packages, and Code Organization

    Error Handling and Debugging Fundamentals

    File Handling and Data Formats

    Object-Oriented Programming in Python

    Advanced Python: Iterators, Generators, and Decorators

    Python Standard Library for Real-World Tasks

    Python for Automation and Scripting

    Testing and Quality Assurance in Python

    Tutorial Not Found