Published on

3. Ternary operator in Python

Authors

3. How does the ternary operator work in Python? Can you assign a value to a variable within a ternary operator?

Ternary Operator in Python

The ternary operator in Python is a way to condense an if-else statement into a single line. It’s often used to assign a value to a variable based on a condition.

Syntax:

value_if_true if condition else value_if_false

Example:

age = 18
status = "Adult" if age >= 18 else "Minor"
print(status)  # Output: Adult

Can You Assign a Value Inside a Ternary Operator?

Yes, you can assign a value to a variable using a ternary operator, as in the example above. However, you cannot assign a value within the expressions of the ternary operator itself.

✅ Valid (assignment using ternary):

x = 10
result = "Positive" if x > 0 else "Non-positive"

❌ Invalid (assignment inside condition/expression):

# This will raise a SyntaxError:
result = y = 5 if condition else 10  # ❌ invalid

If you need to assign multiple values or do more complex logic, use a regular if-else block instead.

Summary:

  • The ternary operator is: a if condition else b
  • You can assign the result of the ternary to a variable.
  • You cannot perform assignments inside the ternary expressions themselves.