Learning Python (D) function

learning target:

  • 函数的基本使用
  • 函数的参数
  • 函数的返回值
  • 函数的嵌套使用

Learning Content;

一)函数的基本使用

The concept : to have 独立功能的代码块organized into a small module, be called in when needed

Step use :
1, defined functions - independent functional package
2, the calling function - to enjoy the success of the package

Role : In the program development process, the use of function can improve write 效率and code重用

Function definition format :

def 函数名():
    函数主体
    …………

def即define的缩写
函数名应该能够表达函数封装代码的功能,方便后续的调用
函数名的命名应该符合标识符的命名规则:可以由字母、下划线和数字组成;不能以数字开头;不能与关键字重名
函数的调用:通过函数名()进行函数的调用
函数一定要先定义再调用
在开发中,如果希望给函数添加注释,应该在定义函数的下方,使用连续的三对引号
在连续的三对引号之间编写对函数的说明文字
在函数调用位置,使用快捷键 CTRL + Q可以查看函数的说明信息.

Example:

name = "小明"

def skill():

    print("会舞蹈")

    print("会唱歌")

    print("擅长游泳和跑步")

print(name)

print(skill())

二)函数的参数

Function parameters used:

Inside parentheses after the function name is used to fill between a plurality of parameters, "" separated

Effect parameters:

The tissue function block having individual functions as a small module, the function call parameters when needed, increasing function 通用性, the data processing logic for the same, to adapt more data
1) inside the function as the variable parameter use, the need for data processing
2 function call, the function according to the order defined by the parameters, data) processing inside the function desired, passed through parameters

And parameter arguments:
形参 : defining a function, the argument in parentheses, is used to access parameters for use as variables inside a function
实参: the function is called, parentheses parameter is used to pass data to the function for internal use

def sum(num1, num2):
    result = num1 + num2
    print("%d + %d = %d" % (num1, num2, result))
sum(50, 20)

三)函数的返回值
Program development, sometimes want to perform a function after the end, tell the caller a result, for the caller to do the follow-up treatment for concrete results. After the return value of the function is to complete the work, a final result to the caller. Used in the function returnkey can return results. One function call variables can be used to receive the function returns

注意:return表示返回,后续的代码都不会被执行.

def sum(num1, num2):
    """对两个数字的求和"""
     return num1 + num2
     
def mul(num1, num2):
    """对两个数字的求积"""
    return num1 * num2
# 调用函数,并使用 result 变量接收计算结果

result1 = sum(10, 20)
result2 = mul(10, 20)

print("计算两个数之和是 %d" % result1)
print("计算两个数之积是 %d" % result2)

四) 函数的嵌套调用

A 函数里面又调用了另外一个函数, which is the function 嵌套调用: If the function test2, call another function test1, test1 is executed to the calling function, the function will first test1 in executing the task will return to the position of test1 test2 function call in and continue Successive code execution

Published 62 original articles · won praise 42 · views 3304

Guess you like

Origin blog.csdn.net/weixin_45375866/article/details/103153400