Search code examples
pythonprintingsyntaxpython-3.xnonetype

Python Script returns unintended "None" after execution of a function


Background: total beginner to Python; searched about this question but the answer I found was more about "what" than "why";

What I intended to do: Creating a function that takes test score input from the user and output letter grades according to a grade scale/curve; Here is the code:

score = input("Please enter test score: ")
score = int(score)

def letter_grade(score):
    if 90 <= score <= 100:
        print ("A")
    elif 80 <= score <= 89:
        print ("B")
    elif 70 <= score <= 79:
        print("C")
    elif 60 <= score <= 69:
        print("D")
    elif score < 60:
        print("F")

print (letter_grade(score))

This, when executed, returns:

Please enter test score: 45
F
None

The None is not intended. And I found that if I use letter_grade(score) instead of print (letter_grade(score)) , the None no longer appears.

The closest answer I was able to find said something like "Functions in python return None unless explicitly instructed to do otherwise". But I did call a function at the last line, so I'm a bit confused here.

So I guess my question would be: what caused the disappearance of None? I am sure this is pretty basic stuff, but I wasn't able to find any answer that explains the "behind-the-stage" mechanism. So I'm grateful if someone could throw some light on this. Thank you!


Solution

  • In python the default return value of a function is None.

    >>> def func():pass
    >>> print func()     #print or print() prints the return Value
    None
    >>> func()           #remove print and the returned value is not printed. 
    >>>
    

    So, just use:

    letter_grade(score) #remove the print

    Another alternative is to replace all prints with return:

    def letter_grade(score):
        if 90 <= score <= 100:
            return "A"
        elif 80 <= score <= 89:
            return "B"
        elif 70 <= score <= 79:
            return  "C"
        elif 60 <= score <= 69:
            return "D"
        elif score < 60:
            return "F"
        else:
            #This is returned if all other conditions aren't satisfied
            return "Invalid Marks"
    

    Now use print():

    >>> print(letter_grade(91))
    A
    >>> print(letter_grade(45))
    F
    >>> print(letter_grade(75))
    C
    >>> print letter_grade(1000)
    Invalid Marks