python notes: #012# function

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:
    1. Defining Functions - Encapsulating Independent Functions
    2. 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

  1. new 04_函数project
  2. Copy the multiplication table file you completed earlier
  3. Modify the file and add function definitionsmultiple_table():
  4. Create another file, importimport

02. Basic use of functions

2.1 Definition of functions

The format for defining a function is as follows:

def 函数名():

    函数封装的代码
    ……
  1. defis definethe
  2. The function name should be able to express the function of the function encapsulation code to facilitate subsequent calls
  3. 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

    1. Write say_helloa function, encapsulate three lines of greeting code
    1. 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 Pythonalready 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 + Qto 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

  1. develop sum_2_numa function of
  2. 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
    1. Inside the function , use the parameters as variables to perform the required data processing
    2. 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 returnkeyword return the result
  • On the calling side of the function, you can use a variable to receive the return result of the function

Note: returnmeans 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 test2is calledtest1
    • Then when the test1function test1, the tasks in the function will be executed first.
    • It will return test2to test1the position where the function was called in 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()

Walkthrough of function nesting - printing dividers

Experience the changing needs of work

Requirement 1

  • Define a print_linefunction 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 filepy 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

  • newhm_10_分隔线模块.py
    • hm_09_打印多条分隔线.pyCopy the contents of , except the last line of printcode
    • add a string variable
name = "黑马程序员"
  • Create a new hm_10_体验模块.pyfile 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 importimport 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 PyCharmnot import this module in .

6.3 Pyc files (understand)

Cmeans compiled compiled

Steps

  1. Browsing the program directory will find __pycache__a directory of
  2. There will be a hm_10_分隔线模块.cpython-35.pycfile , cpython-35indicating the version of the Pythoninterpreter
  3. This pycfile is used by the Python interpreter to convert the module's source code to bytecode
    • PythonSaving bytecode is an optimization for startup speed

bytecode

  • PythonWhen interpreting the source program, it is divided into two steps
    1. First process the source code, compile to generate a binary bytecode
    2. 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
  • PythonWhen 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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324600764&siteId=291194637