Function

In this article, just introducing the basic knowledge of function, for more information, please check Python--Middle.

Function (Method)

In general, Function also is called Method in sometimes. It is the smallest algorithm logic unit. In short, Function is like a black box, the only thing you need to do for using it is passing in the inputs with the correct signature, and it can return the result which you expected. When you are programming, you'd better separate your logic into different pieces, then it will be tested easier.

Calling function
If the function you are calling is a built-in function, then you can directly use it. But if the function is coming from a third package. Then you need to import the package, and calling it directly. If the function is coming from the third package and you have imported it, the name of function also same to the built-in function, you need to explicitly give the prefix for the third party function.
example

//Code==========
#abs function
print(abs(100))
#int function
print(int('123'))
print(int(12.34))
#str function
print(str(123))
//Result==========
100
123
12
123

Define a function
It doesn't like other oop languages when you want to define a function in Python, you need to explicitly have a keyword def, then the name of the function and the parameters follow up. Next line will be the body of the function. For the return value, if there is None to return, you can write return and no value follows up.
example

//Code==========
def square_of_sum(L):
    sum = 0
    for item in L:
        sum += item*item
    return sum
print (square_of_sum([1, 2, 3, 4, 5]))
print (square_of_sum([-5, 0, 5, 15, 25]))
//Result==========
55
900

Multi-return-value
Actually Python only can return a single value, but how it returned multiple values? The answer is tuple, it combimes all values together into a tuple.
Let's have an example, says there is a person who wants to walk from a point to another point. Given start point coordinate, steps, and angle [input]. You need to calculate the coordinate of the end point [output]. (math package provided sin and cos functions, so that you can directly use them after imported the package)

//Code==========
import math
def move(x, y, step, angle):
    nx = x + step * math.cos(angle)
    ny = y - step * math.sin(angle)
    return nx, ny
x, y = move(100, 100, 60, math.pi / 6)
print(x, y)
//Result==========
151.96152422706632 70.0

example(calculate a binary linear equation, ax2 + bx + c = 0)

//Code==========
import math
def quadratic_equation(a, b, c):
    return ((-b)+math.sqrt(b*b-4*a*c))/(2*a), ((-b)-math.sqrt(b*b-4*a*c))/(2*a)
print (quadratic_equation(2, 3, 0))
print (quadratic_equation(1, -6, 5))
//Result==========
(0.0, -1.5)
(5.0, 1.0)

Recursive Function (It's my pain..)
In short, it is a function by using itself until there is a break condition be triggered. For example, n!, it is equals n! = 1 * 2 * 3 * ... * (n-1) * n, and finally fact(n) = fact(n-1) * n when n == 1, it will be break.

def fact(n):
    if n==1:
        return 1
    return n * fact(n - 1)

if we pass n = 5, then

===> fact(5)
===> 5 * fact(4)
===> 5 * (4 * fact(3))
===> 5 * (4 * (3 * fact(2)))
===> 5 * (4 * (3 * (2 * fact(1))))
===> 5 * (4 * (3 * (2 * 1)))
===> 5 * (4 * (3 * 2))
===> 5 * (4 * 6)
===> 5 * 24
===> 120

example(Hanno Tower Game)

Hanno Tower (5-layer)

//Code==========
def move(n, a, b, c):
    if n==1:
        print (a,'-->',c) 
    else:
        move(n-1, a, c, b)
        print (a, '-->', c, ',')
        move(n-1, b, a, c)
move(4, 'A', 'B', 'C')
//Result==========
A --> B, A --> C, B --> C, A --> B, C --> A, C --> B, A --> B,
A --> C, B --> C, B --> A, C --> A, B --> C, A --> B, A --> C,
B --> C

Function's parameter with default value
Sometimes, people using function with optional parameter, but in your function body still need this parameter to join the calculation, at this time, you can have a default value for the parameter, and no matter pass in or not, make sure that the parameter still has value.
example

//Code==========
def greet(string='world'):
    print ('hello,', string)
greet()
greet('Bart')
//Result==========
hello, world
hello, Bart

The amount of parameters are dynamic
This is more flexable for using it. you can pass 0 or more than 1 parameters when you using this method. Python combines all parameters as a tuple, so that when you define your function, you can think the collection actually is a tuple.
example(calculate average)

//Code==========
def average(*args):
    sum = 0.0
    if len(args) == 0:
        return 0.0
    else: 
        for item in args:
            sum += item
        return sum/len(args)
print (average())
print (average(1, 2))
print (average(1, 2, 2, 3, 4))
//Result==========
0.0
1.5
2.4
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末谜嫉,一起剝皮案震驚了整個濱河市赴穗,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,372評論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡船庇,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評論 3 392
  • 文/潘曉璐 我一進店門侣监,熙熙樓的掌柜王于貴愁眉苦臉地迎上來鸭轮,“玉大人,你說我怎么就攤上這事橄霉∏砸” “怎么了?”我有些...
    開封第一講書人閱讀 162,415評論 0 353
  • 文/不壞的土叔 我叫張陵姓蜂,是天一觀的道長按厘。 經(jīng)常有香客問我,道長钱慢,這世上最難降的妖魔是什么逮京? 我笑而不...
    開封第一講書人閱讀 58,157評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮束莫,結果婚禮上造虏,老公的妹妹穿的比我還像新娘。我一直安慰自己麦箍,他們只是感情好,可當我...
    茶點故事閱讀 67,171評論 6 388
  • 文/花漫 我一把揭開白布陶珠。 她就那樣靜靜地躺著挟裂,像睡著了一般。 火紅的嫁衣襯著肌膚如雪揍诽。 梳的紋絲不亂的頭發(fā)上诀蓉,一...
    開封第一講書人閱讀 51,125評論 1 297
  • 那天栗竖,我揣著相機與錄音,去河邊找鬼渠啤。 笑死狐肢,一個胖子當著我的面吹牛,可吹牛的內容都是我干的沥曹。 我是一名探鬼主播份名,決...
    沈念sama閱讀 40,028評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼妓美!你這毒婦竟也來了僵腺?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 38,887評論 0 274
  • 序言:老撾萬榮一對情侶失蹤壶栋,失蹤者是張志新(化名)和其女友劉穎辰如,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體贵试,經(jīng)...
    沈念sama閱讀 45,310評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡琉兜,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,533評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了毙玻。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片豌蟋。...
    茶點故事閱讀 39,690評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖淆珊,靈堂內的尸體忽然破棺而出夺饲,到底是詐尸還是另有隱情,我是刑警寧澤施符,帶...
    沈念sama閱讀 35,411評論 5 343
  • 正文 年R本政府宣布往声,位于F島的核電站,受9級特大地震影響戳吝,放射性物質發(fā)生泄漏浩销。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,004評論 3 325
  • 文/蒙蒙 一听哭、第九天 我趴在偏房一處隱蔽的房頂上張望慢洋。 院中可真熱鬧,春花似錦陆盘、人聲如沸普筹。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽太防。三九已至,卻和暖如春酸员,著一層夾襖步出監(jiān)牢的瞬間蜒车,已是汗流浹背讳嘱。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評論 1 268
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留酿愧,地道東北人沥潭。 一個月前我還...
    沈念sama閱讀 47,693評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像嬉挡,于是被迫代替她去往敵國和親钝鸽。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,577評論 2 353

推薦閱讀更多精彩內容