मुख्य 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"))
not loaded

*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")
not loaded

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()
not loaded

Data type के अनुसार function के pattern

एक function का आकार अक्सर उस type का अनुसरण करता है जिस पर वह काम करता है। ये तीन pattern सीधे data-structure वाले पाठों से जुड़ जाते हैं:

झटपट जाँच

छोटे अभ्यास

क्या करें और क्या न करें

आम ग़लतियाँ

मुख्य बातें