2

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.

ruohola
  • 21,987
  • 6
  • 62
  • 97
Praguru 14
  • 131
  • 1
  • 5

2 Answers2

2

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.

glglgl
  • 89,107
  • 13
  • 149
  • 217
Jack
  • 44
  • 4
2

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
ruohola
  • 21,987
  • 6
  • 62
  • 97