Python functions, advanced syntax and usage

Zhizhitang 2021-04-06 22:25:04
python functions advanced syntax usage


1. What is? python Functions and defining a function

Functions are organized , Reusable , To achieve oneness , Or code snippets associated with functions .

Function can improve the modularity of application , And code reuse . You already know Python Many built-in functions are provided , such as print(). But you can also create your own functions , This is called a user-defined function .

img

# function 
def function(param):
pass
return 'this is function'
result = function('param')
print(result)
 Copy code 

2. Function USES

Parameter description : Parameters Parameters in function : Row reference Call the parameters in the function : Actual parameters


Function returns multiple results , Elegant acceptance of parameters

# Function returns multiple results , Elegant acceptance of parameters 
def function1(param1, param2):
param1 = param1 * 3
param2 = param2 * 2 + 20
return param1, param2
param1, param2 = function1(2, 3)
print(param1)
print(param2)
 Copy code 

Specify the parameters ( No arguments 、 Necessary parameters 、 Specify arguments 、 Default parameters 、 Variable parameters )

# No arguments 
def function1():
print(' No parameters ')
print(' Nonparametric nonparametric return Return results :' ,function1())
# Specify arguments 
param1,param2 = function1(param2 = 4, param1 = 2)
print(param1, param2)
# Row parameter default value 
# Row parameter order : The default parameter is after 
def function1(param1=4, param2=4):
param1 = param1 * 3
param2 = param2 * 2 + 20
return param1, param2
param1,param2 = function1()
print(param1, param2)
# Variable parameters 
def function2(*param):
print(param)
# No, * Output results :((1, 2, 3),)
function2((1,2,3))
function2(*(1,2,3))
# Keyword variable parameters 
def function3(**param):
# Return results :{'x': 1, 'y': 2, 'z': 3}
print(param)
# dict
print(type(param))
function3(x=1, y=2, z=3)
# Return without anything {}
function3()
 Copy code 

We need to avoid the pit here

# Avoid pit Necessary parameters > Variable parameters > Default parameters 
def function3(param1, *param3, param2=2):
print(' Necessary parameters :', param1)
print(' Variable parameters :', param3)
print(' Default parameters :', param2)
# param1 = str,param3 = 1,2,3,param2 = param
function3('str', 1, 2, 3, 'param')
# Output results : Necessary parameters : str , Variable parameters : (1, 2, 3, 'param') , Default parameters : 2 Fall short of expectations 
function3('str', 1, 2, 3, param2='param')
 Copy code 

3. Python Functional programming

Functions themselves can be assigned to variables ( That is, variables can point to functions ). In fact, the function name itself refers to the variable of the function .

One function can take another function as an argument . This kind of function is called higher order function , For example, here are a few examples :

3.1 lambda expression - Anonymous functions

# Anonymous functions 
function = lambda x, y: x + y
print(function(1,2))
 Copy code 

3.2 map And lambda

map Function takes two parameters , One is a function , One is Iterable,map Apply the incoming function to each element of the sequence in turn , And take the result as a new Iterator return .

# map Use 
# seek arr Square of each element 
arr = [1, 2, 3, 4, 5, 6, 7, 8]
def square(x):
return x * x
result = map(square, arr)
print(list(result))
# lambda And map Use it together 
result1 = map(lambda x: x * x, arr)
print(list(result1))
# lambda And map Use it together Multiple parameters ; If arr And arr1 The number is different. , Only the minimum number is calculated , as follows arr1 The number ratio is arr Less Will only return 5 Elements , conversely arr The number ratio is arr1 Less It will only calculate arr One digit 
arr1 = [1, 2, 3, 4, 5, 6]
result2 = map(lambda x, y: x * x + y, arr, arr1)
print(list(result2))
 Copy code 

List push down , Apply to :list、dict、tuple、set

# List derivation - list
arr = [1, 2, 3, 4, 5, 6, 7, 8]
result = [x * x for x in arr]
print(result)
# Add conditional judgment (x Refer to subscript )
result1 = [x * x for x in arr if x >=4]
print(result1)
# List derivation - dict
sex = {
0 : ' male ',
1 : ' Woman ',
2 : ' Neutral '
}
result2 = {value:key for key,value in sex.items()}
print(result2)
 Copy code 

3.3 reduce Continuous calculation data

Use reduce introduce functools library

from functools import reduce
# reduce Use : There must be two parameters 
# reduce effect : Continuous calculation , There's only one result 
arr = [1, 2, 3, 4, 5, 6, 7, 8]
result = reduce(lambda x, y: x + y, arr)
# The calculation is as follows :((((1 + 2) + 3) + 4) + 5)... + 6 + 7 + 8
print(result)
# reduce The third parameter , Starting value 
result1 = reduce(lambda x, y: x + y, arr, 14)
# The calculation is as follows :14 +((((1 + 2) + 3) + 4) + 5)... + 6 + 7 + 8
print(result1)
 Copy code 

3.4 filter Filtering data

and map() similar ,filter() It also takes a function and a sequence . and map() When it's different ,filter() Apply the incoming function to each element in turn , Then according to the return value is True still False Decide whether to keep or discard the element .

# filter Use The first parameter must return bool
arr = [1, 0, 0, 1, 1, 4, 0, 5]
result = filter(lambda x:True if x==1 else False, arr)
print(list(result))
 Copy code 

3.5 Decorator

The essence of decorator is a Python function , It allows other functions to add extra functionality without any code changes . We have decorators , We can pull out a lot of the same code that has nothing to do with the function itself and continue to reuse it . It's often used in scenarios with facet requirements : Including inserting logs 、 Performance testing 、 Transaction processing 、 Cache and permission verification, etc

# Decorator 
# func Refers to a function 
def decorator(func):
def wrapper(*args, **kwargs):
# Execute the internal logic of the function Print time 
print(time.time(), args, kwargs)
# Execute the logic in the calling function Print different parameters 
func(*args, **kwargs)
return wrapper
# One parameter 
@decorator
def function(param):
print('function : this is decorator ' + param)
# Two parameters 
@decorator
def function1(param1, param2):
print('function1 : this is decorator ' + param1)
print('function1 : this is decorator ' + param2)
# Three parameters ( Variable parameters )
@decorator
def function2(param1, param2, **kwargs):
print('function2 : this is decorator ' + param1)
print('function2 : this is decorator ' + param2)
print(kwargs)
function('param')
function1('param1' , 'param2')
function2('param1' , 'param2', x=1,y=2,z=3)
 Copy code 

4. Python Advanced Grammar and usage

4.1 Walrus operators 3.8 above

9.png

Its original English name was Assignment Expressions, Translation means Assignment expression , But now it's more commonly called the walrus operator , Because it looks so much like walrus .

1. The first usage :if/else

10.png

If in Python 3.8 Before ,Python It has to be written like this

11.png

But with the walrus operator , You can and Golang equally ( If you haven't learned Golang, Then pay attention to ,Golang Medium := Short variable declaration , It means to declare and initialize , It and Python Medium := It's not a concept )

12.png

# Walrus operators :=
str = 'Python'
if len(str) > 5:
print('str Longer than 5,str The length is :', len(str))
# Equate to 
if (x:=len(str)) > 5:
print(f'str Longer than 5,str The length is :{x}')
 Copy code 

4.2 enumeration

from enum import Enum
from enum import IntEnum,unique
# Define an enumeration class 
class PEOPLE(Enum):
YELLOW_RACE = ' The yellow race '
WHITE_PERSON = ' The white race '
BLACK_RACE = ' The black race '
DEFULT = 0
# Definition int Type enumeration class @unique value It means the same thing will report an error 
@unique
class PEOPLE1(IntEnum):
YELLOW_RACE = 0
WHITE_PERSON = 1
BLACK_RACE = 2
# Enumeration values 
print(PEOPLE.YELLOW_RACE.name, ' : ',PEOPLE.YELLOW_RACE.value)
# Traversal enumeration 
for item in PEOPLE:
print(item.name, ' : ', item.value)
 Copy code 

Enum Not only can it be a good enumeration, but also can be used to replace some tedious classes 、 state 、 Order and so on . for instance :`life = Enum('life', 'born baby teenager adult older die').

版权声明
本文为[Zhizhitang]所创,转载请带上原文链接,感谢
https://pythonmana.com/2021/04/20210406213025912A.html

  1. Spark Delta Lake 0.4.0 发布,支持 Python API 和部分 SQL
  2. How to transfer office files to PDF
  3. Are you still worried about multiple excel summary statistics? Python second processing really fragrant!
  4. Making music aggregate downloader with Python
  5. Spark delta Lake 0.4.0 is released, supporting Python API and part of SQL
  6. Python信息搜集
  7. Python information gathering
  8. Python - 关于类(self/cls) 以及 多进程通讯的思考
  9. Python - thinking about class (self / CLS) and multi process communication
  10. Python - 关于类(self/cls) 以及 多进程通讯的思考
  11. Python - thinking about class (self / CLS) and multi process communication
  12. Python信用评分卡建模(附代码)
  13. Python credit score card modeling (with code)
  14. 学Python需要学数据库吗?Python学习教程!
  15. Do you need to learn database to learn Python!
  16. Python私有变量如何定义?Python学习教程!
  17. How to define Python private variables? Python tutorial!
  18. Python数据分析入门(六):Pandas的函数应用
  19. Introduction to Python data analysis (6): function application of pandas
  20. 学Python需要学数据库吗?Python学习教程!
  21. Do you need to learn database to learn Python!
  22. Python描述 LeetCode 80. 删除有序数组中的重复项 II
  23. C++/python描述 AcWing 94. 递归实现排列型枚举
  24. C++/python描述 AcWing 92. 递归实现指数型枚举
  25. Python描述 LeetCode 88. 合并两个有序数组
  26. 苏州大学计算机考研 复试机试真题2013-2021真题及Python题解
  27. Python描述 LeetCode 781. 森林中的兔子
  28. 字典和json的区别是什么?Python学习
  29. Python describes leetcode 80. Removing duplicate items from ordered arrays II
  30. C + + / Python description acwing 94. Recursive implementation of permutation enumeration
  31. C + + / Python description acwing 92. Recursive implementation of exponential enumeration
  32. Python describes leetcode 88. Merging two ordered arrays
  33. Real computer test questions 2013-2021 of computer postgraduate entrance examination of Soochow University and python solutions
  34. The rabbit in the forest
  35. Python中的魔法属性
  36. What's the difference between dictionary and JSON? Python learning
  37. Magic properties in Python
  38. 字典和json的区别是什么?Python学习
  39. What's the difference between dictionary and JSON? Python learning
  40. python刷题-字母图形
  41. Python brush questions - letter graphics
  42. Python数据分析入门(七):Pandas层级索引
  43. Introduction to Python data analysis (7): Pandas hierarchical index
  44. Python 操作腾讯云短信(sms)详细教程
  45. Python operation Tencent cloud SMS (SMS) detailed tutorial
  46. Python数据可视化,完整版实操指南 !
  47. Python data visualization, full version of the practical guide!
  48. 上手Pandas,带你玩转数据(2)-- 使用pandas从多种文件中读取数据
  49. 上手Pandas,带你玩转数据(1)-- 实例详解pandas数据结构
  50. Using pandas to read data from various files
  51. Hands on pandas, take you to play with data (1) -- detailed explanation of pandas data structure with examples
  52. Pandas数据结构基础用法
  53. Basic usage of pandas data structure
  54. Python读取ini配置文件,保存到对象属性
  55. Python reads the INI configuration file and saves it to the object properties
  56. Foundation of Python: classes in Python
  57. python刷题-闰年判断
  58. python刷题-01字串
  59. How to judge leap year
  60. Python brush title-01 string