I'm a user of R, but have to learn Python for a school project. Now, in R, I frequently use the base function stop in my code, and I'd like to know how to emulate this functionality in Python. For a concrete example, take this R code:
add.two <- function(t) {
if (!is.numeric(t)) stop('Please make t numeric.')
t + 2
}
This function does three things, (i) it adds two to (e.g.) a numeric vector, (ii) if it is passed a non-numeric argument it returns a personal, concise, and easy to understand error message, and (iii) it ceases the function from running any further in the case that t is non-numeric. My first attempt for how to do this in Python is
def add_two(t):
if not ( isinstance(t, int) or isinstance(t, float) ):
print('Error: Please make t numeric.')
else:
print(t+2)
However, this only does things (i) and (ii). In other words, if the body of this function were longer (although, in this example, it is not), Python would not know to stop running. Another option is
def add_two(t):
if not ( isinstance(t, int) or isinstance(t, float) ):
print('Error: Please make t numeric.')
raise
else:
print(t+2)
Which, I suppose, does things (i) and (iii), but the error message is at best cluttered and confusing, and at worst incorrect and misleading.
Does someone know of a way to achieve all three goals in Python? Thank you for your time.
Edit: IDK why, I said 'error' instead of 'stop' just a brain fart.
return, if you want to stop the whole scriptraisean exceptionisinstance(t, (int, float))