Function Basics
Target
- Quick experience of functions
- Basic use of functions
- function arguments
- the return value of the function
- Nested calls to functions
- Define functions in modules
01. Quick experience of functions
1.1 Quick experience
- The so-called function is to organize the code blocks with independent functions into a small module, which can be called
- The use of the function consists of two steps:
- Defining Functions - Encapsulating Independent Functions
- Calling functions - enjoying the fruits of encapsulation
- The role of functions , when developing programs, using functions can improve the efficiency of writing and code reuse
Walkthrough steps
- new
04_函数
project - Copy the multiplication table file you completed earlier
- Modify the file and add function definitions
multiple_table():
- Create another file,
import
import
02. Basic use of functions
2.1 Definition of functions
The format for defining a function is as follows:
def 函数名():
函数封装的代码
……
def
isdefine
the- The function name should be able to express the function of the function encapsulation code to facilitate subsequent calls
- The function name should be named according to the naming rules for identifiers
- Can consist of letters , underscores and numbers
- cannot start with a number
- Cannot have the same name as a keyword
2.2 Function call
Calling a function is very simple, 函数名()
you can complete the call to the function through
2.3 The first function walkthrough
need
-
- Write
say_hello
a function, encapsulate three lines of greeting code
- Write
-
- Call the hello code below the function
name = "小明"
# 解释器知道这里定义了一个函数
def say_hello():
print("hello 1")
print("hello 2")
print("hello 3")
print(name)
# 只有在调用函数时,之前定义的函数才会被执行
# 函数执行完成之后,会重新回到之前的程序中,继续执行后续的代码
say_hello()
print(name)
Use F8 and F7 to single step to observe the execution of the following code
- After the function is defined, it only means that the function encapsulates a piece of code.
- If the function is not actively called, the function will not be actively executed
think
Can the function call be placed above the function definition?
- can not!
- Because before calling a function with a function name, you must ensure that you
Python
already know 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 tools
- F8 Step Over can step through the code, and it will directly execute the function call as a line of code
- F7 Step Into can step through the code, if it is a function, it will enter the function
2.5 Documentation comments for functions
- In development, if you want to add a comment to a function, you should use three consecutive function definition
- Write a description of the function between three consecutive pairs of quotation marks
- In 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 , two
03. Function parameters
Exercise needs
- develop
sum_2_num
a function of - The function can implement the sum function of two numbers
The walkthrough code is as follows:
def sum_2_num():
num1 = 10
num2 = 20
result = num1 + num2
print("%d + %d = %d" % (num1, num2, result))
sum_2_num()
Think about what's wrong
The function can only handle the addition of fixed numbers
How to solve?
- If you can pass the numbers that need to be calculated, when calling the function, pass it into the function!
3.1 Use of function parameters
- Fill in the parameters
- Use to
,
separate
def sum_2_num(num1, num2):
result = num1 + num2
print("%d + %d = %d" % (num1, num2, result))
sum_2_num(50, 20)
3.2 The role of parameters
- function , which organizes code blocks with independent functions into a small module, which is called
- The parameters of the function increase the versatility of the function , and can adapt to more data for the same data processing logic
- Inside the function , use the parameters as variables to perform the required data processing
- When the function is called, according to the parameter order defined by the function, the data that you want to process inside the function is passed through the parameters
3.3 Formal and actual parameters
- Formal parameters : When defining a function, the parameters in parentheses are used to receive parameters and are used as
- Actual parameters : When calling a function, the parameters in parentheses are used to pass data into the function .
04. The return value of a function
- In program development, sometimes, it is desirable to tell the caller a result after the execution of a function , so that the caller can do follow-up processing for the specific result.
- The return value is the final result given to the caller after the function completes its work
- Use the
return
keyword return the result - On the calling side of the function, you can use a variable to receive the return result of the function
Note:
return
means return, subsequent code will not be executed
def sum_2_num(num1, num2):
"""对两个数字的求和"""
return num1 + num2
# 调用函数,并使用 result 变量接收计算结果
result = sum_2_num(10, 20)
print("计算结果是 %d" % result)
05. Nested calls to functions
- A function calls another function , which is called function nesting
- If in function , another function
test2
is calledtest1
- Then when the
test1
functiontest1
, the tasks in the function will be executed first. - It will return
test2
totest1
the position where the function was called in and continue to execute the subsequent code
- Then when the
def test1():
print("*" * 50)
print("test 1")
print("*" * 50)
def test2():
print("-" * 50)
print("test 2")
test1()
print("-" * 50)
test2()
Walkthrough of function nesting - printing dividers
Experience the changing needs of work
Requirement 1
- Define a
print_line
function that prints a line consisting*
of
def print_line(char):
print("*" * 50)
Requirement 2
- Define a function that prints a separator line consisting of arbitrary characters
def print_line(char):
print(char * 50)
Requirement 3
- Define a function that prints any number of repetitions of the separator line
def print_line(char, times):
print(char * times)
Requirement 4
- Define a function that can print 5 lines of separators, the separators are required to meet requirements 3
Tip: For changes in requirements at work, you should think calmly, and do not easily modify functions that have been completed before and can be executed normally !
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. Use functions in modules
Modules are a core concept of Python program architecture
- A module is like a toolkit . To use the tools in this toolkit, you need to import the module
- Every source code file
py
ending with the extension is a modulePython
- The global variables and functions defined in the module are the tools that the module can provide to the outside world for direct use
6.1 The first module experience
step
- new
hm_10_分隔线模块.py
hm_09_打印多条分隔线.py
Copy the contents of , except the last line ofprint
code- add a string variable
name = "黑马程序员"
- Create a new
hm_10_体验模块.py
file and write the following code:
import hm_10_分隔线模块
hm_10_分隔线模块.print_line("-", 80)
print(hm_10_分隔线模块.name)
Experience summary
- You can define variables or functions in a Python file
- Then
import
import this module in another file using - After importing, you can use the
模块名.变量
/模块名.函数
method to use the variables or functions defined in this module
Modules make it easy to reuse code that has been written before !
6.2 The module name is also an identifier
- Identifiers can consist of letters , underscores and numbers
- cannot start with a number
- Cannot have the same name as a keyword
Note: If you name your Python file starting with a number you can
PyCharm
not import this module in .
6.3 Pyc files (understand)
C
meanscompiled
compiled
Steps
- Browsing the program directory will find
__pycache__
a directory of - There will be a
hm_10_分隔线模块.cpython-35.pyc
file ,cpython-35
indicating the version of thePython
interpreter - This
pyc
file is used by the Python interpreter to convert the module's source code to bytecodePython
Saving bytecode is an optimization for startup speed
bytecode
Python
When interpreting the source program, it is divided into two steps- First process the source code, compile to generate a binary bytecode
- Then the bytecode is processed to generate machine code
- Once you have the module's bytecode file, the next time you run the program, if the source code has not been modified since the last time the bytecode was saved, Python will load the .pyc file and skip the compilation step
Python
When recompiling, it automatically checks the timestamps of source and bytecode files- 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 ways to import modules, follow-up courses will gradually expand!
Modules are a core concept of Python program architecture