1、Python中的“函数”也是大体上分为“内置函数”和“自定义函数”。
2、“内置函数”请直接在向对应的位置调用即可。
3、“自定义函数”则使用固定的语句“def function_name(parameter_name)”来定义。
4、“自定义函数”的参数,有“必选参数”、“默认参数”、“可变参数”、“命名关键字参数”、“关键字参数”。此顺序也为设置参数时的顺序。
5、“必选参数”可以是“位置参数”、“可变参数”、“命名关键字参数”、“关键字参数”,但是设置参数时的顺序需要注意。
6、“可变参数”,可以依据不同的方式进行调用。传入多个“不可变对象”或者是传入“list”、“tuple”。可以近似理解为“数组”。
7、“关键字参数”,简单来说就是传入多个“key-value”或者“dict”。必须要一对一的事物。
8、“命名关键字参数”,是为了解决“关键字参数”传入“key”不固定的做法。对固定的“key”传入“value”。
9、“pass”作为暂定,用于未完成的“自定义函数”中。
10、“命名关键字参数”的前面已经有“可变参数”,就不再需要单独的“*”做分隔了。
11、“func(*args, **kw)”调法:对于一个任意函数,都可以通过类似“func(*args, **kw)”的方式调用。
12、“递归函数”的用法可以直接套用。
13、“尾递归”则是一种防止递归调用函数而发生栈溢出的方法。
print("abs(-10) = %d" % (abs(-10)))
def my_function():
pass
def my_abs(x):
if not isinstance(x, (int, float)):
raise TypeError("参数类型不是int或float")
else:
if x < 0:
x = -x
return x
print("my_abs(-2020) = %d" % (my_abs(-2020)))
print("my_abs(-1.1) = %.1f" % (my_abs(-1.1)))
def Print_Function_One(a, b, c=0, *d, **e):
print("a = %s, b = %s, c = %s, d = %s, e = %s" % (a, b, c, d, e))
print("type(d) = %s" % (type(d)))
print("type(e) = %s" % (type(e)))
def Print_Function_Two(a, b, c=0, *d, e):
print("a = %s, b = %s, c = %s, d = %s, e = %s" % (a, b, c, d, e))
print("type(d) = %s" % (type(d)))
print("type(e) = %s" % (type(e)))
def Print_Function_Two_Change(a, b, c=0, *, d, e):
print("a = %s, b = %s, c = %s, d = %s, e = %s" % (a, b, c, d, e))
print("type(d) = %s" % (type(d)))
print("type(e) = %s" % (type(e)))
def Print_Function_Three(a, b, c=0, *, d, **e):
print("a = %s, b = %s, c = %s, d = %s, e = %s" % (a, b, c, d, e))
print("type(d) = %s" % (type(d)))
print("type(e) = %s" % (type(e)))
Print_Function_One(1, 2, 3, 4, 5, 6, 7, 8, key_word='9')
print("")
Print_Function_Two(1, 2, 3, 4, 5, 6, 7, 8, e="9")
print("")
Print_Function_Three(1, 2, 3, d=4, key_e=5)
def Changeable_Parameter_Function(*number):
print("number = %s" % (number,))
print("type(number) = %s" % (type(number)))
Changeable_Parameter_Function(1, 2, 3, 4, 5)
print("")
list_name = [6, 7, 8, 9, 10]
print("list_name.Changeable_Parameter_Function")
Changeable_Parameter_Function(*list_name)
print("")
tuple_name = (1, 3, 5, 7, 9)
print("tuple_name.Changeable_Parameter_Function")
Changeable_Parameter_Function(*tuple_name)
print("")
args = (1, 2, 3)
kw = {"d": 8, "e": 9}
Print_Function_One(*args, **kw)
Print_Function_Two_Change(*args, **kw)
Print_Function_Three(*args, **kw)
def Recursive_Function(n):
if n == 1:
return 1
return n * Recursive_Function(n - 1)
print("Recursive_Function(3) = %d" % (Recursive_Function(3)))
def Rec_Func(n):
return Rec_Func_Iter(n, 1)
def Rec_Func_Iter(number, product):
if number == 1:
return product
return Rec_Func_Iter(number - 1, number * product)
print("Re_Func(3) = %d" % (Rec_Func(3)))