0

my question is what return -1 does in this code and overall? like when you return number in a function what exactly it does?



def linearSearch(array, n, x):

    # Going through array sequencially
    for i in range(0, n):
        if (array[i] == x):
            return i
    return -1


array = [2, 4, 0, 1, 9]
x = 1
n = len(array)
result = linearSearch(array, n, x)
if(result == -1):
    print("Element not found")
else:
    print("Element found at index: ", result)
Mehdi_
  • 9
  • 1
  • 2
  • The function is returning `-1` to signal that the searched element was not fund, otherwise it returns the index where it was found. – Óscar López Dec 01 '21 at 13:57
  • It literally returns this number. Say, after `result = linearSearch([], 0, 5)`, `result` will be `-1` – ForceBru Dec 01 '21 at 13:57
  • If you want to understand "return", it should be covered in any tutorial. Think of it as the output of the function, output which other parts of the code can use. – John Coleman Dec 01 '21 at 13:57
  • 1
    It is just a flag, if you replace the various `-1` with `"potato"` it will work identically – mozway Dec 01 '21 at 13:58
  • ``return`` is a pretty fundamental statement and any tutorial should have introduced you to it. Do you know what it means to return something other than a number? – MisterMiyagi Dec 01 '21 at 13:58
  • 1
    `-1` is easily distinguishable from a "valid" index (which ranges from `0` to `len(array) - 1`). However, `-1` can be *used* as an index, in which case it is treated as an offset from the end of the array, rather than the beginning. As such, it's not really a good choice as a sentinel, because it could accidentally be used an index unless you explicitly check. `None` is better, because it cannot silently be used as an index. – chepner Dec 01 '21 at 14:01

1 Answers1

0

Return is a statement to terminate a function. It is the value that should be given to a variable when called. It is the value that must be "returned" when the function is overall executed. Let us say, in your program we wrote a statement:

j=linearSearch([1,2,3,4],3,2)

Then the function is getting called. The function is executed and according to your code it will become:

for i in range(0,3):
    if [1,2,3,4][i]==2:
        return i
    return -1

Here, the condition gets satisfied for i=1 because at index 1, 2 is present. So the return value i.e. j's is 1 and the function gets terminated. If we take another example:

j=linearSearch ([1,2,3,4],3,5)

Then the code would be:

for i in range(0,3):
    if [1,2,3,4][i]==5:
        return i
    return -1

Here, the condition never gets satisfied and the loop is completed. Now the return value i.e. j's value is -1