def f1(a, b, c=0, *args, **kw):
# a,b:必選引數 c:預設引數 *arg:可變引數 **kw:關鍵字引數
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
def f2(a, b, c=0, *, d, **kw):
# a,b:必選引數 c:預設引數 d:命名關鍵字引數 **kw:關鍵字引數
print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)
# 必選引數:同c/c++
# 預設引數:同c++
# 可變引數:引數個數可變,f(*arg)
# 關鍵字引數:引數個數可變且帶有關鍵字key,f(**kw)
# 命名關鍵字引數:引數個數可變且只接收確定的關鍵字,fun1(*arg,key1,key2)或fun2(*,key1,key2)
# 函式入口引數的順序:必選、預設、可變、命名關鍵字、關鍵字引數
# 注:當命名關鍵字前存在可變引數時不需要*號,如fun1
def product(*num):
if num==():
raise typeerror
# 當num為空時,引發(raise)乙個錯誤
result=1
for n in num:
result*=n
return result
# 測試
print('product(5) =', product(5))
print('product(5, 6) =', product(5, 6))
print('product(5, 6, 7) =', product(5, 6, 7))
print('product(5, 6, 7, 9) =', product(5, 6, 7, 9))
if product(5) != 5:
print('測試失敗!')
elif product(5, 6) != 30:
print('測試失敗!')
elif product(5, 6, 7) != 210:
print('測試失敗!')
elif product(5, 6, 7, 9) != 1890:
print('測試失敗!')
else:
try:
# 如果try後面出現except中提到的錯誤,
# 則執行except,以防止程式執行中斷
product()
print('測試失敗!')
except typeerror:
print('測試成功!')
python 函式入門
函式分類 是否存在返回值 有返回值的函式 使用return關鍵字返回結果 函式遇到return關鍵字,則立刻返回 無返回值的函式 是否存在引數 有參函式 引數的個數,根據情況任意 引數的型別,是任意型別 無參函式 函式定義者 系統函式 由官方定義的函式 print input type 第三方定義 ...
python入門2 函式
函式格式 def sub x,y return x y print sub 3,2 控制台輸出1 關鍵字引數,位置引數 def test x y z 10 print x,y z test 1,2,3 控制台輸出1,2,3 test 1,2 控制台輸出1,2,10 test x 1,z 3,y 2 ...
python 快速入門函式
def func print hello world return hello world a func print a hello world hello world def func args a,b,c print a,b,c func args 10,20,helloworld 10 20 ...