Python?return函數返回值類型和幫助函數使用教程
引言
經過函數學習之后我們會發(fā)現函數不被調用是不會直接執(zhí)行的,我們在之前的函數調用之后發(fā)現運行的結果都是函數體內print()打印出來的結果,但是有時候為了方便函數參與二次運算,我們讓函數體內不輸出任何結果,而是把函數本身就當做一種結果,輸出這種結果的方式就可以理解為返回函數的結果,python用return關鍵詞來返回。下面我們對比幾種不同的函數調用結果。
一、函數的輸出方式對比
1.直接使用print打印函數運行結果:直接調用函數名傳參即可。
def func1(a, b):
res = a + b
print(res)
func1(4, 9)
返回結果:132.打印沒有返回值,沒有輸出代碼塊的函數,需要把函數當做一個變量來用print輸出。
def func2(a, b):
res = a + b
print(func2(4, 9))
返回結果:None3.打印有返回值(return)的函數,同上,也是把函數當做一個變量來輸出。
def func3(a, b):
res = a + b
return res
# print(a) # return后面的代碼不會被執(zhí)行
print(func3(4, 9))
返回結果:13對比上面三種形式的函數,如果我們想用函數的結果來做運算的話,第一種情況就無法實現,比如
func1(4, 9) * 3 返回結果: TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
第二種情況本身就是None,所以忽略,第三種情況我們再試試
print(func3(4, 9) * 3) 返回結果:39
從上面的結果可以看出,有返回值的函數用起來很方便,直接可以當做變量來使用。
二、return的作用
同時return還有結束函數代碼塊的功能,return之后的下一行語句不會被執(zhí)行。
注意:有返回值的函數一般直接調用函數名是不執(zhí)行任何結果的,賦值給變量后才會返回結果。如果一個函數沒有return語句,其實它有一個隱含的語句,返回值是None,類型也是'None Type'。print是打印在控制臺,而return則是將后面的部分作為返回值。”
下面再來看看return的一些特別之處。
1.可以return多個結果
def func3(a, b):
res1 = a + b
res2 = a - b
return res1, res2
print(func3(4, 9))
返回結果:13? -52.一個函數可以有多個return,但是只會執(zhí)行第一個
def func3(a, b):
res1 = a + b
res2 = a - b
return res1
return res2
print(func3(4, 9))
返回結果:133.沒有return的函數返回NoneType
def func3(a, b):
res1 = a + b
res2 = a - b
print(type(func2(4, 9)))
返回結果:<class 'NoneType'>三、幫助函數
這里屬于一個補充知識點,我們在函數使用的時候不知道傳參和函數的其他用法的時候可以使用help()函數來輸出開發(fā)文檔中的文本提示。
help(print)import os #文件目錄操作模塊
os.mkdir('123')
help(os.mkdir)返回結果:
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
Help on built-in function mkdir in module nt:
mkdir(path, mode=511, *, dir_fd=None)
Create a directory.If dir_fd is not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that directory.
dir_fd may not be implemented on your platform.
If it is unavailable, using it will raise a NotImplementedError.The mode argument is ignored on Windows.
以上是關于Python函數返回值類型和幫助函數的講解,更多關于Python return幫助函數的資料請關注腳本之家其它相關文章!
相關文章
pytest使用@pytest.mark.parametrize()實現參數化的示例代碼
這篇文章主要介紹了pytest使用@pytest.mark.parametrize()實現參數化,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-07-07

