'Is there Python command similar to the 'return' function in MATLAB?

Is there function in Python to can return control to the invoking script or function, similar to the function return in MATLAB?

Does the function exit() or quit() in Python do the same thing?

def absolute_value(num):
    """This function returns the absolute
    value of the entered number"""

        if num >= 0:
            # Return to the invoking script without any return value
        else:
           # Do task A
           # Do task B


print(absolute_value(2))

print(absolute_value(-4))



Solution 1:[1]

Yes, Python methods can return a value(s), similar to that example in MATLAB.

So, this MATLAB code

function idx = findSqrRootIndex(target, arrayToSearch)

idx = NaN;
if target < 0
   return
end

for idx = 1:length(arrayToSearch)
    if arrayToSearch(idx) == sqrt(target)
        return
    end
end

can effectively be written in Python as -

import math

def find_sqr_root_index(target, array_to_search):
    if target < 0:
        return # Same as return None

    # Indexing starts at 0, unlike MATLAB
    for idx in range(len(array_to_search)):
        if array_to_search[idx] == math.sqrt(target):
            return idx

a = [3, 7, 28, 14, 42, 9, 0]
b = 81
val = find_sqr_root_index(b, a)
print(val) # 5 (5 would mean the 6th element)

The Python code has method and variables names changed to adhere to Python's naming conventions.

Solution 2:[2]

Just to add, you can use return just like in MATLAB without any return value.

Python's return statement. A return statement is used to end the execution of the function call and “returns” the result (value of the expression following the return keyword) to the caller. The statements after the return statements are not executed. This is equivalent to MATLAB's return.

def my_func(a):
   # Some code
   if a == 5:
       return # This is valid too, equivalent 
              # to quit the function and go 
              # to the invoking script

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen
Solution 2 Peter Mortensen