Yes, python has a ternary conditional operator though it’s not the typical ? : format like in C or JavaScript. Instead python uses a more readable “x if condition else y” structure.
It allows you to assign a value based on a condition in a single line, perfect for simple logic without writing full if-else blocks.
Basic Syntax
A simple one-line format used for quick conditional assignments.
python
If the condition is true then the value will be “Yes”; otherwise it will be “No”.
Example 1: Assign Based on Condition
Demonstrates how to assign a value based on whether a condition is true or false using the ternary syntax.
python
x = 10result = “Even” if x % 2 == 0 else “Odd”
print(result) # Output: Even
This replaces a full if-else block when you just need one-line decisions.
Also Read: How Much Does It Cost To Build A Web App With Python in 2025?
Example 2: Inline Return in Functions
Shows how to streamline your function logic by returning values conditionally in a single line.
python
def check(num): return “Positive” if num > 0 else “Non-positive”
print(check(5)) # Output: Positive
print(check(-3)) # Output: Non-positive
Great for clean and one-line return statements in functions.
Tip
- Only use ternary expressions for simple decisions.
- For more complex logic prefer regular if-else blocks for clarity.