Python Shorthand if Statements
Shorthand if Statements
When a condition and its action are very simple, writing a full multi-line if block can feel heavy. Python offers two compact forms:
- A one-line
ifstatement, for running a single statement when a condition is true - A conditional expression (often called the ternary operator), for choosing between two values in a single line
Used well, these forms make simple logic shorter and easier to read. Used carelessly, they make code harder to understand — this lesson covers both sides.
One-Line if Statement
When there is only one statement to execute, you can place it on the same line as the condition.
Example: Simple Comparison
x = 12
y = 7
if x > y: print("x is larger than y")
Expected output:
x is larger than y
This is exactly equivalent to:
if x > y:
print("x is larger than y")
Note: The colon (
:) after the condition is still required, even in shorthand form.
Style note: PEP 8, Python's style guide, discourages putting the body on the same line as
ifin most code. The two-line form is easier to read and to extend. Use the one-line form sparingly, for very short statements.
Conditional Expressions (Shorthand if ... else)
A conditional expression evaluates to one of two values depending on a condition.
Syntax
value_if_true if condition else value_if_false
Read it from left to right like an English sentence: "use value_if_true if the condition holds, else use value_if_false."
How It Is Evaluated
- Python evaluates the condition first (even though it is written in the middle).
- If the condition is
True, the result isvalue_if_true. - If the condition is
False, the result isvalue_if_false. - Only the selected value is evaluated; the other is skipped.
Because it is called the ternary operator in many languages (it has three parts), you will often hear that name used for Python's conditional expression as well.
Assigning Values With a Conditional Expression
The most common and recommended use of a conditional expression is to assign one of two values to a variable.
Example: Choosing the Smaller Number
num1 = 18
num2 = 25
smaller = num1 if num1 < num2 else num2
print("Smaller number:", smaller)
Expected output:
Smaller number: 18
Step by step:
- The condition
num1 < num2is18 < 25, which isTrue. - The expression therefore produces
num1, which is18. 18is stored insmaller.
The equivalent full form takes four lines:
if num1 < num2:
smaller = num1
else:
smaller = num2
General Syntax for Assignment
variable = value_if_true if condition else value_if_false
Example: Pass or Fail
marks = 45
passing_score = 50
result = "Pass" if marks >= passing_score else "Fail"
print(result)
Expected output:
Fail
Using a Conditional Expression Inside Other Code
Because a conditional expression produces a value, you can use it anywhere a value is allowed — such as inside print() or an f-string:
items = 1
print(f"You have {items} {'item' if items == 1 else 'items'} in your cart")
Expected output:
You have 1 item in your cart
Calling Functions With a Conditional Expression
You may also see conditional expressions used to choose between two actions:
marks = 45
passing_score = 50
print("Pass") if marks >= passing_score else print("Fail")
Expected output:
Fail
This works, because each side is a function call. However, it is better to choose the value and call print() once:
print("Pass" if marks >= passing_score else "Fail")
This version is shorter, clearer, and avoids repeating print().
Multiple Conditions on One Line
Conditional expressions can be chained to handle more than two outcomes.
Example: Comparing Two Values
p = 50
q = 75
print("p > q" if p > q else "p = q" if p == q else "p < q")
Expected output:
p < q
How Python reads it:
"p > q" if p > q else ("p = q" if p == q else "p < q")
p > qisFalse, so Python moves to theelsepart.- The
elsepart is another conditional expression:p == qisFalse. - The final value is
"p < q".
Tip: Avoid chaining more than two conditions. Readability should always come first. For three or more outcomes, a regular
if–elif–elseblock is clearer:if p > q: print("p > q") elif p == q: print("p = q") else: print("p < q")
Practical Use Cases
Example 1: Finding the Minimum Value
a = 9
b = 4
min_value = a if a < b else b
print("Minimum value:", min_value)
Expected output:
Minimum value: 4
For this specific task, Python's built-in
min(a, b)is even simpler. The example shows how the pattern works.
Example 2: Setting a Default Value
email = None
user_email = email if email else "not_provided@example.com"
print("Email:", user_email)
Expected output:
Email: not_provided@example.com
email is None, which is falsy, so the default address is used. An empty string "" would also trigger the default.
A shorter idiom for this specific pattern uses or:
user_email = email or "not_provided@example.com"
or returns the first truthy value, so it produces the same result here.
Example 3: Labeling a Status
stock = 0
status = "In stock" if stock > 0 else "Out of stock"
print(status)
Expected output:
Out of stock
When to Use Shorthand if
Use shorthand forms when:
- The logic is simple.
- Only one action or one value choice is required.
- The one-line version is easier to read than the multi-line version.
- You are assigning one of two values to a variable.
Avoid shorthand forms when:
- There are more than two or three outcomes.
- Either branch needs more than one statement.
- The line becomes long or hard to scan.
Common Mistakes
| Mistake | Example | Problem |
|---|---|---|
Omitting else in a conditional expression | x = 5 if flag | SyntaxError; a conditional expression must include else |
| Using a statement inside a conditional expression | x = 1 if flag else y = 2 | SyntaxError; both sides must be values |
| Writing the condition first, as in other languages | flag ? 1 : 2 | SyntaxError; Python uses 1 if flag else 2 |
| Long chained expressions | Several nested if ... else on one line | Hard to read and maintain |
Related Concepts
- Python if Statement — standard multi-line conditions
- Python else Statement — two-way decisions
- Python Booleans — truthy and falsy values used in conditions
- Python Operators —
and/orshort-circuit behavior