当前位置:网站首页>07 - knowledge points about functions
07 - knowledge points about functions
2022-04-22 15:25:00 【~ Wen ~ J】
Hello everyone , I am a Python Bloggers in the field .
If you are a programming enthusiast, you can learn together , I send it here every day Python Basic knowledge of , And related code .
If there are any mistakes in the article , Please grant me your advice .
If you think the blogger's article is wrong , Please support the blogger for the third company
I always believe in a word : I believe that hard work will pay off , This return may be slow , But please believe that , As long as you stick to it, it will be better .
Series column :
Python Games and login system _
01-try-except exception handling
02-continue And break The difference between
Catalog
Two . The process of calling letters
Four . Parameter passing of function :
2. Variable quantity parameters :
5、 ... and . The role of functions on variables
6、 ... and . Recursion of a function
1. Definition of function recursion :
One . Definition of function
A function is a segment of 、 Reusable statement groups , Use the function name to represent and call the function through the function name . A function can also be regarded as a subroutine with a name , Execution can be called where needed , There is no need to write these statements repeatedly at every place of execution . Each time you use the function, you can provide different parameters as input , To realize the processing of different data ; After function execution , You can also feed back the corresponding processing results .
Functions can perform specific functions , Similar to black box , The use of functions does not need to understand the internal implementation principle of functions , As long as we know the input and output mode of the function . Strictly speaking , A function is a functional abstraction .
Some functions are written by users themselves , It's called a custom function ;Python The installation package also comes with some functions and methods , Include Python Built in functions ( Such as abs(、eval())、Python Functions in the standard library ( Such as math In the library sqrt()) etc. .
There are two main purposes of using functions : Reduce programming difficulty and code reuse . A function is a functional abstraction , It can be used to decompose a complex large problem into a series of simple small problems , Then continue to divide the small problem into smaller problems , When the problem is refined enough to be simple , We can divide and rule , Write a program for each small problem , And encapsulated by function , When all the small problems are solved , The big problem will be solved . Python Use def Reserved words define a function , The grammatical form is as follows :
def< Function name >(< parameter list >):
< The body of the function >
return < Return value list >
The function name can be any valid Python identifier ; The parameter list is the value passed to the function when it is called , There can be zero 、 One or more , When multiple parameters are passed, each parameter is separated by a comma , Keep parentheses when there are no arguments . The parameters in the parameter list in the function definition are formal parameters , Referred to as “ The formal parameter function body is the code executed each time the function is called , Consisting of one or more lines of statements . Use reserved words when you need to return a value return And return value list , Otherwise, the function can not return sentence , At the end of the function body ! Set to return control to the caller . for example : Here's a birthday song
t=input(" Please enter your name :")
def happy():
print("happy birthday to you")
def happy1(name):
happy()
happy()
print("happy birthday dear {}".format(name))
happy1(t)
After definition , In this way, the function can be called multiple times , Avoid code reuse . It also reduces the difficulty of programming .
Two . The process of calling letters
To call a function, the program needs to execute the following 4 A step .
(1) The caller pauses execution at the call
(2) Copy arguments to functions on call The parameter of .
(3) Execute the function body statement .
(4) The return value is given at the end of the function call , The program returns to the pause before the call and continues to execute .
3、 ... and .lambda function
The syntax is as follows :
< Function name > = lambda < parameter list >:< expression >
lambda Functions are the same as normal functions , Equivalent In the following form :
def < Function name >(< parameter list >):
return < expression >
In short ,lambda The function is used to define simple Single 、 Functions that can be represented on one line , Returns a function type
f=lambda x,y:x+y
type(f)
<class 'function'>
>>>f(10,20)
22
Four . Parameter passing of function :
1. Optional parameters :
Because the parameters need to be input in order when calling the function , Optional parameters must be defined after non optional parameters .
def dup(str,times=3):
That is... With default values times Must be placed in a non optional parameter str Back .
2. Variable quantity parameters :
Variable quantity parameter by adding (*) Realization . And can only appear at the end of the parameter list .
def t(x,*y):
....
>>>t(1,2,3,4)
# among 2,3,4 Is passed as a tuple to y
return Can return 0 individual ,1 individual , Multiple return values , When multiple values are returned , Save in tuple type .
5、 ... and . The role of functions on variables
Variables include : Global and local variables 1. Global variables : It usually indicates variables other than the internal variables of the function , In the whole process .2. local variable : Variables defined within a function , If you add a reserved word global, You can turn a local variable into a global variable , For list types , You can use the global list directly , Without the need for global To declare . If there is a real created and named ls A list of , Operating this list in this function does not change the global variable .
To sum up ,Python The effect of functions on variables Abide by the following principles .
(1) A simple data type variable has the same name as a global variable or not , Variables are released only after the function is created and used inside the function and exits , If there is a global variable with the same name , Its value remains unchanged .
(2) Simple data type variables in use global After the reservation statement , Use as a global variable , After the function exits, the variable remains and the value is changed by the function .
(3) For global variables with combined data types , If there is no real variable with the same name created inside the function , The value of the global variable can be directly used and modified inside the function .
(4) If a combined data type variable is actually created inside the function , Whether there is a global variable with the same name or not, the function only operates on local variables , After the function exits, the local variable is released , The global variable value remains unchanged .
6、 ... and . Recursion of a function
1. Definition of function recursion :
Call function in function definition middle note , Known as the recursive . Recursion has two important features :(1) There are one or more base cases , The base case does not need to recurse again , It's just a definite expression .(2) Therefore, the recursive chain should end with one or more base examples .
2. The use of recursion :
Illustrate with examples : Find the factorial of a number
def fact(n):
if fact==0:
return 1
else:
return n*fact(n-1)
num=eval(input(" Please enter an integer :"))
print(fact(abs(int(num))))
Xiaobian talks freely :
The works published by Xiaobian are suitable for beginners to learn , If you are a beginner , You can study with Xiaobian , I send it here every day Python Basic knowledge of , And related code . If you think the small preparation is good , Focus on , give the thumbs-up , Collection . If there's anything wrong , Your advice are most welcome . I will accept with an open mind . If there's something you don't understand , You can write it by private mail , I will reply to you as soon as possible .
版权声明
本文为[~ Wen ~ J]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204221511142536.html
边栏推荐
- 社区运营书籍推荐
- How to maintain and apply high voltage isolation probe
- [deeply understand tcallusdb technology] delete all data interface descriptions in the list - [list table]
- 人脸识别 (5) 基于MCTNN人脸检测(Pytorch)
- [in depth understanding of tcallusdb technology] description of data interface of designated location in replacement list - [list table]
- CommitFailedException异常,原因以及解决方案
- Computer Vision L7 -- Self-supervised Learning
- Ansible 实用技巧 - 批量巡检站点 URL 状态
- The GNU build system体验教程:Hello world example with Autoconf and Automake
- Sequential list -- basic implementation of one-way headless linked list
猜你喜欢

Face recognition (5) face detection based on mctnn (pytoch)

How to measure small current with oscilloscope and current probe
![[in depth understanding of tcallusdb technology] sample code for reading data - [generic table]](/img/7b/8c4f1549054ee8c0184495d9e8e378.png)
[in depth understanding of tcallusdb technology] sample code for reading data - [generic table]

UART minimalist routine for raspberry PI B

Tcallusdb Jun · industry news collection (4)

Introduction to development using Hal library, stm32cubemx and keil 5 (I): turn on an LED light (nucleo-f411re)

Who will do the school's fixed asset management system? Yunna RFID fixed asset management system
![【深入理解TcaplusDB技术】批量删除列表指定位置数据接口说明——[List表]](/img/7b/8c4f1549054ee8c0184495d9e8e378.png)
【深入理解TcaplusDB技术】批量删除列表指定位置数据接口说明——[List表]

Redis的线程模型

【模型】状态空间平均法建模-降压
随机推荐
【深入理解TcaplusDB技术】读取列表指定位置数据接口说明——[List表]
分布式任务调度平台XXL-JOB安装及使用
[in depth understanding of tcallusdb technology] insert data example code - [generic table]
share memory的bank conflict分析
微服务技术概览
MySQL initialization error
Redis thread model
2022 chemical automation control instrument examination question bank and online simulation examination
如何用示波器和电流探头来测量小电流
JVM garbage collection parnew and CMS introduction
Tcallusdb Jun · industry news compilation (III)
ROS communication mechanism II - service communication
[deeply understand tcallusdb technology] insert data into the specified location of the list interface description - [list table]
How to import Cisco evng image simulator
Tencent cloud im integration (so easy)
Redis optimization series (I) building redis master-slave based on docker
E. 2-Letter Strings
【深入理解TcaplusDB技术】将数据插入到列表指定位置接口说明——[List表]
Wireguard article series (5): introduction to netmaker - a platform for creating and managing wireguard networks
The translation uses Prometheus and grafana to realize SLO
