Skip to main content

Short Hand If

When the if has just one statement to run, that statement can sit on the same line.

Note: The condition must still end with a colon :.

Example

An if written on one line:
Prompt
Write a Python one-line if statement that prints a message if a is greater than b.
Output: complete Python program

Short Hand If ... Else

The same idea works with one statement for if and one for else, which can share a single line.

Python calls this form a conditional expression, and you may also hear it called a "ternary operator".

Example

Printing one of two values with a one-line if/else:
Prompt
Write a Python one-line if/else using a conditional expression to print "A" or "B" based on a comparison.
Output: complete Python program

Assign a Value With If ... Else

A one-line if/else can also pick a value for you to store in a variable.

The general pattern looks like this:

Example

Prompt
Write a Python program that uses a ternary expression to assign the bigger of two values to a variable and print it.
Output: complete Python program
main.py
variable = value_if_true if condition else value_if_false

Multiple Conditions on One Line

Conditional expressions can be chained together. Just stop before the line becomes hard to read:

Example

Three possible results from one line:
Prompt
Write a Python one-liner with chained conditional expressions that prints "A", "=", or "B" depending on whether a is greater, equal, or less than b.
Output: complete Python program

Practical Examples

Ternary operators fit especially well in simple assignments and return statements.

Example

Picking the larger of two numbers:
Prompt
Write a Python program that uses a ternary operator to find and print the maximum of two numbers.
Output: complete Python program

Example

Falling back to a default value:
Prompt
Write a Python program that uses a ternary operator to set a default display name when the username is empty.
Output: complete Python program

When to Use Shorthand If

A shorthand if or ternary operator is a good choice when:

  • Both the condition and the actions are simple
  • The code becomes easier to read
  • A variable needs a quick value that depends on a condition

Important: Shorter code is not always better, so don't lean on this form for complicated conditions. When the logic is complex or spans several lines, a regular if-else statement stays easier to read.