The so-called function is to organize code blocks with independent functions into a small module, which is called when needed
Many people learn python and don't know where to start.
Many people learn python, after mastering the basic grammar, they don't know where to find cases to get started.
Many people who have done case studies do not know how to learn more advanced knowledge.
So for these three types of people, I will provide you with a good learning platform, free to receive video tutorials, e-books, and course source code!
QQ group: 1097524789
The use of the function involves two steps:
Define function-encapsulate independent functions
Call function-enjoy the results of encapsulation
The function of the function, when developing the program, the use of the function can improve the efficiency of writing and the reuse of code
Walkthrough steps
New 04_Function Project
Copy the previous multiplication table file
Modify the file and add the function definition multiple_table():
Create another file, use import to import and call the function
1
Basic use of functions
Function definition
The format of the defined function is as follows:
def function name():
函数封装的代码
……
def is the abbreviation of define in English
The function name should be able to express the function of the function package code to facilitate subsequent calls
The naming of function names should conform to the naming rules of identifiers
Can be composed of letters, underscores and numbers
Cannot start with a number
Cannot have the same name as the keyword
Function call
Calling a function is very simple, you can call the function through the function name ()
The first function walkthrough
demand
Write a hello say_hello function, encapsulate three lines of hello code
Call the greeting code below the function
What you can still hear in the torrential rain, the bitter things others are doing, doesn't mean you have to do it either.
name = “Komei”
The interpreter knows that a function is defined here def say_hello(): print(“hello 1”) print(“hello 2”) print(“hello 3”)
print(name)# Only when the function is called, the previously defined function will be executed. # After the function is executed, it will return to the previous program and continue to execute the subsequent code say_hello()
print(name)
is executed in a single step F8 and F7 observe the execution process 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
Thinking
Can the function call be placed above the function definition?
Can't!
Because before using the function name to call a 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: say_hello is not defined)
PyCharm's debugging tool
F8 Step Over can execute the code step by step, and will treat the function call as a line of code to execute directly
F7 Step Into can step into the code, if it is a function, it will enter the function
Documentation notes for functions
During development, if you want to add a comment to a function, you should use three consecutive pairs of quotation marks below the defined function
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, there should be two blank lines above the function definition and other code (including comments)
2
Function parameters
Rehearsal needs
Develop a function of sum_2_num
Function can realize the sum function of two numbers
The exercise 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 the problem
The function can only handle the addition of fixed values
How to solve?
It would be great if the number to be calculated can be passed into the function when calling the function!
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))
(50, 20 is) sum_2_num
action parameter
Function, which organizes code blocks with independent functions into a small module, which is called when needed
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 required data processing
When the function is called, according to the parameter order defined by the function, pass the data that you want to process inside the function through parameters
Formal and actual parameters
Formal parameters: When defining a function, the parameters in parentheses are used to receive parameters and are used as variables inside the function
Actual parameters: when calling a function, the parameters in parentheses are used to pass data to the function
3
The return value of the function
In program development, sometimes, you want to tell the caller a result after a function is executed, 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 has completed its work
Use the return keyword in the function to return the result
The calling function party can use variables to receive the return result of the function
Note: return means return, subsequent code will not be executed
def sum_2_num(num1, num2): """Sum of two numbers"""
return num1 + num2
Call the function and use the result variable to receive the calculation result result = sum_2_num(10, 20)
print("The calculation result is %d"% result)
4
Nested function call
A function is called another function, this is the function nested call
If in function test2, another function test1 is called
Then when the test1 function is called, the tasks in the function test1 will be executed first
Will return to the location where the function test1 is called in test2 and continue to execute 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 dividing line
Experience the changing needs in work
Demand 1
Define a print_line function to print a dividing line composed of *
def print_line(char):
print("*" * 50)
demand 2
Define a function to print a separator line composed of arbitrary characters
def print_line(char):
print(char * 50)
requirement 3
Define a function that can print any number of repeated dividers
def print_line(char, times): print(char * times)
Demand 4
Define a function that can print a 5-line divider, and the divider must meet the requirements 3
Reminder: You should calmly think about changes in requirements during work, and do not easily modify the 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
5
Use functions in modules
Module is a core concept of Python program architecture
A module is like a toolkit. If you want to use the tools in this toolkit, you need to import the import module
Every Python source code file ending with the extension py is a module
The global variables and functions defined in the module are tools that the module can provide to the outside world for direct use
The first module experience
step
New hm_10_ divider module.py
Copy the content in hm_09_print multiple dividers.py, except the last line of print code
Add a string variable
name = "I am a small test"
Create a new hm_10_experience module.py file, and write the following code:
import hm_10_divider module
hm_10_divider module.print_line("-", 80)print(hm_10_divider module.name)
Experience summary
You can define variables or functions in a Python file
Then use import in another file to import this module
After importing, you can use module name, variable/module name, function, and use the variable or function defined in this module
Modules allow the code once written to be reused easily!
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 the keyword
Note: If you start with a number when naming a Python file, you cannot import this module in PyCharm
Pyc file (understand)
C means compiled
Steps
Browsing the program directory will find a pycache directory
There will be a hm_10_separator module.cpython-35.pyc file in the directory, cpython-35 represents the version of the Python interpreter
This pyc file is converted into bytecode by the Python interpreter.
Python saves bytecode in this way as a startup speed optimization
Bytecode
Python is divided into two steps when interpreting the source program
First process the source code, compile and generate a binary bytecode
After processing the bytecode, the machine code that the CPU can recognize will be generated
After having the bytecode file of the module, the next time the program is run, if the source code has not been modified after the bytecode was saved last time, Python will load the .pyc file and skip the compilation step
When Python is recompiled, it will automatically check the timestamp of the source file and bytecode file
If you modify the source code again, the bytecode will be automatically recreated the next time the program is run