Python-based functions and modules

Keywords: Python Pycharm less

Basic use of functions

  • Definition of a function: A block of code with independent functions is organized into a small module and called when needed. In other words, functions are organized and reusable code segments for single or related functions.
  • Function use: 1. Define function; 2. Call function.
  • Function function: can improve the modularity of the application, and code reuse.
  • Create your own functions, called user-defined functions.

Fast Experience of Functions

Define a function in one py file, import a function in another file and call a function.

Define function:
hello_func.py

def hello():
    print("hello world")
    print("hello python")

Call function:
sayhello.py

import hello_func
hello_func.hello()

Grammatical Format of Function Definition

def function name ():
    Encapsulated function code

Naming of functions

  • Function name, should be known by name
  • Naming rules for identifiers should be complied with
  • It consists of letters, numbers and underscores.
  • Can't start with numbers
  • Cannot rename with keywords

Call of function

The direct function name () is enough; the calling format and examples are as follows:

# Function name ()
sayhello()

Function drill

def say_hello():
    print("hello world 1")
    print("hello world 2")
    print("hello world 3")

say_hello()

Notes for Functions

  1. Functions are not run after they are defined. They are encapsulated. To use functions, functions need to be called.

  2. When the breakpoint debugging passes through the function, it will not execute, it will skip. Only when the function is called later, it will execute the code in turn. After execution, it will return to the code after calling the function.

  3. Define and call first; call first if you don't define a function, and you will get an error; so you should define a function first, and then call a function.

  4. f8 and f7 step-by-step and step-in; f8 step-by-step execution, through the function call will directly execute the entire function without entering the interior;
    When f7 is executed step by step, it will be executed step by step inside the function when it passes through the function call.

Document Annotations for Functions

In the first line of function definition, three pairs of double quotation marks are added, and text annotations are made in the middle of the double quotation marks.
You can use ctrl+q at the function call to view the function description.
The notes are as follows:

def say_hello():
    """Output three greetings"""
    print("hello Dawn 1")
    print("hello Dawn 2")
    print("hello Dawn 3")

Parameters and Return Values of Functions

Examples of parametric-free functions

def sum2num():
    num1 = 10
    num2 = 20
    s = num1 + num2

    print("%d and%d And for%d" % (num1, num2, s))


sum2num()

Functions without parameters can only compute fixed numbers, which is too rigid and ineffective.

Use of Function Parameters

def sum2num(num1, num2):
    """Summing and outputting the two incoming parameters"""
    s = num1 + num2
    print("%d and%d And for%d" % (num1, num2, s))


sum2num(10, 20)  # The sum of 10 and 20 is 30
sum2num(30, 45)  # The sum of 30 and 45 is 75

Use of parameters: Fill in the parentheses after the function name, and separate the parameters by commas.

The role of parameters:
Increase the generality of function, true poison with the same data processing logic, can adapt to more data.
1. In the function, the parameters are used as variables to process the data needed.
2. When calling a function, according to the order of parameters defined by the function, the data that you want to process inside the function is passed through the parameters.

Formal and practical parameters

When defining a function, the parameters transferred are called formal parameters, which are used to receive parameters and are used as variables inside the function.
When calling a function, the parameters passed are called arguments, which are used to transfer data to the inside of the function.
For example:

def sum2num(num1, num2):  # Here's the formal parameter, the formal parameter, a shelf, and the internal use of the function, all of which are the formal parameters.
    s = num1 + num2
    print("%d and%d And for%d" % (num1, num2, s))


sum2num(10, 20)  # Here's the argument, which is the actual transmitted parameter.
sum2num(30, 45)  # Here's the argument, which is the actual transmitted parameter.

Function return value

  • After the function is executed, the result is returned to the caller's function, which facilitates the caller to process the returned result accordingly.
  • If you want to return the result in the function, you can use a return plus the result you want to return.
  • After calling the function, you can receive the result with a variable if you want it to return.

An example of the return value of the receiving function

def sum2num(num1, num2):
    """Summing the two parameters passed in and returning the result"""
    s = num1 + num2
    # You can use the return value to tell the caller the result of the calculation
    return s


# The return result of a function can be received with a variable
result = sum2num(10, 20)
print("The results are as follows:%d" % result)

Notes for the return keyword: return means return, and the following function code will not be executed (unreachable). Be careful not to write code under return

Nested calls to functions

Examples of nested function calls

An example of nested calls to functions

def test1():
    print("*"*50)


def test2():
    print("-"*50)
    test1()
    print("+"*50)


test2()
# The results of implementation are as follows
# --------------------------------------------------
# **************************************************
# ++++++++++++++++++++++++++++++++++++++++++++++++++

Printing examples of parameters and splitting lines

# Version 1
# def print_line():
#     print("*" * 50)
# print_line()


# Version 2
# def print_line(char):
#     print(char * 50)
# print_line("-")

# Version 3
def print_line(char, times):
    print(char * times)
print_line("hi ", 50)

Examples of printing multi-line splitters

def print_line(char, times):
    print(char * times)


def print_lines():
    row = 1
    while row <= 5:
        print_line("-", 50)
        row += 1


print_lines()

Example of Printing Splitting Lines on Demand

def print_line(char, times):
    print(char * times)


def print_lines(char, times, lines):
    row = 1
    while row <= lines:
        print_line(char, times)
        row += 1


print_lines("-", 40, 6)
print_lines("+", 50, 6)

Adding documentation comments to functions

When the parameters are too many or too long to look at the code, it is very likely to forget what each parameter represents, so it is necessary to add document comments.
There are two ways to add function document annotations:

  1. When the function is finished, add three pairs of double quotation marks on the next line of def, and return, the system will automatically generate part of the annotations with function parameters, plus its own annotations.
  2. Click on the function name, move the mouse to the light bulb, there will be a small triangle, Click to find the function to add short document comments, and then add their own comments.

The effect of adding document comments is as follows:

def print_line(char, times):
    """
    :param char:Characters for segmentation
    :param times:Number of split characters per line
    :return:
    """
    print(char * times)


def print_lines(char, times, lines):
    """
    //Print partition line according to customer's requirement, completely customize how many lines, what separators, how many separators per line
    :param char: Characters for segmentation
    :param times: Number of split characters per line
    :param lines: Number of rows printed on partition lines
    :return:
    """
    row = 1
    while row <= lines:
        print_line(char, times)
        row += 1


print_lines("-", 40, 6)
print_lines("+", 50, 6)

Introduction of Modules

Module is a core concept of Python program architecture.
Modules are like a toolkit, and the functions and variables inside are tools.

The concept of module

All source files ending with. py are a module, and the [global] variables and functions defined in the file can be used by the outside world on the premise that import import module is used.

Exercise of modules

Create two functions and a global variable in one file, and import the first file in another file. A function calls a function, and a variable calls a variable.

Define function:
hello_func.py

def hello():
    print("hello world")
    print("hello python")

name = "Xiao Ming"

Call function:
sayhello.py

import cp_01hello_func

hello_func.hello()
hello_func.name

Note: Module names are also identifiers, and you need to follow the naming rules for identifiers.
If you start with a number when naming a py file, you can't call this module in pycharm, and you will get an error.

pyc file improves program performance (just understand)

When we import a module, the system checks whether there is a compiled cache file for this module. If not, it creates and does nothing. Because the module file is pre-compiled and cached, we do not need to re-execute the module line by line when we call it, but use it directly.
Why do you precompile modules into binary files? Because the module has been tested code, and less modification, so it can be pre-compiled, even if occasionally modified, the program can help us to detect and recompile new binary files.

Posted by duke on Thu, 25 Apr 2019 10:45:35 -0700