← Back to Python Course | Chapter 4: Functions | Lesson 3 of 9

Python में Return Values

Return value वह जवाब है जो function खत्म होने पर वापस देता है, जैसे कोई vending machine आपको snack देती है। फिर आप उस जवाब को अपने program के बाकी हिस्से में इस्तेमाल कर सकते हैं।
Syntax
python
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

python
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

python
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

python
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

python
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

python
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))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.