Python None
In this page:
variable = None
if variable is None:
# no value assigned
None क्या है
None, Python का किसी value की अनुपस्थिति दर्शाने का तरीका है — यह अपने ही type, NoneType, का एक singleton object है, जो 0, खाली string या False से अलग है भले ही ये सब falsy हों।
Variables को अक्सर पहले None से initialize किया जाता है और बाद में कोई सार्थक चीज़ assign की जाती है।
उदाहरण: What Is None
result = None # represents the absence of a value
print(result)
print(type(result)) # shows <class 'NoneType'>
None की जाँच
None की जाँच के लिए '== None' की जगह 'is None' इस्तेमाल कीजिए — is object की पहचान (identity) की तुलना करता है, और क्योंकि None एक सच्चा singleton है, identity की तुलना PEP 8 के अनुसार शैली में सही और तकनीकी रूप से ज़्यादा सही भी है, क्योंकि कोई custom class सैद्धांतिक रूप से == को अप्रत्याशित व्यवहार के लिए override कर सकती है।
उदाहरण: Checking for None
value = None
print(value is None)
None बतौर Default Return Value
जिस function में कोई स्पष्ट return statement न हो, या जिसमें बिना कुछ बाद में लिखे सिर्फ़ return हो, वह परोक्ष रूप से None लौटाता है — इसीलिए किसी ऐसे function में जिसे value बनानी चाहिए, return statement भूल जाना चुपचाप होने वाले bugs का आम स्रोत है।
उदाहरण: None as a Default Return Value
def log(message):
print(message)
result = log("hi") # log() has no return statement, so it implicitly returns None
print(result)
None बतौर Default Argument
किसी default parameter value के रूप में None का उपयोग, mutable-default-argument की क्लासिक समस्या का मानक उपाय है — 'def f(items=[])' लिखने के बजाय, जो calls के बीच वही list दोबारा इस्तेमाल करता है, 'def f(items=None)' लिखिए और items के None होने पर function के भीतर नई list बनाइए।
उदाहरण: None as a Default Argument
def add_item(item, items=None): # None avoids the mutable-default-argument pitfall
if items is None:
items = [] # a fresh list is created on every call
items.append(item)
return items
print(add_item("apple"))
print(add_item("banana"))
Comparisons और Collections में None
None को lists, dictionaries या किसी भी अन्य collection में किसी भी दूसरे value की तरह रखा जा सकता है, और None की खुद से '==' से तुलना ठीक काम करती है और True लौटाती है — केवल 0 या '' जैसे अन्य falsy values से तुलना में ही None सही ढंग से बराबर नहीं ठहरता।
उदाहरण: None in Comparisons and Collections
values = [1, None, 3]
print(None in values) # None can be stored and searched for like any value
print(None == None) # comparing None to itself is True
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: