[Tutor] returning None from function definition

Manprit Singh manpritsinghece at gmail.com
Sat Oct 24 09:22:33 EDT 2020


Dear Alan sir ,

Based on your comments, I have written it again . Hope this definition is
perfectly fine .
def prime(x):
    if x > 1:
        for i in range(2, int(x**0.5) + 1):
            if x % i == 0:
                return False
        else:
            return True
    else:
        return False

Many many thanks for your suggestions,
Regards
Manprit Singh

On Sat, Oct 24, 2020 at 11:54 AM Manprit Singh <manpritsinghece at gmail.com>
wrote:

> Dear Sir ,
>
> Consider a problem :
> WAP a program that accepts two integers as user input from keyboard (a and
> b), and then prints all prime numbers within the range(a, b+1).
>
> def prime(x):
>     if x < 2:
>         return None
>     else:
>         for i in range(2, int(x**0.5) + 1):
>             if x % i == 0:
>                 return None
>     return True
>
> a = int(input("Enter first number"))
> b = int(input("Enter second number"))
> for k in range(a, b+1):
>     if prime(k):
>         print(k)
>
> In this program each value within the range(a, b+1) will be checked if it
> is prime number or not . and if it is a prime number it will get printed.
>
> 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
>         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.
>
> So according to you, which function is more readable? keeping readability
> as the main factor which function definition is more acceptable in this
> case ? What about returning  None instead of False inside Function
> definition in this case ?
> Kindly suggest if any improvement needed.
>
> Regards
> Manprit Singh
>
>
>


More information about the Tutor mailing list