How to Use If Else in One Line in Python: Simple Syntax & Examples
In Python, you can write an
if else statement in one line using the ternary conditional operator: value_if_true if condition else value_if_false. This lets you choose between two values based on a condition in a single, concise expression.Syntax
The one-line if else in Python uses this pattern:
value_if_true: the result if the condition is truecondition: the test that returns True or Falsevalue_if_false: the result if the condition is false
This expression returns value_if_true when condition is true, otherwise it returns value_if_false.
python
result = value_if_true if condition else value_if_false
Example
This example shows how to assign a message based on a number's value using one-line if else:
python
number = 10 message = "Even" if number % 2 == 0 else "Odd" print(message)
Output
Even
Common Pitfalls
Common mistakes include:
- Forgetting the
elsepart, which causes a syntax error. - Using multiple statements instead of expressions, which is not allowed in one line.
- Confusing the order: the
ifcomes after the true value, not before.
Here is a wrong and right example:
python
# Wrong (syntax error): # result = if condition: value_if_true else: value_if_false # Right: condition = True result = "Yes" if condition else "No" print(result)
Output
Yes
Quick Reference
| Part | Description | Example |
|---|---|---|
| value_if_true | Result if condition is true | "Even" |
| condition | Test that returns True or False | number % 2 == 0 |
| value_if_false | Result if condition is false | "Odd" |
Key Takeaways
Use the syntax: value_if_true if condition else value_if_false for one-line if else.
Always include the else part to avoid syntax errors.
The condition goes between the true and false values.
One-line if else is an expression, not a statement, so it returns a value.
Use it for simple conditional assignments or expressions to keep code concise.