I understand that the method:
str.find
will return a -1 if the sub is not found.
Is there a specific reason why the value -1 is used? Is it arbitrary or is it useful to have a -1 for some further calculation involving strings?
I'm trying to understand the reasoning if any for the choice of that value.
string.find:
Return the lowest index in s where the substring sub is found such that sub is wholly contained in
s[start:end]. Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.
Since it's supposed to return an index, it makes sense to return -1 when the substring is not found (this is usually the behavior in most programming languages as well).
If you prefer that an Exception is raised instead, use the string.index method.
I've done a lot of research on this question and have come up with the following. As has been said in a number of the answers here, in traditional programing languages or early programming languages coders have dealt with errors by having functions return special values. The consequence of this however is that any other code that calls a function that returns some value has to check whether a value was returned and deal with it specifically.
In newer languages such as Python, we can raise an exception when we are unable to produce a result that is consistent with a function's specifications. While exception handling was evident in languages back in the 1960s. The following post explains that it wasn't until the 80s and 90s that design questions were largely resolved. What language was the first to implement exception handling?
Thus my conclusion is that until the advanced implementation of exception handling that could deal with error generation in a myriad of ways, the primitive method of returning some arbitrary value, was by and large all that could be accomplished until more advanced methods were created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With