Introduction
- Why use
printin python function will sometimes outputNone? - What are the differences between
printandreturn?
To answer my questions above, did a bit googling.
Please feel free to let me know if any of my understandings below are incorrect. Thanks.
The image below answers the question.
If use print, cannot assign it to a variable nor reuse it afterward.print is just used to display a value on screen.
Image from ITVoyagers
Fruitful function (use return, will return values)
- The function which return any value (gives result or return values after execution).
- Can assign it to a variable to hold the return value
Void function (does not return any values)
- The function which does not return any value. Some functions gets executed but doesn’t return any value.
- You can display a value on screen (using
print) but cannot return a value (will returnNone). - cannot assign it to a variable
- A void function may or may not have return statement, if void function has return statement then it is written without any expression.
e.g.
pythondef FunctionName():
print("lalalalala")
return
中文解釋
以下為CSDN博主「crascopy」的原創文章,遵循CC 4.0 BY-SA版權協議,現引用部份內容作個人記錄。
原文鏈接:https://blog.csdn.net/weixin_31222401/article/details/112889641以下部分內容也引用自 好程序员Python培训分享print和return的作用及区别_腾讯新闻
print()
print()函數的作用是輸出數據到控制台,就是打印在你能看到的界面上。
print不會以任何方式影響函數。它對於理解程序如何工作非常有用,並且可以在調試中用於檢查程序中的各種值而不會中斷程序。除了幫助人類看到人們想要看到的結果,print其餘的事情都不做。
return
return作為腳本單獨運行時則需要print函數才能顯示,但是在交互模式下,return的結果會自動打印出來。
不帶參數值的return語句返回None。
return是函數返回值的主要方式。所有函數都將返回一個值,如果沒有return語句,它將返回None。函數返回的值可以作為參數進一步傳遞給另一個函數、存儲為變量,或者只是為了人類用戶的使用而打印。 return旨在立即中斷控制流並退出當前函數,將指定值返回給調用函數的調用者。
Reference
- Easy Fruitful & Void Function,return Values,stack Diagrams-3 - ITVoyagers
- python中的return和print的区别_Python 中print 和return 的区别_crascopy的博客-CSDN博客
- 对python中return和print的一些理解_python_脚本之家
- 好程序员Python培训分享print和return的作用及区别_腾讯新闻

