Can't understand this output

Question:

This is my code:

def temp(c):
    f = c * 9/5 + 32
    if c <= -273:
        print("not possible")
    else:
        return f
print(temp(-273))

It is outputting the correct answer but I can’t understand why it’s also printing None with it whenever the if condition is fulfilled.

Asked By: Praguru 14

||

Answers:

When we call the inbuilt print function, the function expects a value to print out. In your code when print(temp(-273)) is called, the if part of condition is executed however there is not a value returned. By default, a function which doesn’t explicitly return anything returns None. That is what happens after calling the print() in your code.

Answered By: Jack

This:

def temp(c):
    f= c* 9/5 + 32
    if c <= -273:
        print(" not possible")
    else:
        return f

Is equal to this:

def temp(c):
    f= c* 9/5 + 32
    if c <= -273:
        print(" not possible")
    else:
        return f
    return None

Because functions in Python always return something, and that something is None if there is nothing else returned.

So the two cases of your if-else -block are essentially like this:

c <= -273:
    print(" not possible")
    print(None)  # the functions return value

c > -273:
    print(c * 9/5 + 32)  # the functions return value
Answered By: ruohola
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.