def print_string(str): print(str) return
print_string()
>>> def print_string(str):
... print(str)
... return
>>> print_string()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
print_string()
TypeError: print_string() missing 1 required positional argument: 'str'
def Calc_Area(width, height): return width * height print(Calc_Area(height=4, width=3))上述程式碼的執行結果如下所示:
>>> def Calc_Area(width, height):
... return width * height
>>> print(Calc_Area(height=4, width=3))
12
def Calc_Area(width, height = 5): return width * height print(Calc_Area(3))上述程式碼的執行結果如下所示:
>>> def Calc_Area(width, height = 5):
... return width * height
>>> print(Calc_Area(3))
15
*
,以元組型別匯入,用來存放所有未命名的變數引數。例如:
def Multi_Add(arg1, *args): sum = 0 for var in args: sum += var return arg1 + sum print(Multi_Add(1, 2, 3 , 4))Multi_Add( ) 函數的作用是將輸入的引數相加,上述程式碼的執行結果如下所示:
>>> def Multi_Add(arg1, *args):
... sum = 0
... for var in args:
sum += var
... return arg1 + sum
>>> print(Multi_Add(1, 2, 3 , 4))
10
>>> print(Multi_Add(1, 2, 3 , 4, 5, 6))
21
**
,以字典型別匯入,用來存放所有命名的變數引數,例如:
def fun(**kwargs): for key, value in kwargs.items(): print("{0} 喜歡 {1}" . format (key, value)) fun (我="貓", 貓="盒子")上述程式碼的執行結果如下所示:
>>> def fun(**kwargs):
... for key, value in kwargs.items():
... print("{0} 喜歡 {1}" . format (key, value))
>>> fun (我="貓", 貓="盒子")
我 喜歡 貓
貓 喜歡 盒子
def changeVar(a): a = 1 b = 2 changeVar(b) print(b)上述程式碼的執行結果如下所示:
>>> def changeVar(a):
... a = 1
>>> b = 2
>>> changeVar(b)
>>> print(b)
2
def changeVar2(l): l.append([3, 4]) print ("函數內取值:", l) return l = [1, 2] changeVar2(l) print ("函數外取值:", l)上述程式碼的執行結果如下所示:
>>> def changeVar2(l):
... l.append([3, 4])
... print ("函數內取值:", l)
... return
>>> l = [1, 2]
>>> changeVar2(l)
函數內取值: [1, 2, [3, 4]]
>>> print ("函數外取值:", l)