I have a small function as follows:
# Given the numerical value of a minute hand of a clock, return the number of degrees assuming a circular clock.
# Raise a ValueError for values less than zero or greater than 59.
def exercise_20(n):
try:
if n < 0 or n > 59:
raise ValueError("Number supplied is less than 0 or greater than 59")
except ValueError as ex:
print(ex)
else:
return n * 6
print(exercise_20(-15))
print(exercise_20(30))
print(exercise_20(75))
Here is the output:
Number supplied is less than 0 or greater than 59
None
180
Number supplied is less than 0 or greater than 59
None
Why am I returning 'None' when I strike an exception?
The function correctly prints the exception for the appropriate values and it prints the correct answer for a value within the correct range.
I don't understand why it also printing 'None' when it strikes an exception.
CodePudding user response:
You try a block, if it fails your condition if n < 0 or n > 59
, you raise. You then catch your raise and just log it. Then you return nothing. Catch and release is for fishing :).
def exercise_20(n):
if n < 0 or n > 59:
raise ValueError("Number supplied is less than 0 or greater than 59")
return n * 6
print(exercise_20(-15))
print(exercise_20(30))
print(exercise_20(75))
You might be interested on this too: https://softwareengineering.stackexchange.com/questions/187715/validation-of-the-input-parameter-in-caller-code-duplication#. When should you check for input conditions? Caller or callee?
CodePudding user response:
your function should just raise the error. let the called to the catching:
def exercise_20(n):
if n < 0 or n > 59:
raise ValueError("Number supplied is less than 0 or greater than 59")
return n * 6
for n in (-15, 30, 75, 30):
print(f"{n=}:", end=" ")
try:
print(exercise_20(n))
except ValueError as ex:
print(ex)
it will output:
n=-15: Number supplied is less than 0 or greater than 59
n=30: 180
n=75: Number supplied is less than 0 or greater than 59
n=30: 180
you code returns None
because you do not have an explicit return
statement after print(ex)
. therefore python implicitly returns None
.
CodePudding user response:
It is because else:
only happens when there is no error. So when there is an error, it skips the else
block (also skipping the return
inside it), therefore returning None
. Within the function definition, you print the error, and outside it, you print what is returned, causing the format to be
Error (if there is one)
Return value (None (if nothing is returned) or n*6)
The docs have more information.