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
if written on one line:if statement that prints a message if a is greater than b.
Output: complete Python program
a = 5
b = 2
if a > b: print("a is greater than b")
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
if/else:if/else using a conditional expression to print "A" or "B" based on a comparison.
Output: complete Python program
a = 2
b = 330
print("A") if a > b else print("B")
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
Output: complete Python program
a = 10
b = 20
bigger = a if a > b else b
print("Bigger is", bigger)
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
a is greater, equal, or less than b.
Output: complete Python program
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
Practical Examples
Ternary operators fit especially well in simple assignments and return statements.
Example
Output: complete Python program
x = 15
y = 20
max_value = x if x > y else y
print("Maximum value:", max_value)
Example
Output: complete Python program
username = ""
display_name = username if username else "Guest"
print("Welcome,", display_name)
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.