python中return和print的区别(详细)

huskiesir最近在研究python哈,今天纠结一个问题,那就是return和print的区别,都是可以输出结果的,到底有啥区别呀?二话不多说,看下面的例子。

#代码1:
def break_words(stuff):
    """This function will break up words for us. """
    words = stuff.split(' ') 
    return words # 输入的字符串,输出生成切片后的列表

sentence = "All good things come to those who wait."

break_words(sentence)
#代码2:
def break_words(stuff):
    """This function will break up words for us. """
    words = stuff.split(' ')
    print(words) # 打印生成切片后的列表

sentence = "All good things come to those who wait."

break_words(sentence)

到这里,你不用读懂我的代码什么意思,我只要告诉你我在我的函数中进行了计算出某些东西,然后想把它打印出来而已。好的,接下来看执行的结果:

#代码1:
这里什么也没有输出
#代码2:
['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']

ok,以下是我总结的东西,你可以看一下,希望对你有帮助:

# return 和 print的区别:
# 在执行函数的时候return无法打印出值,return返回的结果只能用于给变量赋值。而pirnt则可以直接打印。
# return还有一个重要特性:在函数中,凡是遇到return,这个函数就会结束,这里要特别注意。针对无限循环的函数,可以使用return

 

posted @ 2019-02-14 18:40  huskiesir  阅读(9760)  评论(1编辑  收藏  举报