[Tutor] returning None from function definition

Alan Gauld alan.gauld at yahoo.co.uk
Sat Oct 24 06:40:28 EDT 2020


On 24/10/2020 07:24, Manprit Singh wrote:

> def prime(x):
>     if x < 2:
>         return None

Don't return none here, return False.
None implies no value (although Python considers it false
in boolean tests thats effectively a coincidence!) You
are explicitly returning a negative result so make
it explicit, use False.

>     else:
>         for i in range(2, int(x**0.5) + 1):
>             if x % i == 0:
>                 return None

Again return False not None

>     return True

After all you used the explicit true value here.


> A second version of the function written above :
> 
> def prime(x):
>     if x > 1:
>         for i in range(2, int(x**0.5) + 1):
>             if x % i == 0:
>                 return None

Again, return False not none

>         else:
>             return True

> In this definition there is no check for values below or equal 1 , although
> this function will also work in the problem stated at the top, values
> equals or below 1 will never be printed as prime using this function.

It works, but it does so by accident because it relies on Python
returning None by default.
One of the principles of Python is that explicit is better than
implicit so you should return False for a boolean function.
In this case by adding return False as the last line
of the function that handled the x <= 1 cases (you could add
an else to make the link to the initial if more obvious,
that's a moot choice).

> So according to you, which function is more readable? keeping readability
> as the main factor which function definition is more acceptable in this
> case ? 

As they stand neither are good since both rely on side-effects
and default responses. (And that's ignoring the use of one
instead of false!)

The second version with an added

else: return False

on the last line would be the best (IMHO) since that explicitly
handles all cases.

> What about returning  None instead of False inside Function
> definition in this case ?

That's definitely inferior. False explicitly says why it is being
returned. None requires the mental leap to remember that None is
considered false in Python logic. Don't make your reader do
more work than is necessary.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list