Python में Operator Precedence
In this page:
result = a + b * c ** d # ** first, then *, then +
result = (a + b) * c # parentheses override
Arithmetic Precedence
Python वही क्रम-के-नियम अपनाती है जो गणित की कक्षा में पढ़ाए जाते हैं: गुणा और भाग जोड़ और घटाव से पहले evaluate होते हैं, इसलिए 2 + 3 * 4 का मान 14 है, 20 नहीं।
उदाहरण: Arithmetic Precedence
print(2 + 3 * 4)
Exponentiation Precedence
Exponentiation (**) किसी भी अन्य arithmetic operator से ज़्यादा कसकर बँधता है, यानी यह गुणा या भाग से भी पहले evaluate होता है — 2 * 3 ** 2 पहले 3 ** 2 निकालता है, जिससे 2 * 9 = 18 मिलता है।
उदाहरण: Exponentiation Precedence
print(2 * 3 ** 2)
Relational और Logical Precedence
> और == जैसे comparison operators and/or जैसे logical operators से पहले evaluate होते हैं, इसलिए a > 5 and b < 10 को इच्छित रूप से काम करने के लिए हर comparison के चारों ओर अतिरिक्त parentheses की ज़रूरत नहीं — Python पहले से उन्हें वैसे ही समूहित करती है।
उदाहरण: Relational and Logical Precedence
a, b = 6, 5
print(a > 5 and b < 10)
बाएँ-से-दाएँ Evaluation
जब दो operators का precedence स्तर एक ही हो, तो Python उन्हें बाएँ से दाएँ evaluate करती है (इसे left-associativity कहते हैं) — इसलिए 10 - 3 - 2 का मान (10 - 3) - 2 = 5 निकलता है, 10 - (3 - 2) नहीं।
उदाहरण: Left-to-Right Evaluation
print(10 - 3 - 2)
Chained Comparisons
0 <= x < 100 जैसी chained comparisons बाएँ से दाएँ क्रम में evaluate होती हैं और and की तरह short-circuit करती हैं, जिससे सीमा की जाँच लिखने में संक्षिप्त और evaluate करने में कुशल दोनों बनती है।
उदाहरण: Chained Comparisons
x = 50
print(0 <= x < 100)
- यह उम्मीद करना कि
2 + 3 * 420होगा; multiplication पहले चलता है, इसलिए यह14है (parentheses इस्तेमाल करें)। - यह मान लेना कि
-2 ** 24है;**unary minus से ज़्यादा tightly bind करता है, इसलिए यह-4है। not a == bको(not a) == bकी तरह पढ़ना; यहnot (a == b)है क्योंकिnotकी precedence==से कम होती है।
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