Python Glossary Русский

all Python 3Functionsterm

return

return

Returns a value from a function. Without a return the function returns None. It can return a tuple.

Syntax

return значение

A classic beginner mistake is printing the result inside the function instead of returning it: the number shows on screen, but the caller receives None and can't use it. return ends the function immediately, so code after it never runs; return b, a without parentheses hands back a tuple.

Examples

def double(x):
    return x * 2
print(double(5))  # → 10
def swap(a, b):
    return b, a  # кортеж
a, b = swap(1, 2)
print(a, b)  # → 2 1
def nothing():
    return  # → None
print(nothing())  # → None
def safe_div(a, b):
    if b == 0:
        return None  # ранний return
    return a / b
print(safe_div(10, 0))  # → None
def classify(n):
    if n < 0:
        return 'neg'
    if n == 0:
        return 'zero'
    return 'pos'
print(classify(-1))  # → neg
def stats(lst):
    return min(lst), max(lst), sum(lst)/len(lst)
print(stats([1,2,3,4]))  # → (1, 4, 2.5)
def first_even(lst):
    for x in lst:
        if x % 2 == 0:
            return x
    return None
print(first_even([1,3,4,6]))  # → 4

See also

Open in the full glossarydocs.python.orgReport an inaccuracy