Home  >  Article  >  Backend Development  >  Python Programming: Easily master function definitions, types and how to pass parameters

Python Programming: Easily master function definitions, types and how to pass parameters

WBOY
WBOYforward
2023-04-13 08:49:07963browse

Preface

This article helps you easily understand and master the core features of the Python language - functions: defining the syntax and function form, and introducing two ways to pass function parameters.

Function meaning

A function is a block of statements that performs a specific task. It is a part of the code that allows programmers to reuse, which promotes the modular concept of software programs. . The main idea behind this approach is to divide a large block of code into smaller independent parts and therefore more manageable sub-blocks. There are two types of functions in Python:

Built-in functions (Build-in): You can use these functions directly in the program without defining them when programming. This type of function is often used in the initial learning (for example, print(), input(), sum(), etc.).

User-defined functions (User-defined): Python allows programmers to create their own functions. This specific function type will be highlighted next.

In short, a function is a structured statement block that is defined and can be called repeatedly. The function has a unique name, can receive parameters, and returns the corresponding result (value) to the caller as needed, or does not return a value.

Function definition

The main rules for defining functions in Python are as follows:

  • The function block starts with the keyword def, followed by function name and brackets. Note that since Python is case-sensitive, def must be used instead of Def.
  • Similar to variable names, function names can contain letters or numbers, but do not contain spaces or special characters, and cannot start with a number.
  • Optional input parameters (called arguments) should be placed in parentheses - the number and type of parameters are as needed.
  • The function name is followed by a colon. Usually the statement block in the function starts with a newline after the colon and is indented.
  • Function that returns data must contain the keyword return in its code block.

In summary, there are four types of functions:

  • Function with no parameters and no return value;
  • Function with parameters and no return value;
  • Functions without parameters and return values;
  • Functions with parameters and return values.

The syntax format of function definition is as follows:

def functionName (var1, var2, … etc.):
 Statements

According to the presence or absence of actual parameters and the presence of input and/or return values, functions can be divided into for the four possible types above. They will be introduced separately below.

No parameter and no return value type function

In this type, the function does not accept variables as parameters and does not return any data. For example, the following script demonstration is such a function, which only prints a predefined string on the screen.

The code is obvious. There are formal parameters in the definition, no actual parameters when calling, and no return statement in the statement block. The structure simply calls the print() function to display the desired message. Calling such a function in the main program is quite simple and straightforward, as shown below:

# 定义一个既无参数也无返回值的函数
def printSomething():
print('Hello world')

# 在主程序中直接调用
printSomething()

The output result after running the program is:

Hello world

Function with parameters and no return value

Another type of function accepts variables as parameters but does not return any data. In the following example, a function is called by its declared name while including some value in the called function brackets. These values ​​are passed to the body of the function and can be treated as ordinary variables:

# 定义接收参数但无返回值的函数
def printMyName(fName, lName):
print('Your name is:', fName, lName)

# 提示用户输入姓名
firstName = input('Enter your first name: ')
lastName = input('Enter your last name: ')

# 在主程序中调用所定义的函数
printMyName(firstName, lastName)

Run the program and the results will be similar to the following:

Enter your first name:Solo
Enter your last name: Cui
Your name is: Solo Cui

Function with no parameters and return value

The third type is a function that does not accept parameters but returns data. It is important to remember that because this type of function returns a value to the calling code, this value must be assigned to a variable before it can be used or processed. An example is as follows:

# 定义无参数但有返回值的函数
def returnFloatNumber():
inputFloat = float(input('输入一个数字,其将返回给主程序:'))
return inputFloat

# 主程序调用函数并显示输入结果
x = returnFloatNumber()
print('输入的数字为:', x)

The result of running the program is similar to the following:

输入一个数字,其将返回给主程序: 5.7
输入的数字为:: 5.7

Function with parameters and return value

This type of function accepts parameters and returns the value to the caller code. Situation example below. In this case, the function call must include a parameter list and assign the return value to a specific variable for later use:

# 有参有返回值函数
def calculateSum(number1, number2):
print('计算两个数字和.')
return(number1 + number2)

# 接受用户输入的两个数字
num1 = float(input('输入第一个数字: '))
num2 = float(input('输入第二个数字: '))

# 调用函数计算俩个数字和
addNumbers = calculateSum(num1, num2)

# 输出两个数字和
print('两个数字和为:', addNumbers)

The results of running the program will be similar to the following:

输入第一个数字: 3
输入第二个数字: 5
计算两个数字和...
两个数字和为:: 8.0

Function parameter passing methods

There are two different methods for passing parameters to functions. Determining which of the two methods to choose should depend on whether the value of the original variable can be changed within the function. There are two ways to pass parameter values ​​to a function, usually called call/pass by value and call/pass by reference.

In summary, function parameter transfer:

First, by value: the parameter is a copy of the original variable, keeping the copy without changing the original value;

Second , by reference: changes act directly on the original variable, thus changing the original value.

Calling/passing by value

In this case, the value of the actual parameter (formal parameter) is treated as a copy of the original variable. Therefore, when program control returns to the caller, the original variables in the caller's scope remain unchanged.

在Python中,如果将不可变参数(例如,整数和字符串)传递给函数,通常的做法是按值调用/传递参数。下面的示例通过介绍id()函数说明了这种情况。它接受一个对象作为参数(即id(object)),并返回这个特定对象的标识。Id()返回值是一个整数,它在对象的生命周期内是惟一的和永久的。如示例所示,在调用checkParamemterID函数之前,变量x的id为4564813232。需要注意的是,只要x的值没有更新,x的id在函数中就不会改变。但是,一旦该值更新为20,其对应的id将更改为4564813552。需要注意的最重要的一点是,x的id在调用函数后不会改变,它的原始值保持不变(4564813232)。这意味着对x值的更改应用于变量的副本,而不是调用者作用域内的原始变量。

示例代码如下:

#按值传递参数
# 定义函数'checkParameterID',带参且按值传递
def checkParameterID(x):
print('在checkParameterID函数内x值改变之前其值为 ', x, 'n其id 为', id(x))
# 在函数范围内改变参数x的值
x = 20
print('checkParameterID中x的值改变后为', x, 'n 其id为', id(x))

# 在主程序声明变量x并赋予初始值
x = 10

print('调用checkParameterID函数之前x的值是', x, 'n 其id为', id(x))

# 调用'checkParameterID'函数
checkParameterID(x)

# 函数调用后在主程序中显示关于'x'的信息
print('调用checkParameterID函数后x的值为', x, 'n 其id为', id(x))

运行输出结果类似如下:

调用checkParameterID函数之前x的值是 10
其id为 2570870194704
在checkParameterID函数内x值改变之前其值为 10
其id 为 2570870194704
checkParameterID中x的值改变后为 20
其id为 2570870195024
调用checkParameterID函数后x的值为 10
其id为 2570870194704

按引用调用/传递

在这种情况下,函数获取实参(即原始变量)的引用,而不是它的副本。如果函数内发生更改,则调用者作用域中原始变量的值也将被修改。在Python中,如果可变参数(如列表)传递给函数,则调用/传递是通过引用进行的。如下所示,updateList将值5追加到名为y的列表中。即原始可变变量x的值发生了变化,这证明函数按引用调用/传递参数的特征。示例代码如下:

# 定义函数'upDateList' 其改变列表内的值
def updateList(y):
y = y.append(5)
return y

# 声明列表'x' 有四个元素值
x = [1, 2, 3, 4]
print('在调用updateList函数之前,x的内容是:', x)

# 调用函数'updateList'
print('调用函数updateList')
updateList(x)
print('调用updateList函数后x的内容为:', x)

运行程序输出结果类似如下:

在调用updateList函数之前,x的内容是: [1, 2, 3, 4]
调用函数updateList
调用updateList函数后x的内容为: [1, 2, 3, 4, 5]

本文小结

本期内容介绍了函数的基本内容和实现语法,以及参数传递、有无参数和返回值的函数形式以及函数调用/传递的实现。

The above is the detailed content of Python Programming: Easily master function definitions, types and how to pass parameters. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete