मुख्य Python · #4 / 11
Functions + Scope
दोबारा इस्तेमाल होने वाला logic और साफ़ code
यह क्यों मायने रखता है
Functions आपके logic को दोबारा इस्तेमाल होने लायक़, testable, और पढ़ने में आसान बनाए रखते हैं।
मूल विचार
एक function एक छोटा प्रोग्राम है: input → प्रोसेसिंग → output। Default arguments एक function को कई बना देते हैं; *args / **kwargs इसे variadic बना देते हैं। Scope LEGB का पालन करता है: Local → Enclosing → Global → Built-in।
आज़माकर देखिए
Default args + keyword args:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Ada"))
print(greet("Linus", greeting="Hi"))
print(greet(greeting="Howdy", name="Margaret"))
*args / **kwargs बचे हुए positional और keyword arguments पकड़ लेते हैं:
def describe(*things, **labels):
for t in things:
print("-", t)
for k, v in labels.items():
print(k, "=", v)
describe("apple", "banana", "cherry", colour="red", taste="sweet")
Scope: एक function बाहरी names देख सकता है पर nonlocal / global के बिना उन्हें फिर से bind नहीं कर सकता:
counter = 0
def inc():
global counter
counter += 1
inc(); inc(); inc()
print("counter:", counter)
def outer():
x = 1
def inner():
nonlocal x
x += 10
inner()
print("outer.x:", x)
outer()
Data type के अनुसार function के pattern
एक function का आकार अक्सर उस type का अनुसरण करता है जिस पर वह काम करता है। ये तीन pattern सीधे data-structure वाले पाठों से जुड़ जाते हैं:
- list → एक नई list लौटाएँ:
[x*2 for x in nums] - dict →
.get()से बनाएँ:counts[x] = counts.get(x, 0) + 1 - str → सामान्य कीजिए, फिर तुलना:
s.lower()
झटपट जाँच
- प्र:
printऔरreturnमें क्या फ़र्क़ है? उ:returnएक मान वापस देता है;printबस दिखाता है।
छोटे अभ्यास
is_even(n)लिखिए।- एक loop का इस्तेमाल करके
square_all(nums)लिखिए।
क्या करें और क्या न करें
- करें functions छोटे और केंद्रित रखें।
- न करें
def f(x=[])जैसे mutable default args इस्तेमाल न करें।
आम ग़लतियाँ
- ग़लती: मान return करना भूल जाना। समाधान:
returnजोड़ें। - ग़लती: किसी default list argument को बदलना। समाधान:
Noneइस्तेमाल करें और list को अंदर बनाएँ।
मुख्य बातें
- Default arguments परिभाषा के समय एक ही बार मूल्यांकित होते हैं — mutables को defaults के रूप में इस्तेमाल न करें।
*args/**kwargsforwarding को संभव बनाते हैं (f(*args, **kwargs))।- LEGB scope: Local → Enclosing → Global → Built-in।
- Pure functions (बिना side effects वाले) test करने और समझने में आसान होते हैं।