---
title: "Does Python have a ternary conditional operator?"  
description: "Does Python have a ternary conditional operator?"  
author: "Anonymous User"  
published: 2015-05-11  
updated: 2015-05-11  
canonical: https://www.mindstick.com/forum/23210/does-python-have-a-ternary-conditional-operator  
category: "python"  
tags: ["python"]  
reading_time: 2 minutes  

---

# Does Python have a ternary conditional operator?

If not, is it possible to simulate one concisely using other [language](https://www.mindstick.com/startup/28/preply-the-fast-growing-platform-transforming-language-learning) constructs?\

## Replies

### Reply by Anonymous User

Yes, it was added in version 2.5. The syntax is:

```
a if test else b
```

First test is evaluated, then either a or b is returned based on the Boolean value of test;if test evaluates to True a is returned, else b is returned.\
For example:

```
>>> 'true' if True else 'false''true'>>> 'true' if False else 'false''false'
```

Keep in mind that it's frowned upon by some Pythonistas for:\
The order of the arguments is different from many other languages (such as C, Ruby, Java, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour (they may reverse the order).Some find it "unwieldy", since it goes against the flow of thought; you think of the condition first and then the effects.Stylistic reasons.If you're having trouble remembering the order (as many seem to do), then remember that if you read it out loud, you (almost) say what you mean x = 4 if b > 8 else 9 is read out loud as x will be 4 if b is greater than 8 otherwise 9.\

Official documentation:

- Conditional expressions
- Is there an equivalent of C’s ”?:” ternary operator?


---

Original Source: https://www.mindstick.com/forum/23210/does-python-have-a-ternary-conditional-operator

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
