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, ax² + 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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容