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