Python Ternary Operator
In this page:
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
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
n = 7
print("even" if n % 2 == 0 else "odd")
Nested Ternary Expressions
एक conditional expression को दूसरे के भीतर रखने से आप तीन या अधिक नतीजों में से चुन सकते हैं, लेकिन एक स्तर से ज़्यादा nesting पर पठनीयता तेज़ी से गिरती है — अगर दो से ज़्यादा branches चाहिए, तो सामान्य if/elif/else block आमतौर पर ज़्यादा साफ़ है।
उदाहरण: Nested Ternary Expressions
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
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
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)
Chapter Quiz — Complete all 16 topics to unlock
0/16 topics done
Complete these topics first:
- Python print()
- Python input()
- Python Format Strings
- Python f-strings
- Python String Formatting
- Python Arithmetic Operators
- Python Relational Operators
- Python Logical Operators
- Python Bitwise Operators
- Python Assignment Operators
- Python Increment & Decrement
- Python Ternary Operator
- Python Operator Precedence
- Python Identity Operators
- Python Membership Operators
- Python Operators