Issue
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.
Solution
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
.
Answered By - hiro protagonist
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.