Short-hand If

  • Short-hand If in Python allows you to write conditional statements in a single line of code. It makes your program shorter, cleaner, and easier to read when working with simple conditions.

  • What is a Short-hand if Statement?

    The short-hand if statement is a one-line version of the normal if statement in Python.

    It is used when:

    • The if condition has only one statement

    • The code is simple and short

    • We want to improve readability

    👉 It is also called Single-Line if Statement.

    Why Use Short-hand if?

    Short-hand if is used to:

    • Write clean and compact code

    • Reduce the number of lines

    • Improve readability for simple conditions

    • Avoid unnecessary blocks

    Note:
    Short-hand if should be used only for simple logic, not complex conditions.

    Syntax of Short-hand if

    General Syntax

    if condition: statement

    Syntax Explanation

    Part

    Description

    if

    Keyword for condition checking

    condition

    Expression returning True or False

    :

    Starts the statement

    statement

    Single statement executed if condition is True

    ⚠️ Only one statement is allowed

Checking Greater Number Using Short-hand if

This program checks whether one number is greater than another using a short-hand if statement.

a = 10
b = 5

if a > b: print("a is greater than b")

Voting Eligibility Using Short-hand if

This program prints a message if the user is eligible to vote using a one-line if.

age = 19

if age >= 18: print("Eligible to vote")
  • Limitations of Short-hand if

    ❌ Cannot contain multiple statements
    ❌ Not suitable for complex logic
    ❌ No else block (use ternary for that)