Catalog
One 、 Function basis
1. Fast experience of functions
1.1 Quick experience
So called functions , Is to organize code blocks with independent functions into a small module , Called when needed
There are two steps to using the function :
a. Defined function -- Encapsulate independent functions
b. Call function -- Enjoy the results of packaging
Function function , When developing programs , Using functions can improve the efficiency of writing and code reuse
# Encapsulated 99 multiplication table
def multiple_table():
row = 1
while row <= 9:
col = 1
while col <= row:
# print("*", end="")
print("%d * %d = %d " % (col, row, col * row), end="\t")
col += 1
print("")
row += 1
# Call function
import file name
file name .multiple_table()
2. The function basically uses
2.1 Definition of function
The format of defining a function is as follows :
def Function name ():
Function encapsulated code
......
a.def It's English define Abbreviation
b. The function name should be able to express the function of the function encapsulated code , Convenient for subsequent calls
c. The naming of function names should conform to the naming rules of identifiers :
It can be made of letters 、 Underline and numbers make up
Cannot start with a number
Cannot have the same name as the keyword
2.2 Function call
It's easy to call functions , By function name () Can complete the call to the function
2.3 The first function walkthrough
"""
demand :
1. Write a greeting say_hello Function of , Package three lines of greeting code
2. Call the Hello code below the function
"""
def say_hello():
print("hello 1")
print("hello 2")
print("hello 3")
say_hello()
After defining the function , It just means that this function encapsulates a piece of code
If you don't call the function actively , Functions are not executed proactively
reflection :
Can function calls be placed above function definitions ?
You can't ! Because before calling a function with a function name , It must be ensured that pyhton We already know that functions exist , Otherwise, the console will prompt :NameError:name 'say_hello' is not defined( Name error :say_hello The name is not defined )
2.4 PyCharm Debugging tools for
F8 Step Over You can step through the code , Think of function calls as a line of code that executes directly
F7 Step Into You can step through the code , If it's a function , It goes inside the function
2.5 Documentation notes for functions
In development , If you want to annotate a function , It should be below the definition function , Use three consecutive pairs of quotation marks
Write a description of the function between three consecutive pairs of quotation marks
At the function call location , Using shortcut keys CTRL+Q You can view the description of the function
Be careful : Because the function body is relatively independent , Above the function definition , And other code ( Including comments ) Leave two blank lines
3. The parameters of the function
"""
demand :
1. To develop a sum_2_num function
2. Function can realize the summation function of two numbers
"""
def sum_2_num():
num1 = 10
num2 = 20
result = num1 + num2
print("%d + %d = %d" % (num1,num2,result))
sum_2_num()
The problem is : The function can only handle the addition of fixed values
3.1 The use of function parameters
Fill in the parameters inside the parentheses after the function name , Use... Between multiple parameters , Separate
def sum_2_num(num1,num2):
result = num1 + num2
print("%d + %d = %d" % (num1,num2,result))
sum_2_num(50,20)
3.2 Function of parameters
function , Organize code blocks with independent functions into a small module , Called when needed
The parameters of the function , Increase the generality of functions , For the same data processing logic , Can be applied to more data
a. Inside the function , Use parameters as variables , Do the necessary data processing
b. When a function is called , In the order of the parameters defined by the function , Put the data you want to care about inside the function , Pass through parameters
3.3 Formal parameters and actual parameters
Shape parameter : When defining a function , Parameters in parentheses , It is used to accept parameters , Used as a variable inside a function
Actual parameters : When you call a function , Parameters in parentheses , It is used to transfer data to the function
4. The return value of the function
In program development , occasionally , You'll want a function to finish executing , Tell the caller a result , So that the caller can do subsequent processing for specific results
The return value is after the function completes its work , Finally, a result for the caller
Use... In functions return Keywords can return results
Call function side , You can use variables to receive the return result of a function
Be careful :return Said to return to , No subsequent code will be executed
def sum_2_num(num1,num2):
""" The sum of two numbers """
return num1 + num2
# Call function , And use result Variables receive calculation results
result = sum_2_num(10,20)
print(" The result is %d" % result)
5. Nested calls to functions
Another function is called in one function , This is the nested function call
If the function test2 in , Another function was called test1, Then execute to call test1 Function time , I'll start with the function test1 All the tasks in are finished , Will return to test2 Calling function in test1 The location of , Continue with the subsequent code
def test1():
print("*" * 50)
print("test 1")
print("*" * 50)
def test2():
print("-" * 50)
print("test 2")
test1()
print("-" * 50)
test2()
Function nesting walkthrough -- Print separator lines
"""
demand : Define a function that can print separator lines composed of arbitrary characters
"""
def print_line(char):
print(char * 50)
print_line("-")
"""
demand : Define a function that can print separator lines for any number of repetitions
"""
def print_line(char,times):
print(char * times)
print_line("-",50)
"""
demand : Define a function that can print 5 Line separator
"""
def print_line(char,times):
""" Print single line separator
:param char: Separator character
:param times: Repeat the number
"""
print(char * times)
def print_lines(char,times):
""" Print multiline separator
:param char: The separator character used by the separator
:param times: The number of times the separator is repeated
"""
row = 0
while row < 5:
print_line(char,times)
row += 1
print_lines("-",20)
6. Use the functions in the module
The module is python A core concept of program architecture
Modules are like toolkits , To use the tools in this toolkit , You need to import import This module , Each with an extension py At the end of the python The source code file is a module
Global variables defined in the module 、 Functions are tools that modules can provide to the outside world for direct use
6.1 The first module experience
step :
newly build xcc_02_ Divider module .py, The contents are as follows :
def print_line(char,times):
print(char * times)
def print_lines(char,times):
row = 0
while row < 5:
print_line(char,times)
row += 1
name = " Black horse programmer "
newly build xcc_02_ Experience module .py, The contents are as follows :
import xcc_02_ Divider module
xcc_02_ Divider module .print_line("-",80)
print(xcc_02_ Divider module .name)
Experience summary :
Can be in a python Define variables or functions in a file
Then use... In another file import Import this module
After importing , You can use the module name . Variable / Module name . How to function , Use the variables or functions defined in this module
Modules can make the code that has been written easy to reuse !
6.2 The module name is also an identifier
Identifiers can be made up of letters 、 Underline and numbers make up
Cannot start with a number
Cannot have the same name as the keyword
Be careful : If you're giving python When the file is named , Starting with a number cannot be in pycharm By importing the
6.3 pyc file ( understand )
c yes compiled Compiled means
Operation steps :
a. If you browse the program directory, you will find a _pycache_ The catalog of
b. There will be a xcc_02_ Divider module .cpython-38.pyc file ,cpython-38 Express python Version of interpreter
c. This pyc File is made up of python The interpreter converts the source code of the module into bytecode
python This saves bytecode as an optimization of startup speed
Bytecode :
python There are two steps in interpreting the source program
a. Deal with the source code first , Compile and generate a binary bytecode
b. Then process the bytecode , Generation CPU Recognizable machine code
With the bytecode file of the module , The next time you run the program , If the source code has not been modified since the bytecode was last saved ,python Will load .pyc File and skip the compile step
When python When recompiling , It automatically checks the time stamps of the source and bytecode files
If you change the source code again , Next time the program runs , Bytecode will be automatically recreated