Python新手入門之函式

2021-10-25 15:03:55 字數 1390 閱讀 2293

函式的定義

函式就是執行特定的任務和特定功能的一段**

函式的作用

復用**

隱藏實現細節

提高可維護性

提高可讀性便於除錯

函式的建立

def 函式名(

[輸入引數]

) 函式體

return *** ;

函式的引數傳遞

def

sun(a,b)

:print

('a='

,a)print

('b='

,b)return a+b

print

(sun(1,

2))

def

sun(a,b)

:print

('a='

,a)print

('b='

,b)return a+b

print

(sun(b=

1,a=2)

)

注:在函式呼叫過程中,進行引數的傳遞,如果是不可變物件,函式體的改變不會影響實參的值;如果是可變物件,函式體的改變會影響實參的值

個數可變的位置引數

def

sun(

*args)

:print

(args)

sun(1,

2,3,

4,5,

6)sun(

'h',

'o',

'l',

'l',

'o',

'w')

個數可變的關鍵字形參

def

sun(

**args)

:print

(args)

sun(a=

1,b=

2,c=

3,d=

4,e=

5,f=

6)

def

sun(

**args)

:print

(args)

defsun1

(*args)

:print

(args)l=[

1,2,

3,4]

sun1(

*l)d=

sun(

**d)

函式的返回值

python新手入門 函式

2019 5 25 魚c教程19 20課 全域性變數與區域性變數 def discounts price,rate final price price rate return final price old price float input 請輸入原價 rate float input 請輸入折扣...

Python新手入門之函式(一)

1.1 定義函式 使用關鍵字def告訴python你要定義函式,向python指出了函式名,還可能在括號內指出函式為完成其任務需要什麼樣的資訊。簡單示例如下 文件字串用三引號括起,python使用它們來生成有關程式中函式的文件。行print hello 是函式體內的唯一一行 greet user 只...

python新手入門

1.先看下python的基礎,然後去看 ng的機器學習課程,最後結合周志華的機器學習和 機器學習實戰兩本書 2.盡量不要直接呼叫工具箱,自己去實現演算法 3.先安andconda,再安ide就可以了,pycharm 4.4,測試anaconda,桌面 開始 右下角執行 ipython第乙個 執行 5...