Skip to content

Python function return variable

  • by

You can return variables from Python functions the same as return any value. You have to make sure variables are in the scope of the function.

Note: Python function is not required to return a variable, it can return zero, one, two, or more variables.

Python function return variable

Simple example code stores a return value in a variable in Python.

# int var
def func():
    a = 10
    return a


print(func())


# string var
def func2():
    x = "random"

    print("random")
    return x


func2()

Output:

Python function return variable

Or

def myfunction():
    value = "myvalue"
    return value

var = myfunction()
print(var)

Output: myvalue

Multiple Return Values

You can also return multiple values by separating them with commas. The returned values are captured as a tuple.

def arithmetic_operations(a, b):
    sum = a + b
    difference = a - b
    product = a * b
    quotient = a / b if b != 0 else None
    return sum, difference, product, quotient

# Calling the function
results = arithmetic_operations(10, 5)
print(results)  # Output: (15, 5, 50, 2.0)

# Unpacking the returned values
sum, difference, product, quotient = arithmetic_operations(10, 5)
print(sum)        # Output: 15
print(difference) # Output: 5
print(product)    # Output: 50
print(quotient)   # Output: 2.0

Returning None

If no return statement is encountered or if return is used without an argument, the function will return None.

def do_nothing():
    pass

result = do_nothing()
print(result)  # Output: None

By using the return statement effectively, you can control the output of your functions and use those outputs in subsequent code.

Do comment if you have any doubts or suggestions on this Python function topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading