Python में not: तार्किक NOT ऑपरेटर समझाया गया

Python NOT ऑपरेटर का उपयोग करना सीखें बूलियन मानों को उलटने, नकारात्मक स्थितियां लिखने और व्यावहारिक उदाहरणों और सर्वोत्तम प्रथाओं के साथ प्रोग्राम प्रवाह को नियंत्रित करने के लिए।

Python में not ऑपरेटर एक एकल तार्किक ऑपरेटर है जो अपने ऑपरेंड के सत्य मान को उलट देता है। यह True लौटाता है यदि ऑपरेंड False के रूप में मूल्यांकन करता है, और False लौटाता है यदि ऑपरेंड True के रूप में मूल्यांकन करता है। and और or ऑपरेटरों के विपरीत जिन्हें दो ऑपरेंड की आवश्यकता होती है, not एक ही ऑपरेंड के साथ काम करता है और अंग्रेजी शब्द "not" के रूप में लिखा जाता है।

मूल NOT ऑपरेटर सिंटैक्स

not ऑपरेटर एक एकल ऑपरेटर है जो एक ही ऑपरेंड लेता है और इसके सत्य मान को उलट देता है।

condition1 or condition2

not ऑपरेटर True लौटाता है यदि ऑपरेंड False है, और False लौटाता है यदि ऑपरेंड True है।

उदाहरण 1: मूल NOT ऑपरेशन

bool1 = 2 > 3  # False
bool2 = 2 < 3  # True

result = bool1 or bool2
print(result)
आउटपुट:
False
True
False
True

Example 2: Both False

bool1 = 2 > 3  # False
bool2 = 5 > 10  # False

result = bool1 or bool2
print(result)
Output:
False

When both conditions are False, the or operator returns False.

NOT ऑपरेटर के लिए सत्य तालिका

not ऑपरेटर कैसे काम करता है इसे समझना नकारात्मक स्थितियां लिखने के लिए आवश्यक है।

Condition 1 Condition 2 not ऑपरेंड
True True True
True False False
False True False
False False False

not ऑपरेटर बूलियन मान को नकारता है, True को False में बदलता है और इसके विपरीत।

Example: All Truth Table Cases

# Case 1: True or True = True
if True or True:
    print("Case 1: True")  # This executes

# Case 2: True or False = True
if True or False:
    print("Case 2: True")  # This executes

# Case 3: False or True = True
if False or True:
    print("Case 3: True")  # This executes

# Case 4: False or False = False
if False or False:
    print("Case 4: True")
else:
    print("Case 4: False")  # This executes
Output:
Case 1: True
Case 2: True
Case 3: True
Case 4: False

Combining Multiple Conditions

The and operator is commonly used to combine multiple comparison operations in conditional statements.

Example 1: Age and License Check

age = 25
has_license = True

if age >= 18 and has_license:
    print("You can drive")
else:
    print("You cannot drive")
Output:
You can drive

Example 2: Number Range Check

number = 15

if number > 10 and number < 20:
    print(f"{number} is between 10 and 20")
Output:
15 is between 10 and 20

Example 3: Multiple Conditions

a = 10
b = 10
c = -10

if a > 0 and b > 0:
    print("The numbers are greater than 0")

if a > 0 and b > 0 and c > 0:
    print("All numbers are greater than 0")
else:
    print("At least one number is not greater than 0")
Output:
The numbers are greater than 0
At least one number is not greater than 0

This example shows how and can chain multiple conditions together.

Short-Circuit Evaluation

Python's and operator uses short-circuit evaluation, meaning if the first condition is False, Python doesn't evaluate the second condition because the result is already determined to be False.

Example: Demonstrating Short-Circuit

def check_first():
    print("First condition evaluated")
    return False

def check_second():
    print("Second condition evaluated")
    return True

# Short-circuit in action
if check_first() and check_second():
    print("Both are True")
else:
    print("At least one is False")
Output:
First condition evaluated
At least one is False

Notice that "Second condition evaluated" never prints because check_first() returned False, so Python skipped evaluating check_second(). This optimization improves performance and prevents unnecessary computations.

Example 2: Avoiding Division by Zero

x = 0
y = 10

# Safe division check
if x != 0 and y / x > 2:
    print("y/x is greater than 2")
else:
    print("Cannot divide or condition not met")
Output:
Cannot divide or condition not met

The short-circuit evaluation prevents the division by zero error because x != 0 is False, so y / x is never evaluated.

Using and with Boolean Variables

Boolean variables can be combined directly with the and operator without comparison operators.

Example 1: Direct Boolean Check

is_logged_in = True
has_permission = True

if is_logged_in and has_permission:
    print("Access granted")
else:
    print("Access denied")
Output:
Access granted

Example 2: Multiple Boolean Flags

a = 10
b = 12
c = 0

if a and b and c:
    print("All numbers have boolean value as True")
else:
    print("At least one number has boolean value as False")
Output:
At least one number has boolean value as False

In Python, 0 evaluates to False in boolean context, while non-zero numbers evaluate to True.

Chaining Multiple Conditions

You can chain multiple and operators together to check several conditions at once.

Example 1: Grade Requirements

attendance = 85
homework_score = 90
exam_score = 88

if attendance >= 80 and homework_score >= 85 and exam_score >= 85:
    print("You passed the course with good grades")
else:
    print("Requirements not met")
Output:
You passed the course with good grades

Example 2: Password Validation

password = "SecurePass123"

has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)
min_length = len(password) >= 8

if has_upper and has_lower and has_digit and min_length:
    print("Password is strong")
else:
    print("Password does not meet requirements")
Output:
Password is strong

Example 3: Date Range Validation

year = 2024
month = 6
day = 15

if year > 2000 and month >= 1 and month <= 12 and day >= 1 and day <= 31:
    print("Valid date")
else:
    print("Invalid date")
Output:
Valid date

Python 'and' vs Other Languages '&&'

Unlike languages like C, C++, Java, or JavaScript that use && for logical AND, Python uses the keyword and.

Python Syntax:

x = 5
y = 10

if x < y and y < 15:
    print("Both conditions are True")

Other Languages (JavaScript/Java/C++):

// This does NOT work in Python
if (x < y && y < 15) {
    console.log("Both conditions are True");
}

Important: Attempting to use && in Python will result in a SyntaxError. Always use the keyword and in Python.

# This will cause an error
# if x > 0 && y > 0:  # SyntaxError
#     print("Error!")

# Correct Python syntax
if x > 0 and y > 0:
    print("Correct!")

Combining and with or Operator

You can mix and and or operators in the same expression, but remember that and has higher precedence than or. Use parentheses to control evaluation order.

Example 1: Without Parentheses

age = 25
has_ticket = True
is_vip = False

# and has higher precedence than or
if age >= 18 and has_ticket or is_vip:
    print("You can enter")
Output:
You can enter

This evaluates as: (age >= 18 and has_ticket) or is_vip

Example 2: With Parentheses for Clarity

score = 75
extra_credit = 10

# Explicit grouping
if (score >= 70 and score < 80) or extra_credit >= 20:
    print("Grade: B")
Output:
Grade: B

Example 3: Complex Condition

temperature = 25
is_sunny = True
is_weekend = True

if (temperature > 20 and is_sunny) or is_weekend:
    print("Good day for outdoor activities")
Output:
Good day for outdoor activities

सामान्य उपयोग के मामले

उपयोग मामला 1: आवश्यक फ़ील्ड सत्यापित करना

username = "alice"
password = "password123"
email = "alice@example.com"

if len(username) > 0 and len(password) >= 8 and "@" in email:
    print("Registration successful")
else:
    print("Please check your input")
आउटपुट:
{'success': True, 'user': {...}}

उपयोग मामला 2: त्रुटि हैंडलिंग

age = 22
citizen = True
registered = True

if age >= 18 and citizen and registered:
    print("You are eligible to vote")
else:
    print("You are not eligible to vote")
आउटपुट:
त्रुटि: फ़ाइल 'nonexistent.txt' नहीं मिली

उपयोग मामला 3: गेम स्टेट प्रबंधन

purchase_amount = 150
is_member = True
has_coupon = True

if purchase_amount > 100 and (is_member or has_coupon):
    discount = 0.15
    final_price = purchase_amount * (1 - discount)
    print(f"You qualify for 15% discount. Final price: ${final_price}")
आउटपुट:
True
गेम रोक दिया गया
False
गेम फिर से शुरू किया गया
True

Use Case 4: Access Control

user_role = "admin"
is_authenticated = True
session_valid = True

if is_authenticated and session_valid and user_role == "admin":
    print("Access granted to admin panel")
else:
    print("Access denied")
Output:
Access granted to admin panel

Use Case 5: Data Validation

data = [1, 2, 3, 4, 5]

if len(data) > 0 and all(isinstance(x, int) for x in data) and min(data) >= 0:
    print("Data is valid")
else:
    print("Invalid data")
Output:
Data is valid

Nested Conditions vs and Operator

Using the and operator is often cleaner than nesting multiple if statements.

Nested Approach (Less Readable):

age = 25
income = 50000

if age >= 21:
    if income >= 30000:
        print("Loan approved")
    else:
        print("Insufficient income")
else:
    print("Age requirement not met")

Using and Operator (More Readable):

age = 25
income = 50000

if age >= 21 and income >= 30000:
    print("Loan approved")
else:
    print("Requirements not met")
Output:
Loan approved

The second approach using and is more concise and easier to understand.

बचने के लिए सामान्य गलतियां

गलती 1: "not" और "not in" को भ्रमित करना

# Wrong - SyntaxError
# if x > 0 && y > 0:
#     print("Both positive")

# Correct
if x > 0 and y > 0:
    print("Both positive")

गलती 2: ऑपरेटर प्राथमिकता त्रुटियां

# Ambiguous - may not work as intended
if x > 5 and y > 3 or z < 10:
    print("Condition met")

# Better - use parentheses
if (x > 5 and y > 3) or z < 10:
    print("Condition met")

गलती 3: == False के साथ तुलना करना

x = 5

# Wrong - doesn't work as expected
# if x == 3 or 5 or 7:  # Always True!

# Correct
if x == 3 or x == 5 or x == 7:
    print("x is 3, 5, or 7")

# Even better - use 'in'
if x in [3, 5, 7]:
    print("x is 3, 5, or 7")

Mistake 4: Not Considering Short-Circuit

# Potentially unsafe
# if len(my_list) > 0 and my_list[0] > 10:  # Error if my_list doesn't exist

# Safe approach
my_list = []
if my_list and len(my_list) > 0 and my_list[0] > 10:
    print("First element is greater than 10")

सर्वोत्तम प्रथाएं

अभ्यास 1: बूलियन निषेध के लिए 'not' का उपयोग करें

# Clearer with parentheses
if (age >= 18 and age <= 65) and (has_license or has_permit):
    print("Can drive")

अभ्यास 2: 'if variable == False:' के बजाय 'if not variable:' पसंद करें

# Instead of this:
# if user.age >= 18 and user.has_account and user.verified and not user.banned:
#     grant_access()

# Do this:
is_adult = user.age >= 18
has_valid_account = user.has_account and user.verified
not_banned = not user.banned

if is_adult and has_valid_account and not_banned:
    print("Access granted")

अभ्यास 3: जटिल बूलियन अभिव्यक्तियों के लिए कोष्ठक का उपयोग करें

# Put the most likely to fail condition first
def cheap_check():
    return True

def expensive_operation():
    return True

if cheap_check() and expensive_operation():
    print("Both passed")

अभ्यास 4: ऑपरेटर प्राथमिकता से सावधान रहें

# Poor
# if a and b and c:
#     do_something()

# Better
is_authenticated = True
has_permission = True
is_active = True

if is_authenticated and has_permission and is_active:
    print("Action allowed")

इसे स्वयं आज़माएं

नीचे दिए गए कोड को संशोधित करके आपने जो सीखा है उसका अभ्यास करें। विभिन्न आउटपुट देखने के लिए मानों और स्थितियों को बदलने का प्रयास करें!

तैयार
main.py
आउटपुट कंसोल 0 ms
// परिणाम देखने के लिए "कोड चलाएं" पर क्लिक करें

संबंधित विषय

अक्सर पूछे जाने वाले प्रश्न

Python में 'not' और '!' में क्या अंतर है?

Python तार्किक NOT संचालन के लिए not कीवर्ड का उपयोग करता है। ! प्रतीक का उपयोग C, Java और JavaScript जैसी अन्य भाषाओं में किया जाता है, लेकिन यह Python में SyntaxError का कारण बनेगा।

'not' और 'not in' में क्या अंतर है?

not ऑपरेटर एक तार्किक ऑपरेटर है जो बूलियन मानों को नकारता है। not in ऑपरेटर एक सदस्यता ऑपरेटर है जो जांचता है कि कोई तत्व अनुक्रम में नहीं है। वे अलग-अलग उद्देश्यों की सेवा करते हैं।

'not' की 'and' और 'or' की तुलना में प्राथमिकता क्या है?

not ऑपरेटर की तार्किक ऑपरेटरों के बीच सबसे अधिक प्राथमिकता है, उसके बाद and, फिर or। इसका मतलब है कि not a and b को (not a) and b के रूप में मूल्यांकन किया जाता है।

मुझे 'if not x:' या 'if x == False:' का उपयोग करना चाहिए?

if x == False: के बजाय if not x: पसंद करें। पहला falsy मानों (None, 0, खाली स्ट्रिंग आदि) की जांच करता है, जबकि दूसरा केवल बूलियन False मान की जांच करता है।

क्या मैं 'not' को गैर-बूलियन मानों के साथ उपयोग कर सकता हूं?

हां। Python बूलियन संदर्भ में मानों का मूल्यांकन करता है। not पहले ऑपरेंड को बूलियन में परिवर्तित करता है, फिर इसे नकारता है। Falsy मान (0, None, खाली संग्रह) नकारे जाने पर True बन जाते हैं।

मैं 'not' के साथ बूलियन मान को कैसे टॉगल करूं?

बूलियन मान को उलटने के लिए आप toggle = not toggle का उपयोग कर सकते हैं। यह लूप या स्टेट प्रबंधन में वैकल्पिक क्रियाओं के लिए एक सामान्य पैटर्न है।