简体   繁体   中英

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 ?

I didn't get this result when I use just 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

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

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(cent_to_fahr(20))

Which will print 68.0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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