Python Function Return Values

What is a Return Value?

A return value is the output that a function sends back to the part of the program where it was called. The return statement ends the function execution and "returns" the result.

Why Use Return?

Using return lets your function give back a result that can be stored in a variable, used in expressions, or passed to other functions. Without return, a function does some work but does not produce a reusable output.

return का उपयोग करने से आपका function ऐसा परिणाम देता है जिसे किसी variable में संग्रहित किया जा सकता है, expression में इस्तेमाल किया जा सकता है या अन्य functions को दिया जा सकता है। बिना return के, function सिर्फ काम करता है लेकिन पुनः उपयोग योग्य आउटपुट नहीं देता।

When is Return Useful?

Return is useful when you want your function to:

  • Send back calculated values
  • Process data and provide results to use elsewhere
  • Make your code modular and reusable

Return तब उपयोगी होता है जब आप चाहते हैं कि आपका function:

  • गणना किए गए मान वापस भेजे
  • डाटा प्रोसेस करके अन्य जगह उपयोग के लिए परिणाम प्रदान करे
  • आपका कोड मॉड्यूलर और पुनः उपयोग योग्य बने

Examples with Explanation

Example 1: Simple Return Value
def add(a, b):
    return a + b

result = add(5, 3)
print(result)

The function returns the sum of a and b, which is stored in 'result' and printed.

यह function a और b का योग वापस करता है, जिसे 'result' में स्टोर करके प्रिंट किया जाता है।

Output:

8
Example 2: Return Without Value
def greet():
    print('Hello!')

result = greet()
print(result)

Function prints 'Hello!' but returns nothing, so 'result' is None.

function 'Hello!' प्रिंट करता है लेकिन कोई वैल्यू वापस नहीं करता, इसलिए 'result' None होगा।

Output:

Hello!
None
Example 3: Returning Multiple Values
def get_stats(numbers):
    return min(numbers), max(numbers), sum(numbers)

min_val, max_val, total = get_stats([2, 5, 1, 7])
print(min_val, max_val, total)

Function returns multiple values as a tuple, which are unpacked into variables.

function कई मान टुपल के रूप में वापस करता है, जिन्हें अलग-अलग variables में असाइन किया जाता है।

Output:

1 7 15
Example 4: Early Return to Exit Function
def check_positive(num):
    if num <= 0:
        return 'Not Positive'
    return 'Positive'

print(check_positive(10))
print(check_positive(-5))

Return stops function execution early and sends back a value.

return function के execution को जल्दी रोक देता है और मान वापस भेजता है।

Output:

Positive
Not Positive
Example 5: Returning a Function Result
def square(x):
    return x * x

def double_square(x):
    return 2 * square(x)

print(double_square(4))

Functions can return results of other functions to build complex operations.

functions अन्य functions के परिणाम वापस कर सकते हैं जिससे जटिल ऑपरेशन बनते हैं।

Output:

32