← Back to Python Course | Chapter 2: Input, Output & Operators | Lesson 12 of 16

Python Ternary Operator

Ternary operator दो जवाबों में से एक चुनने का एक-लाइन तरीका है, जैसे 'अगर बारिश हो रही है तो छाता ले लो, वरना धूप का चश्मा पहन लो'। यह आपको एक लंबा if-else लिखने से बचाता है।
Syntax
python
result = value_if_true if condition else value_if_false

Conditional Expressions

Python के ternary operator को औपचारिक रूप से conditional expression कहते हैं, जो value_if_true if condition else value_if_false के रूप में लिखा जाता है — यह आपको छोटे if/else को एक line में समेटने देता है जहाँ statement नहीं बल्कि expression अपेक्षित है।

उदाहरण: Conditional Expressions

python
age = 20
status = "adult" if age >= 18 else "minor"  # conditional expression on one line
print(status)

सम या विषम जाँचना

इसका क्लासिक उपयोग सम या विषम को inline जाँचना है: "even" if n % 2 == 0 else "odd" शर्त को एक बार evaluate करता है और तुरंत जो भी string लागू हो वह बना देता है, बहु-line if block के बिना।

उदाहरण: Checking Even or Odd

python
n = 7
print("even" if n % 2 == 0 else "odd")

Nested Ternary Expressions

एक conditional expression को दूसरे के भीतर रखने से आप तीन या अधिक नतीजों में से चुन सकते हैं, लेकिन एक स्तर से ज़्यादा nesting पर पठनीयता तेज़ी से गिरती है — अगर दो से ज़्यादा branches चाहिए, तो सामान्य if/elif/else block आमतौर पर ज़्यादा साफ़ है।

उदाहरण: Nested Ternary Expressions

python
score = 75
grade = "A" if score >= 90 else "B" if score >= 70 else "C"  # nested ternary, evaluated left to right
print(grade)

Functions में Inline Ternary

क्योंकि conditional expression बस एक expression है, यह return statement में सहजता से बैठ जाता है — return "pass" if score >= 60 else "fail" — जिससे function बहु-line branch की जगह एक line में अपना return value चुन लेता है।

उदाहरण: Inline Ternary in Functions

python
def result(score):
    return "pass" if score >= 60 else "fail"  # ternary directly in the return statement

print(result(72))

Lists के साथ Ternary

वही पैटर्न दो containers में से चुनने के लिए भी काम करता है, जैसे items = cached_items if use_cache else fresh_items, जिससे आप एक अकेली शर्त के आधार पर बदल सकते हैं कि variable किस list या default की ओर इशारा करे।

उदाहरण: Ternary with Lists

python
use_cache = False
cached_items = ["old"]
fresh_items = ["new"]
items = cached_items if use_cache else fresh_items  # picks which list to use
print(items)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.