[Python] Learn the function and usage of Python common functions

1. Function

​ The function is to package the program and encapsulate it into a package, which can be called directly when used

1. Create a function and call a function:
>>> def test():
	pass

>>> test()
>>> def test():
	for i in range(3):
		print("I love curry")

		
调用函数
>>> test
<function test at 0x000001B617CCF3A0>
>>> test()
I love curry
I love curry
I love curry
2. Create a parameter passing function
>>> def test(times,name):
	for i in range(times):
		print(f"I love {
      
      name}")

		
>>> test(5,"Python")
I love Python
I love Python
I love Python
I love Python
I love Python
3. The return value of the function

​ return: Return the value directly, ignoring all the following codes

>>> def test(x,y):
	return x/y

>>> test(4,2)
2.0
>>> def test(x,y):
	if y == 0:
		return "不能为0"
	return x/y

>>> test(10,2)
5.0
4. Positional parameters

There are two key names in using the parameter passing function:

Formal parameters (formal parameters): When creating a function, the reserved variable names are called formal parameters

​ Actual parameters (actual parameters): When calling a function, the parameters given are called actual parameters

>>> def test(a,b,c):
	return "".join((c,b,a))

位置参数传参
>>> test("我","爱","你")
'你爱我'

关键参数传参
>>> test(c="我",b="爱",a="你")
'我爱你'

​ Default parameters:

>>> def test(a,b,c="她"):
	return "".join((c,b,a))

>>> test("我","爱")
'她爱我'
5. Cold knowledge
>>> help(sum)
Help on built-in function sum in module builtins:

sum(iterable, /, start=0)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers
    
    When the iterable is empty, return the start value.
    This function is intended specifically for use with numeric values and may
    reject non-numeric types.

​ As you can see, there is a / backslash in the usage format, which means that keyword parameters are not allowed before it, only positional parameters can be used

​ The same is true in functions, but we can use * asterisks instead, so that the first digit can be a positional parameter or a key parameter, but the latter must be keyword parameters

>>> def test(a,*,b,c):
	return "".join((c,b,a))
>>> test(a="我",b="爱",c="她")
'她爱我'
>>> test("我",b="爱",c="她")
'她爱我'
>>> test("我","爱","她")
Traceback (most recent call last):
  File "<pyshell#181>", line 1, in <module>
    test("我","爱","她")
TypeError: test() takes 1 positional argument but 3 were given
6. Multi-parameters

​ Passing in multiple parameters is packaged in the form of tuples, just add an * star in front of the variable name

​ The second understanding: pass in a variable of tuple type and put multiple values ​​into a tuple

>>> def test(*args):
	print(f"一共多少个参数{
      
      len(args)}")
	print(f"第2个参数是什么:{
      
      args[1]}")

	
>>> test(1,2,3,4,5)
一共多少个参数52个参数是什么:2

​ If multi-parameter assignment is used, other variables must be assigned using keyword parameters

>>> def test(*args,a,b):
	print(args,a,b)

	
>>> test(1,2,3,4,5,a=6,b=7)
(1, 2, 3, 4, 5) 6 7
dictionary function

​ When declaring a function, you can also declare a variable of dictionary type to store data

>>> def test(**args):
	print(args)

	
>>> test(a=1,b=2,c=3)
{
    
    'a': 1, 'b': 2, 'c': 3}
>>> def test(a,*b,**args):
	print(a,b,args)

>>> test(1,2,3,4,5,d=1,b=2,c=3)
1 (2, 3, 4, 5) {
    
    'd': 1, 'b': 2, 'c': 3}
Unpack parameters

​ Unpacking of tuples

>>> args=(1,2,3,4)
>>> def test(a,b,c,d):
	print(a,b,c,d)
	
>>> test(*args)
1 2 3 4

​ Dictionary unpacking

>>> args={
    
    'a':1,'b':2,'c':3,'d':4}
>>> test(**args)
1 2 3 4
7. Scope
1. Local scope
>>> def test():
	x=520
	return x

>>> test()
520
>>> print (x)
Traceback (most recent call last):
  File "<pyshell#266>", line 1, in <module>
    print (x)
NameError: name 'x' is not defined
2. Global scope
>>> x = 888
>>> def test():
	return x

>>> test()
888

​ If the name of the local variable in the function is the same as that of the global variable, the local variable will replace the global variable and is limited to use in the current function

>>> x = 888
>>> def test():
	return x

>>> test()
888
>>> def test():
	x = 666
	return x

>>> test()
666
3.global statement

​ Use global to declare variables as global variables

>>> x = 888
>>> def test():
	global x
	x = 520
	return x

>>> x
888
>>> test()
520
>>> x
520
4. Nested functions
>>> def funA():
	x = 520
	def funB():
		x = 666
		print (f"FunB:{
      
      x}")
	funB()
	return f"funA:{
      
      x}"

>>> funA()
FunB:666
'funA:520'
5. nonlocal statement

Function: Variables can be declared as external variables

>>> def funA():
	x = 520
	def funB():
		nonlocal x
		x = 666
		print (f"FunB:{
      
      x}")
	funB()
	return f"funA:{
      
      x}"

>>> funA()
FunB:666
'funA:666'
6. LEGB rules

L: local (local scope) E: enclosed (outer function scope of nested functions) G: global (global scope) B: build-ln (built-in function yu)

​ When a local variable is the same as a global variable, this local variable will replace the global variable to be called and used

>>> str(123)
'123'
>>> str="123"
>>> str(123)
Traceback (most recent call last):
  File "<pyshell#313>", line 1, in <module>
    str(123)
TypeError: 'str' object is not callable
>>> del str
>>> str(123)
'123'

​ Note: In order to avoid this from happening, try not to conflict with the built-in function names in python when declaring variables
1,2,3,4,5,a=6,b=7)
(1, 2, 3 , 4, 5) 6 7


###### 	字典函数

​		在声明一个函数中,可以同时声明一个字典类型的变量来存储数据

```py
>>> def test(**args):
	print(args)

	
>>> test(a=1,b=2,c=3)
{'a': 1, 'b': 2, 'c': 3}
>>> def test(a,*b,**args):
	print(a,b,args)

>>> test(1,2,3,4,5,d=1,b=2,c=3)
1 (2, 3, 4, 5) {
    
    'd': 1, 'b': 2, 'c': 3}
Unpack parameters

​ Unpacking of tuples

>>> args=(1,2,3,4)
>>> def test(a,b,c,d):
	print(a,b,c,d)
	
>>> test(*args)
1 2 3 4

​ Dictionary unpacking

>>> args={
    
    'a':1,'b':2,'c':3,'d':4}
>>> test(**args)
1 2 3 4
7. Scope
1. Local scope
>>> def test():
	x=520
	return x

>>> test()
520
>>> print (x)
Traceback (most recent call last):
  File "<pyshell#266>", line 1, in <module>
    print (x)
NameError: name 'x' is not defined
2. Global scope
>>> x = 888
>>> def test():
	return x

>>> test()
888

​ If the name of the local variable in the function is the same as that of the global variable, the local variable will replace the global variable and is limited to use in the current function

>>> x = 888
>>> def test():
	return x

>>> test()
888
>>> def test():
	x = 666
	return x

>>> test()
666
3.global statement

​ Use global to declare variables as global variables

>>> x = 888
>>> def test():
	global x
	x = 520
	return x

>>> x
888
>>> test()
520
>>> x
520
4. Nested functions
>>> def funA():
	x = 520
	def funB():
		x = 666
		print (f"FunB:{
      
      x}")
	funB()
	return f"funA:{
      
      x}"

>>> funA()
FunB:666
'funA:520'
5. nonlocal statement

Function: Variables can be declared as external variables

>>> def funA():
	x = 520
	def funB():
		nonlocal x
		x = 666
		print (f"FunB:{
      
      x}")
	funB()
	return f"funA:{
      
      x}"

>>> funA()
FunB:666
'funA:666'
6. LEGB rules

L: local (local scope) E: enclosed (outer function scope of nested functions) G: global (global scope) B: build-ln (built-in function yu)

​ When a local variable is the same as a global variable, this local variable will replace the global variable to be called and used

>>> str(123)
'123'
>>> str="123"
>>> str(123)
Traceback (most recent call last):
  File "<pyshell#313>", line 1, in <module>
    str(123)
TypeError: 'str' object is not callable
>>> del str
>>> str(123)
'123'

​ Note: In order to avoid this from happening, try not to conflict with the built-in function names in python when declaring variables

Guess you like

Origin blog.csdn.net/weixin_53678904/article/details/131692614