Home  >  Article  >  Backend Development  >  What are the fundamental concepts of Python functions?

What are the fundamental concepts of Python functions?

王林
王林forward
2023-05-09 23:43:061143browse

01. Quick experience of functions

1.1 Quick experience

  • The so-called function is to combine code blocks with independent functions Organized into a small module, when needed Call

  • The use of the function includes two steps:

  1. Define functions——EncapsulationIndependent functions

  2. Call functions——Enjoy the results of Encapsulation

  • The role of functions, when developing programs, using functions can improve the efficiency of writing and the reuse of code

Walkthrough steps

  1. New04_Function Project

  2. Copy the previously completed multiplication tablefile

  3. Modify the file and add function definitionmultiple_table():

  4. Create another file, use import to import and call the function

02. Basic function usage

2.1 Function definition

The format of defining functions is as follows:

def 函数名():
  1. def is the abbreviation of English define

  2. Function name should be able to express the function of function encapsulation code to facilitate subsequent calls

  3. Function name# The naming of ## should conform to the naming rules for identifiers

    ## can be composed of
  • letters

    , underscore and digits form

  • cannot start with a number

  • Cannot have the same name as a keyword

    ##2.2 Function call
Calling a function is very simple, through

function name()

Complete the call to the function

2.3 The first function walkthrough

Requirements

Write a greeting## The function of #say_hello
    encapsulates three lines of code to say hello
  1. Call the code to say hello below the function

  2. name = "小明"
    
    
    # 解释器知道这里定义了一个函数
    def say_hello():
        print("hello 1")
        print("hello 2")
        print("hello 3")
    
    print(name)
    # 只有在调用函数时,之前定义的函数才会被执行
    # 函数执行完成之后,会重新回到之前的程序中,继续执行后续的代码
    say_hello()
    
    print(name)

    Use
  3. Single-step execution of F8 and F7
Observe the execution process of the following code

After defining the function, it only means that this function encapsulates a piece of code
  • If the function is not actively called, the function will not be actively executed.

  • Think about whether it is possible to

    Function call
  • placed above
function definition
?
  • cannot!

  • Because before
using the function name
    to call the function, you must ensure that
  • Python

    already knows the existence of the function

  • Otherwise the console will prompt NameError: name 'say_hello' is not defined (Name error: the name say_hello is not defined)

  • 2.4 PyCharm’s debugging tool

    #F8 Step Over
  • You can execute the code step by step, and the function call will be regarded as a line of code and executed directly

  • F7 Step Into

    You can execute the code in one step. If it is a function, you will enter the inside of the function

  • 2.5 Function documentation comments
  • During development, if you want to add comments to a function, you should use

    three consecutive pairs of quotation marks
# below

define the function

  • ##Write a description of the function between

    three consecutive pairs of quotation marks

    At the
  • function call
  • position , use the shortcut key

    CTRL Q to view the description information of the function

  • Note: Because the function body is relatively independent, Above the function definition, you should keep

    two blank lines with other code (including comments)

03. 函数的参数

演练需求

  1. 开发一个sum_2_num 的函数

  2. 函数能够实现两个数字的求和功能

演练代码如下:

def sum_2_num():

    num1 = 10
    num2 = 20
    result = num1 + num2

    print("%d + %d = %d" % (num1, num2, result))

sum_2_num()

思考一下存在什么问题

函数只能处理 固定数值 的相加

如何解决?

  • 如果能够把需要计算的数字,在调用函数时,传递到函数内部就好了!

3.1 函数参数的使用

  • 在函数名的后面的小括号内部填写参数

  • 多个参数之间使用, 分隔

def sum_2_num(num1, num2):

    result = num1 + num2
    
    print("%d + %d = %d" % (num1, num2, result))

sum_2_num(50, 20)

3.2 参数的作用

  • 函数,把具有独立功能的代码块组织为一个小模块,在需要的时候调用

  • 函数的参数,增加函数的通用性,针对相同的数据处理逻辑,能够适应更多的数据

  1. 在函数内部,把参数当做变量使用,进行需要的数据处理

  2. 函数调用时,按照函数定义的参数顺序,把希望在函数内部处理的数据通过参数传递

3.3 形参和实参

  • 形参定义函数时,小括号中的参数,是用来接收参数用的,在函数内部作为变量使用

  • 实参调用函数时,小括号中的参数,是用来把数据传递到函数内部用的

04. 函数的返回值

  • 在程序开发中,有时候,会希望一个函数执行结束后,告诉调用者一个结果,以便调用者针对具体的结果做后续的处理

  • 返回值是函数完成工作后,最后给调用者的一个结果

  • 在函数中使用return 关键字可以返回结果

  • 调用函数一方,可以使用变量接收函数的返回结果

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

def sum_2_num(num1, num2):
    """对两个数字的求和"""

    return num1 + num2

# 调用函数,并使用 result 变量接收计算结果
result = sum_2_num(10, 20)

print("计算结果是 %d" % result)

05. 函数的嵌套调用

  • 一个函数里面又调用另外一个函数,这就是函数嵌套调用

  • 如果函数test2 中,调用了另外一个函数test1

  • 那么执行到调用test1 函数时,会先把函数test1 中的任务都执行完

  • 才会回到test2 中调用函数test1 的位置,继续执行后续的代码

def test1():

    print("*" * 50)
    print("test 1")
    print("*" * 50)


def test2():

    print("-" * 50)
    print("test 2")
    
    test1()
    
    print("-" * 50)

test2()

函数嵌套的演练 —— 打印分隔线

体会一下工作中 需求是多变

需求 1

  • 定义一个print_line 函数能够打印* 组成的一条分隔线

def print_line(char):

    print("*" * 50)

需求 2

  • 定义一个函数能够打印由任意字符组成的分隔线

def print_line(char):

    print(char * 50)

需求 3

  • 定义一个函数能够打印任意重复次数的分隔线

def print_line(char, times):

    print(char * times)

需求 4

  • 定义一个函数能够打印5 行的分隔线,分隔线要求符合需求 3

提示:工作中针对需求的变化,应该冷静思考,不要轻易修改之前已经完成的,能够正常执行的函数

def print_line(char, times):

    print(char * times)


def print_lines(char, times):

    row = 0
    
    while row < 5:
        print_line(char, times)

        row += 1

06. 使用模块中的函数

模块是 Python 程序架构的一个核心概念

  • 模块就好比是工具包,要想使用这个工具包中的工具,就需要导入 import这个模块

  • 每一个以扩展名py 结尾的Python 源代码文件都是一个模块

  • 在模块中定义的全局变量函数都是模块能够提供给外界直接使用的工具

6.1 第一个模块体验

步骤

  • 新建hm_10_分隔线模块.py

  • 复制hm_09_打印多条分隔线.py 中的内容,最后一行 <strong>print</strong> 代码除外

  • 增加一个字符串变量

name = "黑马程序员"
  • 新建hm_10_体验模块.py 文件,并且编写以下代码:

import hm_10_分隔线模块

hm_10_分隔线模块.print_line("-", 80)
print(hm_10_分隔线模块.name)
体验小结
  • 可以在一个 Python 文件定义 变量 或者 函数

  • 然后在另外一个文件中使用import 导入这个模块

  • 导入之后,就可以使用模块名.变量 /模块名.函数 的方式,使用这个模块中定义的变量或者函数

模块可以让 曾经编写过的代码 方便的被 复用

6.2 模块名也是一个标识符

  • 标示符可以由字母下划线数字组成

  • 不能以数字开头

  • 不能与关键字重名

注意:如果在给 Python 文件起名时,以数字开头 是无法在 PyCharm 中通过导入这个模块的

6.3 Pyc 文件(了解)

Ccompiled 编译过 的意思

操作步骤

  1. 浏览程序目录会发现一个__pycache__ 的目录

  2. 目录下会有一个hm_10_分隔线模块.cpython-35.pyc 文件,cpython-35 表示Python 解释器的版本

  3. 这个pyc 文件是由 Python 解释器将模块的源码转换为字节码

  • Python 这样保存字节码是作为一种启动速度的优化

字节码

  • Python 在解释源程序时是分成两个步骤的

  1. 首先处理源代码,编译生成一个二进制字节码

  2. 再对字节码进行处理,才会生成 CPU 能够识别的机器码

  • After you have the bytecode file of the module, the next time you run the program, if the source has not been modified since the last time you saved the bytecode code, Python will load the .pyc file and skip the compilation step

  • WhenPython recompiles, it will automatically check the source file and bytecode file The timestamp

  • If you modify the source code again, the bytecode will be automatically recreated the next time the program is run

Tip: Regarding modules and other import methods of modules, subsequent courses will gradually expand!

Module is a core concept of Python program architecture

The above is the detailed content of What are the fundamental concepts of Python functions?. For more information, please follow other related articles on the PHP Chinese website!

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