python中的函式

2021-10-01 09:22:39 字數 2496 閱讀 9103

函式的定義,呼叫,巢狀

# 如何定義乙個函式

def hello(

): print(

'hello'

) print(

'python'

)# 通過函式名來呼叫函式

hello(

)#函式裡面巢狀函式

def westos(

): print(

'is westos'

) def python(

): print(

'is python'

) python(

)westos(

)#執行結果

hello

python

is westos

is python

函式中的引數

引數:形參 實參

形參:位置引數 預設引數 可變引數 關鍵字引數

# 位置引數:形參和實參數量必須保持一致

def getinfo(name,age): # 按照位置傳遞引數

print(name,age)

getinfo(

'westos',11)

getinfo(11,'westos'

)getinfo(age=11,name=

'westos'

)# 預設引數

def mypow(x,y=2):

print(x**y)

mypow(2,3)

mypow(2)

# 可變引數

def mysum(*args):

print(*args)

print(args)

sum= 0

for item in args:

sum += item

print(sum)

nums =

[1,2,3,4]

nums1 =

(1,2,3,4)

nums2 =

mysum(1,2,3,4,5)

# 引數解包 在引數名前加*

mysum(*nums)

mysum(*nums2)

# 關鍵字引數

# **kwargs是乙個字典 可以傳遞任意多個key-value

def getstuinfo(name,age,**kwargs):

print(name)

print(age)

print(kwargs)

d = dict(a=1,b=2)

# 如果要對字典進行解包 乙個* 獲取所有的key值

print(*d)

getstuinfo(

'westos',11,***=1,score=100)

#執行結果

westos 11

11 westos

westos 1184

1 2 3 4 5

(1, 2, 3, 4, 5)

151 2 3 4

(1, 2, 3, 4)

101 2 3 4

(1, 2, 3, 4)

10a b

westos

11

函式的返回值

""

"返回值:函式執行的結果 還需進一步操作 就給函式乙個返回值

return用來返回函式的執行結果,如果函式沒有返回值 預設返回none

一旦遇到return函式執行結束 後面的**不會執行

多個返回值的時候哦,python會幫助我們封裝成乙個元組型別"""

def mypow(x,y=2):

#print(x**y)

return x**y,x+y,x-y

print(

'hello'

)print(mypow(4))

a = mypow(3)

print(a)

#執行結果

(16, 6, 2)

(9, 5, 1)

宣告變數

""

"區域性變數:在函式內部定義的變數 只在函式內部起作用 函式

執行結束後 變數會自動刪除"""

a = 1

print(

'outside:',id(a))

def fun(

): global a #宣告a為全域性變數

a = 5

print(

'inside:',id(a))

fun(

)print(a)

print(id(a))

#執行結果

outside: 9322464

inside: 9322592

59322592

python函式實驗 Python中的函式

一 定義 1 def函式名 引數 2 3 4 函式體5 6 返回值 函式的定義主要有如下要點 def 表示函式的關鍵字 函式名 函式的名稱,日後根據函式名呼叫函式,用引號標記即可 函式體 函式中進行一系列的邏輯計算,如 傳送郵件 計算出 11,22,38,888,2 中的最大數等.引數 為函式體提供...

python中的lo函式 Python 函式

函式 內建函式 print input len type print hello world 函式 引數 定義函式 def greet name print name 早上好 return 第一行def的意思是定義 define greet是 函式名 自己取的 再搭配乙個括號和冒號,括號裡面的nam...

Python中的函式

你可以定義乙個由自己想要功能的函式,以下是簡單的規則 任何傳入引數和自變數必須放在圓括號中間。圓括號之間可以用於定義引數。函式的第一行語句可以選擇性地使用文件字串 用於存放函式說明。函式內容以冒號起始,並且縮排。return expression 結束函 數,選擇性地返回乙個值給呼叫方。不帶表示式的...