search
HomeBackend DevelopmentPython TutorialWhat are the fundamental concepts of Python functions?

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 <h3 id="使用模块中的函数">06. 使用模块中的函数</h3><blockquote data-id="b603af74-piQdAH4b"><p data-id="p838747a-N5R08QQL"><strong>模块是 Python 程序架构的一个核心概念</strong></p></blockquote>
  • 模块就好比是工具包,要想使用这个工具包中的工具,就需要导入 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:亿速云. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.