Basic learning functions for python introductory

python function definition

Function: implement specific functions, reusable, organized
Benefits: can be used at any time, improve efficiency, reduce duplication

Function Syntax

def function name (incoming parameters):
 function body
 return return value

function call

Syntax: function-name(parameters)

Note:
① The incoming parameters, parameters, and return values ​​of the function can be omitted.
② The function is defined first and then called
. Example:

# 定义一个函数,输出相关信息
def name():
    print("My name is 二狗。\n今年26岁。")# \n换行输出


# 调用函数,让函数进行工作
name()

Running result:
My name is Ergou.
26 years old this year.

The incoming parameters of the function

①The function of passing in parameters: when the function performs calculations, it accepts the data provided by the external call.
② The number of parameters used is not limited .
③ Function fractal parameters and actual parameters:
functionin definitionThe parameters are called formal parameters (parameters), and the parameters are separated by commas;
the functioncallingThe parameters of are called actual parameters (actual parameters), and they are passed in in order (one-to-one correspondence with the formal parameters) when they are passed in, separated by commas.
Example 1:

# 定义相加的函数,通过参数接收被计算的数字
def add(x, y, z):
    result = x + y + z
    print(f"{
      
      x}+{
      
      y}+{
      
      z}的计算结果是{
      
      result}。")


# 调用函数,传入被计算的数字
add(5, 6, 7)

Running result: The calculation result of 5+6+7 is 18.

Example 2:

def check(num):
    if num <= 37.5:
        print(f"体温{
      
      num}度,正常!")
    else:
        print(f"体温{
      
      num}度,不正常!")


print("请出示体温!")
# 调用函数,传入参数
check(int(input("请输入体温:")))

Running result:
Please show your body temperature!
Please enter body temperature: 36
body temperature 36 degrees, normal!

function return value

Syntax: (return data to the caller through the return keyword)
def function (parameter):
 function body
 return return value

variable = function(parameters)
Note: The function body ends when it encounters a return, and the code after the return will not be executed again.
Example:

# 定义一个函数
def add(a, b):
    result = a + b
    # 通过返回值,将结果返回给调用者
    return result
    # print(result) #retrun后语句不会再执行


# 函数的返回值,可以通过变量去接收
r = add(5, 6)
print(r)

Running result: 11

Return value of None type: empty, meaningless
None is the literal value of type 'NoneType'
return None, it can be left blank, and
None is returned if the return statement is not used

Scenarios for using the None type:
①Used in a function with no return value, for example: return None
②Used in an if judgment, None is equal to False
③Defining a variable with no initial value: name=None
Example:

# None 用于if判断
def check_age(age):
    if age > 18:
        return "success"
    else:
        return None


result = check_age(16)
if not result:
    # 进入if表示result是None值就是False
    print("你还未成年")

# None用于声明无初始内容的变量
name = None

Function documentation

Syntax:
def func(x,y)
 """
 Function description
 : param x: description of formal parameter x
 : param y: description of formal parameter y
 : return: description of return value
 """
 function body
 return return value

Function and definition of function documentation

① Explain the function through multi-line comments
② Write before the function body
③: param is used to explain the parameters
④: return is used to explain the return value
⑤ Enter """""" and press
Enter to complete automatically For functions, you can see the function documentation
. Example:

# 定义一个函数
def add(a, b):  # 输入""""""回车就自动补齐

    """
    add 函数接收2个数进行相加
    :param a: 形参x表示一个数
    :param b: 形参y表示一个数
    :return: 返回两个数的结果
    """
    result = a + b
    # 通过返回值,将结果返回给调用者
    return result
    # print(result) #retrun后的语句不会再执行


# 函数的返回值,可以通过变量去接收
r = add(5, 6)  # 光标停留在调用函数可以看到函数说明文档
print(r)

nested function calls

Definition: A function calls another function.
Syntax:
def func_b():
 print

def func_a():
 print
 func_b()

func_a()

When a is called, the part before b is executed first, then to b and then to the rest of a.

Variable scope in functions

variable scope

Definition: Variable scope refers to the scope of the variable.
There are two main types of variables: local variables and global variables:
①Local variables refer to definitionsinside the function bodyVariables are only valid within the function body.
Local variable role: in the function bodytemporarySave the data, and destroy the local variables after the function body call is completed.
②Global variables refer toinside and outside the function bodyVariables that are in effect.

global keyword

Definition: Variables can be declared as global variables inside the function, that is, local variables in the function body become global variables.
Syntax: global variable-name
Example:

# global关键字,在函数中声明变量为全局变量
num = 200


def test_a():
    print(f"test_a:{
      
      num}")


def test_b():
    global num  # 设置内部定义的变量为全局变量,得加这个
    num = 500  # 此时num500与num200是同一个
    print(f"test_b:{
      
      num}")


test_a()
test_b()
print(num)  # 此时全局的num应该等于500

Running result:
test_a:200
test_b:500
500

Function synthesis case

ATM machine deposit, withdrawal, balance inquiry and other business procedures

Guess you like

Origin blog.csdn.net/weixin_44996886/article/details/132263159