Shorthand If

2 min read ·

Python provides a shorter way to write an if statement when there is only one statement to execute.
This is also called:
  • One-line if
  • Single-line if
It makes the code compact and readable when used correctly.

Syntax of Shorthand if

  • Condition is written first
  • Statement is written on the same line
  • Colon : is still required
  • Only one statement is allowed
Note

Shorthand if should be used only for simple logic.


Basic Shorthand if Example

  • Condition is checked
  • If True, the print statement runs
  • If False, nothing happens

Shorthand if with Mathematical Condition


Shorthand if with String Condition


Shorthand if with Boolean Value


Shorthand if with User Input


Shorthand if vs Normal if

Normal if

Shorthand if


Multiple Statements in Shorthand if (Not Recommended)

Caution

Multiple statements reduce readability and should be avoided.


Shorthand if with Logical Operator


Invalid Use of Shorthand if

Using Indentation ❌

Writing Block Code ❌

Stop

Shorthand if must be written in one single line.


Real World Example

Real World Scenario

Display message only when stock is available


Exercise

Practice Task
  1. Check if a number is positive using shorthand if
  2. Print a message if user is logged in
  3. Use shorthand if to check marks >= 75