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.
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.
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
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.
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.
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