简体   繁体   English

Python-打印功能输出

[英]Python - print function output

def cent_to_fahr(cent):
    print (cent / 5.0 * 9 + 32)

print (cent_to_fahr(20))

The output is this : 输出是这样的:

68.0
None

Why this output has None ? 为什么此输出None

I didn't get this result when I use just cent_to_fahr(20) . 当我只使用cent_to_fahr(20)时,我没有得到这个结果。 Can I ask why it happens ? 请问为什么会这样?

def cent_to_fahr(cent):
    return (cent / 5.0 * 9 + 32)

print (cent_to_fahr(20))

a function needs to return a value to have an output other then None 一个函数需要return一个值以具有除None的输出

To put it into context, let's try understand what causes each line of output you received: 为了将其放在上下文中,让我们尝试了解是什么原因导致您收到的每一行输出:

  • 68.0 is printed thanks to the contents of your function. 由于功能的内容 ,打印了68.0 This could be seen as the "end" of that computation's "life", that value/result is no longer available for further computations. 这可以看作是该计算“寿命”的“终点”,该值/结果不再可用于进一步的计算。
  • None is what the function returns , and in this case is also quite useless. 函数返回的值 None是,在这种情况下也完全没有用。

Now that we understand that better, I would recommend adjusting the function to return the value computed. 现在我们更好地了解了,我建议调整函数以返回计算出的值。

def cent_to_fahr(cent):
    return (cent / 5.0 * 9 + 32)

That way when the function is called (in context of further functions) it will return a value that that can be further processed (in this case with print() ): 这样,当调用该函数时(在其他函数的上下文中),它将返回一个可以进一步处理的值(在这种情况下,使用print() ):

>>>print(cent_to_fahr(20))

Which will print 68.0 . 它将打印68.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM