-1

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))

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mpx
  • 3,081
  • 2
  • 26
  • 56
  • 2
    It's `return` in python too. – Zabir Al Nazi Apr 26 '20 at 10:03
  • Thanks @zabir for the response. So, it save to return without any return value? Also, is there any possibilities to avoid using the else. I mean, The task A and B will in same alignment with the if vertical line? – mpx Apr 26 '20 at 10:12

2 Answers2

2

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tidakdiinginkan
  • 918
  • 9
  • 18
  • @ZabirAlNazi You can test the code for `b = -8` for example, the value of `val` turns out to be None. – tidakdiinginkan Apr 26 '20 at 10:20
  • @ZabirAlNazi it isn't best practice to return None anyway, best to have a value like -1 for eg:, indicating that the element was not found. I found a good read [here](https://stackoverflow.com/questions/15300550/return-return-none-and-no-return-at-all) – tidakdiinginkan Apr 26 '20 at 10:27
1

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zabir Al Nazi
  • 10,298
  • 4
  • 33
  • 60