python 函式學習

2021-06-20 14:04:36 字數 1628 閱讀 1200

今兒再網上看了下別人總結的python 函式,功能挺強大的,c有的功能都有,下面就記些它的功能點:

1)定義,格式跟c不一樣,概念是一樣的。

def

<

函式名》

(引數列表):

<

函式語句

>

return

<

返回值》

2)函式可以命別名,很方便啊,c語言我記憶中只有指標可以。

def sum(list):

...     result=0

...     for i in list:

...             result = result+i

...     return result

sum1 = sum #定義乙個別名 sum1

l = [1,2,3]

sum1(l) #結果為 6

3)預設引數,這個跟c是一樣的,預設引數必須放在最後

def

sum(a,

b=1):

#b為預設引數

returna+

bsum(1,2)

#3sum(1)

#2

4)關鍵引數,一般引數都是位置來解析,這個為了破壞這個規則來設定的,規定指定的引數是什麼值,他媽的有點逆天,c沒有這個功能。

def

sum(a=0,

b=0):

returna+

bsum()

# 0 + 0

sum(a=1)

# 1 + 0

sum(b=1)

# 0 + 1

sum(a=1,

b=2)

# 1 + 2

sum(b=1,

a=2)

# 2 + 1

5)可變長引數,這個跟c語言很像,有點不同是c語言跟變長引數,都會跟乙個整形的引數,表示變長的個數。

*seq 序列位置引數,接收乙個元組

>>>

deftest(*seq):

...print

seq...

>>>

test(1,2,3,4)

(1,2,

3,4)

>>>

test(*[1,2,3])

(1,2,

3)

**dic 關鍵引數,接收乙個字段

>>>

deftest2(**dic):

...print

dic...

>>>

test2(a=1,b=2)

>>>

test2(**)

6)特殊的輕型函式 lambda

語法:

#lambda 引數列表:表示式

lambda

arg1,arg2,…argn:

expression

using

args

例如:

>>>

result

=lambda

x:x**2

>>>

result(3)

9

Python函式學習

def hello name return hello,name print hello holly defhello name print hello,name hello holly 輸出結果為hello,holly!稍微複雜一點的例子有 求長方體的體積 def volume length,wi...

Python函式學習

1 def 語句和引數 def hello name print hello name hello alice hello bob 如果執行這個程式,輸出看起來像這樣 hello alice hello bob 在這個程式的 hello 函式定義中,有乙個名為 name 的變元 變元 是乙個 變數,...

Python函式學習

1.簡化 2,呼叫方便,修改方便 3.呼叫引數,形引數,與位置引數。關鍵引數,位置引數只能發在關鍵引數之後 4.預設引數 5.引數組 args 元組引數 6 接受字典 kwargs 當同時使用時必須放到引數的最後 程式執行的從檔案的上邊到下邊的執行 乙個變數只在函式中生效。外部訪問不到 在檔案頂層宣...