What 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:
Define functions——EncapsulationIndependent functions
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
New
04_Function
Project-
Copy the previously completed multiplication tablefile
Modify the file and add function definition
multiple_table():
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 函数名():
def
is the abbreviation of Englishdefine
Function name should be able to express the function of function encapsulation code to facilitate subsequent calls
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
function name()
Complete the call to the function2.3 The first function walkthrough
Requirements
Write a greeting## The function of #say_hello
- encapsulates three lines of code to say hello
Call the code to say hello below the function
-
Use
name = "小明" # 解释器知道这里定义了一个函数 def say_hello(): print("hello 1") print("hello 2") print("hello 3") print(name) # 只有在调用函数时,之前定义的函数才会被执行 # 函数执行完成之后,会重新回到之前的程序中,继续执行后续的代码 say_hello() print(name)
Copy after loginSingle-step execution of F8 and F7
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
?
cannot!
Because before
- 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
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,
two blank lines with other code (including comments)Above the function definition
, you should keep
03. 函数的参数
演练需求
开发一个
sum_2_num
的函数函数能够实现两个数字的求和功能
演练代码如下:
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 参数的作用
函数,把具有独立功能的代码块组织为一个小模块,在需要的时候调用
函数的参数,增加函数的通用性,针对相同的数据处理逻辑,能够适应更多的数据
在函数内部,把参数当做变量使用,进行需要的数据处理
函数调用时,按照函数定义的参数顺序,把希望在函数内部处理的数据,通过参数传递
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 文件(了解)
C
是compiled
编译过 的意思
操作步骤
浏览程序目录会发现一个
__pycache__
的目录目录下会有一个
hm_10_分隔线模块.cpython-35.pyc
文件,cpython-35
表示Python
解释器的版本这个
pyc
文件是由 Python 解释器将模块的源码转换为字节码
Python
这样保存字节码是作为一种启动速度的优化
字节码
Python
在解释源程序时是分成两个步骤的
首先处理源代码,编译生成一个二进制字节码
再对字节码进行处理,才会生成 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
When
Python
recompiles, it will automatically check the source file and bytecode file The timestampIf 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.
