Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return of None not expected

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading