Definition and use of functions
1. Function understanding and definition
Function is a reusable statement group with specific functions. It is an abstraction of functions. Its basic function is to reduce programming difficulty and code reuse.
def <Function name>(<parameter>): <Function body> return <Return value>
2. Function use and call
When calling, the actual parameters shall be given. The actual parameters will replace the parameters in the definition, and the return value will be obtained after the function call.
Function parameter passing:
You can have parameters or not, but you must keep parentheses. You can specify default values to form optional parameters. A non optional parameter means that this parameter must be present when calling the function, preceded by all optional parameters. Optional parameter means that this parameter can not be given. If given, execute the function according to the given parameter. If not, execute the function according to the default parameter.
def <Function name>(<Non optional parameter>, <Optional parameters>): <Function body> return <Return value> def fact(n, m = 1): s = 1 for i in range(1, n+1): s *= i return s//m >>> fact(10) 3628800 >>> fact(10, 5) 725760
Variable parameter definition: the number of parameters received by the design function is variable. First, make sure that the parameters to be given are placed first, and use * b to express the uncertain parameters.
def <Function name>(<parameter>, *b): <Function body> return <Return value> def fact(n, *b): s = 1 for i in range(1, n+1): s *= i for item in b: s *= item return s
When calling a function, it can be passed by location (default) or name:
def fact(n, m = 1): s = 1 for i in range(1, n+1): s *= i return s//m >>> fact(10, 5) >>> fact(m=5, n=10)
Function return value
You can return 0 or more results. Use return to pass the return value. It can have a return value or not.
def fact(n, m = 1): s = 1 for i in range(1, n+1): s *= i return s//m, n, m >>> fact(10, 5) (725760, 10, 5) #Tuple type >>> a, b, c = fact(10, 5)
3. Local and global variables
Local variable: it is a variable used inside the function and is only used inside the function
Global variables: variables used throughout the program
Usage rules:
Local variables and global variables are different variables: for basic data types, whether they have the same name or not, they are different variables. After the function operation, its internal local variables are released. You can use global to use global variables inside the function.
n, s = 10, 100 def fact(n): s = 1 for i in range(1, n+1): s *= i return s print(fact(n), s) >>> 3628800 100 n, s = 10, 100 def fact(n): global s for i in range(1, n+1): s *= i return s print(fact(n), s) >>> 3628800 3628800
If a local variable is a composite data type and is not created inside a function, it is equivalent to a global variable.
ls = ["F", "f"] #Create list def func(a): ls.append(a) returen func("C") print(ls) >>> ["F", "f", "C"] ls = ["F", "f"] #Create list def func(a): ls = [] ls.append(a) returen func("C") print(ls) >>> ["F", "f"]
4. lambda function
lambda function returns the function name as the result. It is an anonymous function. It is only used to define simple functions that can be represented in one line. It is used with caution. It is mainly used as the parameter of some specific functions or methods, as well as some fixed usage methods.
<Function name> = lambda<parameter>: <expression> >>> f = lambda x, y : x + y >>> f(10, 15) 25 >>> f = lambda : "Call succeeded" >>> print(f()) Call succeeded
Example
#Seven segment nixie tube drawing '''Problem disassembly: First, you should learn to draw a line, Then you can draw seven lines, Then how to combine them to get a digital display, Finally, how to get the time and display it.''' import turtle import time def drawGap():#I hope there is a certain interval between nixie tubes turtle.penup() turtle.fd(5) def drawLine(draw): #Drawing single segment nixie tube drawGap() turtle.pendown() if draw else turtle.penup() turtle.fd(40) drawGap() turtle.right(90) def drawDigit(digit):#Draw the number of seven segments according to the number #The core idea is to split each pen, which is needed by those numbers, drop the line when needed, and lift the brush when not needed drawLine(True) if digit in [2, 3, 4, 5, 6, 8, 9] else drawLine(False) drawLine(True) if digit in [0,1,3,4,5,6,7,8,9] else drawLine(False) drawLine(True) if digit in [0,2,3,5,6,8,9] else drawLine(False) drawLine(True) if digit in [0,2,6,8] else drawLine(False) turtle.left(90) drawLine(True) if digit in [0,4,5,6,8,9] else drawLine(False) drawLine(True) if digit in [0,2,3,5,6,7,8,9] else drawLine(False) drawLine(True) if digit in [0,1,2,3,4,7,8,9] else drawLine(False) turtle.left(180) turtle.penup() turtle.fd(20)#Position subsequent numbers def drawDate(data): #Make an agreed mark, such as% Y -% m *% d& turtle.pencolor("red")#Specified year color for i in data: if i == '-' turtle.write('year', font=("Arial", 18, "normal")) turtle.pencolor("green")#Specified month color turtle.fd(40) elif i == '*' turtle.write('month', font=("Arial", 18, "normal")) turtle.pencolor("blue")#Specify Date color turtle.fd(40) elif i == '&' turtle.write('day', font=("Arial", 18, "normal")) else: drawDigit(eval(i)) def main(): turtel.setup(800, 350, 200, 200) turtel.penup() turtle.fd(-300) turtle.pensize(5) drawDate(time.strftime('%Y-%m*%d&', time.gmtime())) #Get time and format turtle.hideturtle() turtle.done() main()
Code reuse and function recursion
Abstract code as a resource:
Code resource: program code is a kind of "resource" used to express computing
Code abstraction: use functions and other methods to give a higher level of definition to the code
Code reuse: the same piece of code can be reused when needed. Generally, functions or objects are used to realize code reuse. Functions establish preliminary abstraction at the code level, while objects are organized and abstracted again on the function.
The core idea of modular design is divide and conquer, that is to divide the program into modules and the expression between modules through function or object encapsulation, including the main program, subroutine and the relationship between subroutines.
Tight coupling: there is a lot of communication between the two parts, which cannot exist independently
Loose coupling: there is little communication between the two parts and can exist independently
The parameters and return values between functions are the communication channels between programs. The clearer the communication channel, the easier it is to reuse the code. Therefore, we want tight coupling within modules and loose coupling between modules.
Function recursion: the way in which function is called in function design. Recursion has two key features:
Chain: recursive chain exists during calculation
Base case: there are one or more base cases (base instances) that do not need to be recursive again
The implementation of recursion needs to combine functions and branch statements. Recursion itself is a function and needs to be described in the way of function definition; Inside the function, you need to use the branch statement to judge whether the input parameter belongs to the base instance.
#Calculate the factorial of n def fact(n): if n == 0 return 1 else: return n*fact(n-1)
#String inversion: output after string s inversion >>> s[::-1] def rvs(s): if s == "": return s else: return rvs(s[1:]+s[0]) #Febrache sequence def F(n): if n == 1 or n == 2: return 1 else: return F(n-1) + F(n-2) #Hanoi Tower problem count = 0 def hanoi(n, src, dst, mid): global count if n == 1 #If there is only one disc print("{}:{}->{}".format(1, src, dst))#Directly transport disc 1 from the beginning to the target count += 1 else: #Suppose we move n-1 disks to the middle disk, we can move the last disk to the target disk hanoi(n-1, src, mid, dst) print("{}:{}->{}".format(n, src, dst)) count += 1 hanoi(n-1, mid, dst, src)
Example
#Koch Snowflake ''' The curve used for fractal is itself an iterative process. ''' #KochDrawV1.py import turtle def koch(size, n): if n == 0: turtle.fd(size)#n=0 draws a straight line else: for angle in [0, 60, -120, 60]: turtle.left(angle) koch(size/3, n-1) def main(): turtle.setup(600, 600) turtle.penup() turtle.goto(-200, 100) turtle.pendown() turtle.pensize(2) level = 3 koch(400, level) turtle.right(120) koch(400, level) turtle.right(120) koch(400, level) turtle.hideturtle() main()
Package applet to form executable: open cmd
pyinstaller -i curve.ico -F KochDrawV1.py
Attached - PyInstaller Library
Convert the. py source code into an executable file without source code. It is a third-party library and requires additional installation( http://www.pyinstaller.org )
Install: open cmd and execute pip install pyinstaller
use:
In the directory where the source code is located, execute pyinstaller - f < file name. Py > through cmd (command line of windows). After completion, three folders will be generated, and there is an exe file with the same name in dist.
Common parameters:
parameter | describe |
---|---|
-h | view help |
–clean | Clean up temporary files during packaging |
-D, --onedir | By default, dist folders are generated |
-F, --onefile | Only separate package files are generated in the dist folder |
-I < icon file name. ICO > | Specifies the icon file used by the packer |