function

Function definition and call

# a,b; Parameter; Def caladd(a, b): c = a + b return c # a=5,b=5; Positional argument; Res = caladd(5, 5) print(res) # a=5,b=10; Keyword arguments; Res = caladd(b=10, a=5) print(res)Copy the code

Function parameter passing

Def fun(arg1, arg2): print(arg1, arg2) # 10 [1, 2, 3] arg1 = 100 arg2.append(10) # 100 [1, 2, 3, 10] print(arg1, arg2) return n1 = 10 n2 = [1, 2, 3] print(n1, n2) # 10 [1, 2, 3] fun(n1, n2) print(n1, n2) # 10 [1, 2, 3, 10] "" When a function is called, changes in the body of the function do not affect the value of the argument if the object is immutable.Copy the code

Function return value

Def fun1(a, b): def fun2(a, b): def fun2(a, b): def fun2(a, b): def fun1(a, b): def fun2(a, b): def fun2(a, b): return a * a, b * b print(fun1(10, 10)) # 20 print(fun2(10, 10)) # (100, 100)Copy the code

The parameter definition of a function

Def fun(a, b=10): return a, b print(fun(5)) # (5, 10) print(fun(6)) # (6, 6) # def fun2(*args): Print (args) # (1, 2, 3) for arg in args: print(arg) fun2(1, 2, 3) def fun3(**args): Print (args) # {'a': 10, 'b': 20, 'c': 30} for arg in args: Def fun4(*arg1, **agr2): pass def fun4(*arg1, **agr2): pass def fun4(*arg1, **agr2): pass def fun4(*arg1, **agr2): passCopy the code

Summary of parameter usage

Def fun(a, b, c): Print (a, b, c) # position parameter arguments fun (1, 2, 3) # will be in the list each element into position argument list1 = [10, 20, 30] fun (* list1) # keyword arguments argument fun (a = 4, b = 5, Dict1 = {"a": 7, "b": 8, "c": 9} fun(**dict1) # dict1 = {"a": 7, "b": 8, "c": 9} Def fun2(a, b, *, c, d): print(a, b, c, d) fun2(1, 2, c=3, d=4) #Copy the code

Variable scope

Def fun2(): def fun2(): def fun2(): def fun2(): Def fun3(): print(name) fun2() def fun3(): Print (age) fun3() print(age) fun3() print(age) fun3() Otherwise: NameError: name 'age' is not defined print(age)Copy the code