Article Directory
- 1 Definition and use of functions
- 1.1 Function parameter passing
- 1.2 The return value of the function
- 1.3 Local variables and global variables
- 1.4 Lambda function
- 2 Example: Seven-segment digital tube drawing
- 3 Function recursion
- 4 Use of PyInstaller library
- 5 Example: Koch snowflake package
- 6 Summary
1 Definition and use of functions
The function can have parameters or no parameters, but you must keep the brackets:
- def <function name> (<parameter (0 or more)>):
<function body>
return <return value>
1.1 Function parameter passing
Optional parameter passing : When defining a function, you can specify default values for certain parameters to form optional parameters
- def <function name> (<non-optional parameter>, <optional parameter>):
<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 passing : A variable number of parameters can be designed when the function is defined, using * b to achieve
- 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
>>> fact(5, 2)
240
>>> fact(5, 2, 2, 5)
2400
There are two ways to pass parameters : when the function is called, the parameters can be passed by location or name
>>> def fact(n, m=1):
s = 1
for i in range(1, n + 1):
s *= i
return s//m
>>> fact(10, 5)
725760
>>> fact(m = 5, n = 10)
725760
1.2 The return value of the function
The function can return 0 or more results
- return reserved word is used to pass the return value
- The function may have a return value, or may not have, return may or may 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)
>>> a, b, c = fact(10, 5)
>>> print(a, b, c)
725760 10 5
1.3 Local variables and global variables
- Local variables are placeholders inside the function, which may be the same as global variables but different
- After the function operation ends, the local variables are released
- You can use global reserved words to use global variables inside functions
Local variables are combined data types and not created, equivalent to global variables
1.4 Lambda function
- The lambda function is an anonymous function, that is, a function without a name
- Use lambda reserved word definition, the function name is to return the result
- Lambda functions are used to define simple functions that can be represented on one line
example:
>>> f = lambda x, y : x + y
>>> f(10, 15)
25
>>> f = lambda : "lambda函数"
>>> print(f())
lambda函数
2 Example: Seven-segment digital tube drawing
- Step 1: Draw the digital tube corresponding to a single number
- Step 2: Obtain a string of numbers and draw the corresponding digital tube
- Step 3: Obtain the current system time and draw the corresponding digital tube
import turtle, time
def drawGap(): #绘制数码管间隔
turtle.penup()
turtle.fd(5)
def drawLine(draw): #绘制单段数码管
drawGap()
turtle.pendown() if draw else turtle.penup()
turtle.fd(40)
drawGap()
turtle.right(90)
def drawDight(dight): #根据数字绘制七段数码管
drawLine(True) if dight in [2,3,4,5,6,8,9] else drawLine(False)
drawLine(True) if dight in [0,1,3,4,5,6,7,8,9] else drawLine(False)
drawLine(True) if dight in [0,2,3,5,6,8,9] else drawLine(False)
drawLine(True) if dight in [0,2,6,8] else drawLine(False)
turtle.left(90)
drawLine(True) if dight in [0,4,5,6,8,9] else drawLine(False)
drawLine(True) if dight in [0,2,3,5,6,7,8,9] else drawLine(False)
drawLine(True) if dight in [0,1,2,3,4,7,8,9] else drawLine(False)
turtle.left(180)
turtle.penup()
turtle.fd(20)
def drawDate(data): #data为日期,格式为 '%Y-%m=%d+'
turtle.pencolor("red")
for i in data:
if i == '-':
turtle.write("年", font = ("Arial", 18, "normal"))
turtle.pencolor("green")
turtle.fd(40)
elif i == '=':
turtle.write("月", font = ("Arial", 18, "normal"))
turtle.pencolor("green")
turtle.fd(40)
elif i == '+':
turtle.write("日", font = ("Arial", 18, "normal"))
else:
drawDight(eval(i)) #通过eval()函数将数字变为整数
def main():
turtle.setup(800, 350, 200, 200)
turtle.penup()
turtle.fd(-300)
turtle.pensize(5)
drawDate(time.strftime("%Y-%m=%d+", time.gmtime()))
turtle.hideturtle()
turtle.done()
main()
operation result:
3 Function recursion
Recursion requires recursive formulas and recursive end conditions
Example 1: String inversion
def rvs(s):
if s == "":
return s
else:
return rvs(s[1:]) + s[0]
Example 2: Fibonacci sequence
def f(n):
if n == 1 or n == 2:
return 1
else:
return f(n-1)+ f(n-2)
Example 3: The Hanoi Tower problem The
solution process is as follows:
if n = 1, then move this plate directly from column A to column C.
If n> 1, perform the following three steps:
- Using column C as a buffer, move the (n-1) plates on column A to column B
- Move the last plate on column A directly to column C.
- Using column A as a buffer, move the (n-1) plates on column B to column C.
count = 0
def hanoi(n, src, dst, mid):
global count
if n == 1:
print("{}:{}->{}".format(1, src, dst))
count += 1
else:
hanoi(n-1, src, mid, dst)
print("{}:{}->{}".format(n, src, dst))
count += 1
hanoi(n-1, mid, dst, src)
hanoi(3, "A", "C", "B")
print(count)
4 Use of PyInstaller library
Function: PyInstaller library can convert .py source code into executable file without source code
PyInstaller library installation: (cmd command line) pip install pyinstaller
Simple to use: (cmd command line) pyinstaller -F <file name.py>
Common parameters:
parameter | description |
---|---|
-h | View help |
–clean | Clean up temporary files during packaging |
-D, --onedir | Default value, generate dist folder |
-F, --onefile | Only generate independent package files in the dist folder |
-i <icon file name.ico> | Specify the icon file used by the packager |
example: Use the icon curve.ico as the icon of the executable file
- pyinstaller –i curve.ico –F SevenDigitsDrawV2.py
5 Example: Koch snowflake package
import turtle
def koch(size, n):
if n == 0: # 0阶时是一条直线
turtle.fd(size)
else: # 多阶时,分别针对4段绘制n-1阶科赫曲线
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()
operation result:
6 Summary
Definition and use of functions
- Use the reserved word def to define functions, and lambda to define anonymous functions
- Optional parameters (assign initial values), variable parameters (* b), name transfer
- The reserved word return can return any number of results
- The reserved word global declares the use of global variables, some implicit rules