Python If-Else Statements: Two-Way Decision Making & Ternary Expressions

While a standalone if statement provides a one-way branch, real-world programming frequently demands two-way decision making: do action A if a condition is met; otherwise, do action B. The if-else statement guarantees that exactly one of the two execution blocks will run.


1. Syntax and Flow of If-Else

if condition:
    # Executes when condition is True
    statement_block_1
else:
    # Executes when condition is False
    statement_block_2

Practical Example: Even or Odd Number Checker

number = 27

if number % 2 == 0:
    print(f"{number} is an EVEN number.")
else:
    print(f"{number} is an ODD number.")

2. Python Ternary Operator (One-Line Conditional Expression)

Python provides an elegant inline syntax to assign values based on a condition:

# Syntax: result = x if condition else y
marks = 68
status = "PASSED" if marks >= 40 else "FAILED"
print("Examination Status:", status)

# Finding maximum of two numbers:
a, b = 45, 78
max_val = a if a > b else b
print("Maximum:", max_val)

Frequently Asked Questions (FAQ)

Can an else block exist without an if block?

No. An else statement cannot stand alone; it must always be paired with a preceding if, for, while, or try block.
Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!