Short Hand If Else

  • The Short Hand If Else statement in Python allows you to write simple conditional logic in a single line. It improves code readability and is mainly used when conditions and actions are short and clear.

  • What is Short-hand if-else?

    The short-hand if-else, also called the Ternary Operator, is a one-line conditional expression in Python.

    It allows a program to choose between two values or actions in a single line.

    👉 It is mainly used for simple if-else decisions.

    Why is it Called a Ternary Operator?

    It is called ternary because it uses three parts:

    1. Condition

    2. Value if condition is True

    3. Value if condition is False

    Syntax of Short-hand if-else

    General Syntax

    value_if_true if condition else value_if_false


    Syntax Explanation

    Part

    Description

    condition

    Expression that returns True or False

    value_if_true

    Executed when condition is True

    else

    Separates True and False expressions

    value_if_false

    Executed when condition is False



    Important:

    • Only one expression is allowed on each side

    • Best for simple logic only

Finding Greater Number Using Ternary Operator

This program checks which number is greater using the short-hand if-else expression.

a = 10
b = 20

result = "a is greater" if a > b else "b is greater"
print(result)

Voting Eligibility Using Ternary Operator

This program checks whether a person is eligible to vote using a one-line conditional expression.

age = 17

status = "Eligible to vote" if age >= 18 else "Not eligible to vote"
print(status)

Pass or Fail Using Ternary Operator

This program checks whether a student has passed or failed based on marks.

marks = 42

result = "Pass" if marks >= 35 else "Fail"
print(result)
  • Limitations of Ternary Operator

    ❌ Not suitable for complex logic
    ❌ Reduces readability if overused
    ❌ Cannot contain multiple statements