Python में Return Values
In this page:
def function_name(parameter):
# body
return value
result = function_name(argument)
return Statement
return उस code को एक value वापस भेजता है जिसने function को call किया था, और return चलते ही function का execution रुक जाता है -- उसी block में उसके बाद लिखा गया कोई भी code कभी execute नहीं होता।
उदाहरण: The return Statement
def add(a, b):
return a + b
print("This never runs") # unreachable, return already exited the function
print(add(2, 3))
Implicit return None
बिना किसी return statement वाला function खत्म होते ही implicitly None वापस देता है; बिना किसी value के सिर्फ़ return लिखना भी बिल्कुल वही करता है, यह explicitly function को जल्दी खत्म करता है लेकिन फिर भी कोई meaningful चीज़ वापस नहीं देता।
उदाहरण: Implicit return None
def log(message):
print(message)
result = log("hi") # log has no return statement, so it implicitly returns None
print(result)
कई Values Return करना
return a, b लिखना ऐसा दिखता है जैसे दो अलग values return हो रही हों, लेकिन Python असल में उन्हें अपने-आप एक ही tuple में pack कर देता है -- caller फिर उस tuple को x, y = my_function() से वापस दो variables में unpack कर सकता है।
उदाहरण: Returning Multiple Values
def min_max(numbers):
return min(numbers), max(numbers) # packs two values into a tuple
x, y = min_max([3, 1, 4, 1, 5]) # unpacks the tuple into x and y
print(x, y)
Complex Data Types Return करना
एक function कोई भी Python object return कर सकता है -- list, dictionary, custom class instance -- सिर्फ़ साधारण numbers या strings नहीं, यही वजह है कि functions बड़े programs के लिए composable building blocks बनते हैं।
उदाहरण: Returning Complex Data Types
def make_user():
return {"name": "Alex", "age": 30} # returns a dict, not just a number or string
user = make_user()
print(user)
Early return
किसी invalid input या edge case के पहचान होते ही return कर देना -- बाकी function को else के अंदर nest करने के बजाय -- एक common style है जिसे "guard clause" कहा जाता है, और यह आमतौर पर main logic को flatter और follow करने में आसान बनाए रखता है।
उदाहरण: Early return
def safe_divide(a, b):
if b == 0:
return None # guard clause exits early to avoid dividing by zero
return a / b
print(safe_divide(10, 0))
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: