python basics 7 - functions

1. Quick experience of functions

  • 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

2. Basic use of functions

2.1 Definition of functions

The format is as follows:

def function name():

    function encapsulated code
    ……

 

  1. def is the abbreviation of English define
  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 the function name ()

2.3 The first function walkthrough

need

  1. Write a function to say hello say_hello and encapsulate three lines of hello code
  2. Call the hello code below the function
name = " Xiao Ming " 
#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)

 

  • 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 using the function name 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 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 pairs of quotation marks  below the  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

3. Function parameters

Exercise needs

  1. Develop a function of sum_2_num
  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!
  • Fill in the parameters
  • Use between multiple parameters, separate

3.1 Use of function parameters

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 .
  • 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 in a function to return the result
  • On the calling side of the function, you can use a variable to receive the return result of the function

4. The return value of the function

Note: return means return, and 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 result of the calculation is %d " % result)

 

5. Nested Calls of Functions

  • A function calls another function , which is called function nesting
  • If the function test2 calls another function test1
    • Then when the test1 function is called, the tasks in the function test1 will be executed first.
    • It will return to the position where the function test1 was 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 ()

 

Walkthrough of function nesting - printing dividers

Experience the changing needs of work

Requirement 1

  • Define a print_line function to print a
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 requirement 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

 

6. Using 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 Python source code file ending with the extension py is a module
  • 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 my_10_divider module.py
    • Copy the contents of hm_09_print multiple lines.py except the last line of print code
    • add a string variable

name = "programmer"

  • Create a new my_10_experience module.py file and write the following code:

import my_10_divider module

my_10_divider module.print_line("-", 80)
print(my_10_divider module.name)

Experience summary

  • You can define variables or functions in a Python file
  • Then import this module in another file using import
  • After importing, you can use the variable or function defined in this module by using the module name.variable/module name.function

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 the name of the Python file starts with a number , it is not possible to import this module in PyCharm

6.3 Pyc files (understand)

C means compiled compiled

Steps

  1. Browsing the program directory will find a __pycache__ directory
  2. There will be a hm_10_ separator module.cpython-35.pyc file in the directory, cpython-35 represents the version of the Python interpreter
  3. This pyc file is used by the Python interpreter to convert the source code of the module to bytecode

             Python saves bytecode as a startup speed optimization

bytecode

  • Python interprets the source program in 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
  • When Python is recompiled, 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

 

Modules are a core concept of Python program architecture

Guess you like

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