內建函數
Python有很多內建的函數,具體可查看官方文檔:
Python內建函數官方文檔連結
也可以在命令列,使用help(函數名)來查看使用方法:
>>> help(max)Help on built-in function max in module builtins:max(...) max(iterable, *[, default=obj, key=func]) -> value max(arg1, arg2, *args, *[, key=func]) -> value With a single iterable argument, return its biggest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the largest argument.
自訂函數
Python的自訂函數的文法是:
def 函數名(參數名,多個參數用逗號隔開): 函數體
使用return語句返回函數的結果,沒有return語句的函數,預設返回None:
>>> def fun_1():... return 'test1'...>>> fun_1()'test1'
>>> def fun_2(x):... x = 12...>>> fun_2(3)>>>
使用pass表示空語句,此語句不做任何事情,主要用於佔位:
>>> def fun_3():... if 2 > 1:... pass... else:... print('error')...>>> fun_3()>>>
函數的傳回值
Python函數的傳回值既可以返回單個值,也可以返回多個值:
>>> def fun_4(a, b):... return a, b...>>> fun_4(123, 321)(123, 321)>>> r = fun_4(123,321)>>> r[0]123>>> r[1]321
注意,返回多個值的時候,實際上返回的是個tuple。另外,還可以這樣接收傳回值:
>>> x, y = fun_4(123, 321)>>> x123>>> y321>>>