Python Function के Parameters
In this page:
def function_name(parameter1, parameter2):
# body
function_name(argument1, argument2)
function_name(parameter2=value, parameter1=value)
Parameters और Arguments क्या हैं?
Parameters वे placeholder नाम हैं जो function की definition में listed होते हैं, जबकि arguments वे असली values हैं जो function को call करते समय दी जाती हैं -- यह फ़र्क़ इसलिए मायने रखता है क्योंकि parameters function के interface को describe करते हैं, जबकि arguments किसी एक specific call के लिए उसे भरते हैं।
उदाहरण: What are Parameters and Arguments?
def greet(name): # name is the parameter
print("Hello,", name)
greet("Alex") # "Alex" is the argument
Positional Arguments
Default रूप से, Python arguments को parameters से position के आधार पर match करता है -- पहला argument पहले parameter को भरता है, और आगे भी ऐसे ही -- इसलिए call में values देने का क्रम उसी क्रम से मेल खाना चाहिए जिसमें उन्हें define किया गया था।
उदाहरण: Positional Arguments
def describe(animal, sound):
print(animal, "says", sound)
describe("Cat", "Meow") # "Cat" fills animal, "Meow" fills sound, by position
Keyword Arguments
position पर निर्भर रहने के बजाय parameter नाम के साथ explicitly name="value" pass करना आपको किसी भी क्रम में arguments देने देता है और call को self-documenting बना देता है, क्योंकि parameter का नाम call site पर ही सीधे दिख जाता है।
उदाहरण: Keyword Arguments
def describe(animal, sound):
print(animal, "says", sound)
describe(sound="Meow", animal="Cat") # order doesn't matter when using keyword arguments
Mutable Parameters को Modify करना
क्योंकि lists और dictionaries mutable होती हैं, किसी function में उन्हें pass करना और अंदर modify करना (जैसे .append() call करना) उस original object को बदल देता है जिसे caller अब भी hold किए हुए है -- यह किसी number या string को pass करने से अलग है, जिसे in-place बदला नहीं जा सकता।
उदाहरण: Modifying Mutable Parameters
def add_item(cart):
cart.append("apple") # mutates the list object passed in
cart = []
add_item(cart)
print(cart) # shows the change, since lists are mutable and shared by reference
Positional-Only और Keyword-Only Parameters
parameter list में / उससे पहले की हर चीज़ को positionally pass करने के लिए मजबूर करता है, और * उसके बाद की हर चीज़ को सिर्फ़ keyword से pass करने के लिए -- ये दोनों optional safeguards हैं जो किसी function की calling convention को explicit बनाते हैं और उसका गलत इस्तेमाल करना मुश्किल कर देते हैं।
उदाहरण: Positional-Only and Keyword-Only Parameters
def greet(name, /, *, greeting): # / forces name to be positional, * forces greeting to be keyword
print(greeting, name)
greet("Alex", greeting="Hi")
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: