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

Python Operator Precedence

Operator precedence वह क्रम है जिसमें Python किसी गणित के सवाल के हिस्सों को हल करता है, ठीक वैसे ही जैसे स्कूल में जोड़ से पहले गुणा करना। Brackets आपको तय करने देते हैं कि पहले क्या होगा।
Syntax
python
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

python
print(2 + 3 * 4)

Exponentiation Precedence

Exponentiation (**) किसी भी अन्य arithmetic operator से ज़्यादा कसकर बँधता है, यानी यह गुणा या भाग से भी पहले evaluate होता है — 2 * 3 ** 2 पहले 3 ** 2 निकालता है, जिससे 2 * 9 = 18 मिलता है।

उदाहरण: Exponentiation Precedence

python
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

python
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

python
print(10 - 3 - 2)

Chained Comparisons

0 <= x < 100 जैसी chained comparisons बाएँ से दाएँ क्रम में evaluate होती हैं और and की तरह short-circuit करती हैं, जिससे सीमा की जाँच लिखने में संक्षिप्त और evaluate करने में कुशल दोनों बनती है।

उदाहरण: Chained Comparisons

python
x = 50
print(0 <= x < 100)
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.