Python Conditional Statements: IF…Else, ELIF & Switch Case

โšก Smart Summary

Python Conditional Statements direct program flow by executing specific code blocks only when Boolean expressions evaluate to true. They include if, else, elif, nested if, the ternary operator, and structural pattern matching for clean, decision-driven logic.

  • Core Concept: An if statement runs its indented block only when the condition evaluates to true, forming the foundation of decision-making in Python.
  • Handle Alternatives: Add else for a fallback path and elif to test additional conditions in sequence without deep nesting.
  • Avoid Logic Errors: Use a single if-elif-else chain rather than independent if statements when exactly one outcome should apply.
  • Write Concise Code: Apply the ternary expression value_if_true if condition else value_if_false to assign a value in one readable line.
  • Modern Branching: Replace long elif chains with dictionary mapping or the match-case statement introduced in Python 3.10 for cleaner multiway selection.

Python Conditional Statements

What are Conditional Statements in Python?

Conditional Statements in Python perform different computations or actions depending on whether a specific Boolean constraint evaluates to true or false. They let a program make decisions and follow different paths instead of running every line in sequence. In Python, conditional statements are handled by the if statement and its companions: else, elif, and nested if.

What is Python If Statement?

The Python if statement is used for decision-making operations. It contains a body of code that runs only when the condition given in the if statement is true. If the condition is false, the optional else statement runs instead, holding the code for the else condition. When you want to act on one condition while another is not true, you use the Python if-else statement.

Python if Statement Syntax:

if expression:
    statement
else:
    statement

Python ifโ€ฆelse Flowchart

Python ifโ€ฆelse flowchart showing the true and false branches

The flowchart above shows how control flows through an if-else statement. Let us see an example of the Python if-else statement in action:

Python if statement example output in the editor

# Example file for working with conditional statements
def main():
    x, y = 2, 8
    if(x < y):
        st = "x is less than y"
    print(st)

if __name__ == "__main__":
    main()
  • Code Line 3: We define two variables x, y = 2, 8.
  • Code Line 4: The if statement checks the condition x < y, which is True in this case.
  • Code Line 5: The variable st is set to “x is less than y.”
  • Code Line 6: The line print(st) outputs the value of st, which is “x is less than y.”

What Happens When the “if” Condition Is Not Met

Building on the previous example, let us see what happens when the if condition in Python is not met. When the condition is false and no else branch exists, the indented code is skipped entirely.

Python error when the if condition is not met

# Example file for working with conditional statements
def main():
    x, y = 8, 4
    if(x < y):
        st = "x is less than y"
    print(st)

if __name__ == "__main__":
    main()
  • Code Line 3: We define two variables x, y = 8, 4.
  • Code Line 4: The if statement checks the condition x < y, which is False in this case.
  • Code Line 5: The variable st is NOT set to “x is less than y.”
  • Code Line 6: The line print(st) tries to print a variable that was never declared, so Python raises a NameError.
โš  Warning: Referencing a variable that is only assigned inside an if block is a common beginner mistake. Either provide an else branch or give the variable a default value before the if statement.

How to Use the “else” Condition

To avoid the error above, you can add an else condition. The else condition is used when you have to judge one statement on the basis of another. If one condition is false, the else block provides an alternative path so the program still produces a result.

Example:

Python if-else condition example

# Example file for working with conditional statements
def main():
    x, y = 8, 4
    if(x < y):
        st = "x is less than y"
    else:
        st = "x is greater than y"
    print(st)

if __name__ == "__main__":
    main()
  • Code Line 3: We define two variables x, y = 8, 4.
  • Code Line 4: The if statement checks the condition x < y, which is False in this case.
  • Code Line 6: The flow of program control goes to the else condition.
  • Code Line 7: The variable st is set to “x is greater than y.”
  • Code Line 8: The line print(st) outputs the value of st, which is “x is greater than y.”

When the “else” Condition Does Not Work

The else condition will not always give you the desired result. It can print the wrong output when there is a flaw in the program logic. This usually happens when you have to justify more than two statements or conditions in a program. An example will help you understand this concept.

Here both variables are the same (8, 8), yet the program output is “x is greater than y,” which is WRONG. This happens because the program checks the first condition (the if condition), and when it fails, it prints the second condition (the else condition) as the default. In the next step, we will see how to correct this error.

Python else condition producing a wrong result

# Example file for working with conditional statements
def main():
    x, y = 8, 8
    if(x < y):
        st = "x is less than y"
    else:
        st = "x is greater than y"
    print(st)

if __name__ == "__main__":
    main()

How to Use the “elif” Condition

To correct the previous error made by the else condition, we can use the elif statement. By using the elif condition, you tell the program to test a third possibility when the first condition is false. You can chain multiple elif conditions to check for fourth, fifth, and further possibilities in your code.

Example:

Python elif condition example

# Example file for working with conditional statements
def main():
    x, y = 8, 8
    if(x < y):
        st = "x is less than y"
    elif(x == y):
        st = "x is same as y"
    else:
        st = "x is greater than y"
    print(st)

if __name__ == "__main__":
    main()
  • Code Line 3: We define two variables x, y = 8, 8.
  • Code Line 4: The if statement checks the condition x < y, which is False in this case.
  • Code Line 6: The flow of program control goes to the elif condition. It checks whether x == y, which is true.
  • Code Line 7: The variable st is set to “x is same as y.”
  • Code Line 10: The program control exits the if statement (it will not reach the else statement) and prints st. The output is “x is same as y,” which is correct.

How to Execute a Conditional Statement With Minimal Code

Now that you can write full if-elif-else blocks, Python lets you condense a simple condition into a single line. Instead of writing separate code for each branch, you can use a ternary (conditional) expression.

Syntax:

value_if_true if condition else value_if_false

Example:

Python one-line ternary conditional statement example

def main():
    x, y = 10, 8
    st = "x is less than y" if (x < y) else "x is greater than or equal to y"
    print(st)

if __name__ == "__main__":
    main()
  • Code Line 2: We define two variables x, y = 10, 8.
  • Code Line 3: The variable st is set to “x is less than y” if x < y; otherwise it becomes “x is greater than or equal to y.” Because x > y here, st becomes the second value.
  • Code Line 4: Prints the value of st and gives the correct output.

Python Nested if Statement

A nested if statement places one if statement inside another, which is useful when a decision depends on a second condition. The following example demonstrates a nested if statement in Python that calculates shipping cost based on country and order total.

total = 100
# country = "US"
country = "AU"

if country == "US":
    if total <= 50:
        print("Shipping Cost is $50")
    elif total <= 100:
        print("Shipping Cost is $25")
    elif total <= 150:
        print("Shipping Cost is $5")
    else:
        print("FREE")

if country == "AU":
    if total <= 50:
        print("Shipping Cost is $100")
    else:
        print("FREE")

Uncomment Line 2 in the code above, comment out Line 3, and run the code again to see how the output changes for a different country.

Switch Case Statement in Python

What is a Switch Statement?

A switch statement is a multiway branch statement that compares the value of a variable against the values specified in case statements. For many years, the Python language did not have a switch statement, so developers implemented the same behavior with Python dictionary mapping.

Example using dictionary mapping:

def switch_example(argument):
    switcher = {
        0: "This is Case Zero",
        1: "This is Case One",
        2: "This is Case Two",
    }
    return switcher.get(argument, "nothing")

if __name__ == "__main__":
    argument = 1
    print(switch_example(argument))

Switch Case With match (Python 3.10 and Later)

Since Python 3.10 (released in October 2021), Python provides a native match-case statement, known as structural pattern matching. It offers a clean, readable alternative to long elif chains and the dictionary approach shown above.

def switch_example(argument):
    match argument:
        case 0:
            return "This is Case Zero"
        case 1:
            return "This is Case One"
        case 2:
            return "This is Case Two"
        case _:
            return "nothing"

if __name__ == "__main__":
    print(switch_example(1))

The underscore (_) acts as the default case, matching any value not handled by the earlier cases, just like the default in a traditional switch statement.

โœ… Tip: Use match-case if you are on Python 3.10 or newer. For older versions, dictionary mapping remains the standard way to emulate a switch statement.

if vs elif vs else: Quick Comparison

Use this comparison to decide which conditional structure fits your decision-making logic.

StatementPurposeWhen to Use
ifRuns a block when a condition is trueA single yes/no decision
ifโ€ฆelseProvides a fallback when the condition is falseTwo mutually exclusive outcomes
elifTests additional conditions in sequenceThree or more possibilities
Nested ifPlaces an if inside another ifA decision that depends on a second condition
TernaryCondenses if-else into one lineSimple value assignment
match-caseMatches a value against many patternsMultiway branching (Python 3.10+)
โš  Note: Python 2 reached end-of-life on January 1, 2020, and all examples in this article use Python 3 syntax. In Python 2, print was a statement (for example, print st) rather than a function, so the code above will not run unchanged on Python 2.

FAQs

An if statement starts a decision and is always evaluated. An elif (else-if) is checked only when the preceding if or elif conditions are false, letting you test several possibilities in one chain while exactly one block runs.

Yes. Since Python 3.10, the match-case statement provides native switch-style branching through structural pattern matching. On older versions, developers emulate a switch using dictionary mapping with the get() method to supply a default value.

Use a ternary expression: value_if_true if condition else value_if_false. For example, st = “low” if x < 10 else “high” assigns a value in a single readable line without a full if-else block.

Yes. AI coding assistants can generate, explain, and debug if-elif-else logic from a plain-language prompt. They are helpful for learning, but you should still review the output to confirm the conditions and indentation match your intended logic.

Yes. Conditional logic is fundamental to AI. Decision trees, rule-based systems, and data-preprocessing pipelines all rely on if-else branching to choose actions, filter data, and control how a model handles different inputs.

Summarize this post with: