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

Python Logical Operators

Logical operators हाँ-या-ना वाले सवालों को जोड़ते हैं, जैसे यह कहना कि 'तुम तभी खेल सकते हो अगर होमवर्क पूरा किया हो AND कमरा साफ किया हो'। and, or, और not तय करते हैं कि पूरा statement सही है या नहीं।
Syntax
python
result = condition1 and condition2
result = condition1 or condition2
result = not condition

and Operator

and तभी True होता है जब दोनों operands सही हों; अगर कोई भी पक्ष गलत हो तो पूरी expression गलत होती है, जो उन दो शर्तों को जोड़ने के लिए स्वाभाविक पसंद है जिनका *दोनों* सही होना ज़रूरी हो।

उदाहरण: The and Operator

python
print(True and False)
print(5 > 2 and 3 > 1)

or Operator

or तब True होता है जब कम से कम एक operand सही हो, और तभी विफल होता है जब दोनों पक्ष गलत हों — जब भी कई शर्तों में से किसी एक के पूरा होने पर नतीजा मिलना चाहिए, यह सही औज़ार है।

उदाहरण: The or Operator

python
print(True or False)
print(5 > 10 or 3 > 1)

not Operator

not boolean value को पलट देता है: not True False बन जाता है और उल्टा भी, और अक्सर किसी condition को उसके विपरीत रूप में दोबारा लिखे बिना साफ़ ढंग से उलटने के लिए इस्तेमाल होता है।

उदाहरण: The not Operator

python
print(not True)

Logical Operators को मिलाना

एक ही expression में and, or और not को मिलाना जल्दी अस्पष्ट हो सकता है, इसलिए sub-conditions को parentheses में लपेटना — (a and b) or c — Python और अगले पढ़ने वाले, दोनों के लिए इच्छित evaluation क्रम को स्पष्ट कर देता है।

उदाहरण: Combining Logical Operators

python
a, b, c = True, False, True
print((a and b) or c)

Short-circuit Evaluation

Python logical evaluation को short-circuit करती है: a and b में, अगर a पहले से गलत है तो b को evaluate ही नहीं किया जाता, और a or b में, अगर a पहले से सही है तो b छोड़ दिया जाता है।

यह केवल optimization नहीं है — code कभी-कभी जान-बूझकर इस पर निर्भर करता है, जैसे None object पर error से बचने के लिए obj and obj.value

उदाहरण: Short-circuit Evaluation

python
obj = None
print(obj and obj.upper())
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.