First, recursive call
1. A function call itself is recursive call, at most one function recursively call themselves 999 times, more than will be wrong
2. Recursion must have a definite end condition
3. Each time a deeper level of recursion is reached, the problem size should be reduced compared to the previous recursion
4. Recursive efficiency is not high, use less recursion
eg
def test1 ():
num = Int (input (' Please enter a number: '))
If num%2==0: #判断输入的数字是不是偶数
Return True #如果是偶数的话, the program exits, returns True
Print (' Not even please re-enter! ‘)
return test1 () #如果不是偶数的话继续调用自己, enter a value
Test1 () #这样为什么不返回return
# Print (Test1 ()) #调用test
second, higher order function
1. If the argument of a function is a function name, then this function is the higher order function
2. function is variable
eg
def hello (name):
Print (name)
New_hello = Hello
Print (type (hello))
Print (Type (New_hello))
Hello (' hello.. ')
New_hello (' New_hello ')
EG1:
#如果不明白函数即变量, just look here.
def add (x, Y, z): #如果一个函数的入参是一个函数名的话, then this function is the higher order function
#参数z是要传入一个函数名
res = Z (x) +z (y)
return res
Print (Add (' 98 ', ' + ', int))
third, the use of Python built-in functions1. Scope
1?? function of the scope, is the nearest principle, from the inside out, if you have in the function, take the past, if you do not have the function inside, go to its parent function inside find
2?? function is executed only if it is called
eg
name = ' Python '
Def warpper ():
name = ' Wubing '
Def deco ():
Name = ' Chen Winter melon '
Print (' I'm inside%s '%name)
Def HHH ():
name = ' Zhangying '
Print (' www%s '%name)
HHH ()
Deco ()
Print (' name outside ' is%s '%name)
Warpper ()
2, the decorative device
1?? Functions can also be nested within a function to define a function
2?? Higher order functions
A. The adorner is plainly a function nesting + higher order function
B. The role of the adorner is not to change the original function of the call mode, in the case of the argument to add new functions
C. Surreptitiously add new functions to the function, but do not change the original function
EG1:
Import time
def run ():
Print (' Run.. ‘)
Time.sleep (1)
def run_time (func):
Start_time = Time.time () #开始时间
Func ()
End_time = Time.time () #结束时间
Print (' Run function is ', end_time-start_time)
Run_time (Run)
EG2:
Import time
def timer (func):
def deco (*args,**kwargs):
#*args,**kwargs the parameters used to receive incoming functions
Start_time = Time.time ()
res = func (*args,**kwargs)
End_time = Time.time ()
Print (' Runtime ', end_time-start_time)
return res
Return deco
@timer #==run
def run ():
Print (' Run.. ‘)
Time.sleep (1)
Run = timer (run) #run = = Deco
Run ()
@timer
def run2 (name):
Print (name)
Time.sleep (2)
Run2 (' Niuhanyang ')
The function above actually returns a function name.
1. When calling the timer function, to pass in a method name, the timer function defines a function inside the function called Deco, and within the function Deco function calls the method passed in the timer.
2.run saved is Deco,deco is a function, call R is call Deco
3. Built-in functions
Print (All ([1,2,3,4])) #判断可迭代的对象里面的值是否都为真
Print (Any ([0,0,0,0,0])) #判断可迭代的对象里面的值是否有一个为真
Print (BIN) #十进制转二进制
The following functions are mandatory type conversions
Print (bool (' s ')) #把一个对象转换成布尔类型
Int () #整形
Float () #小数
STR () #zifuc
Dict () #字典
List () #列表
Set () #集合
Tuple () #元组
def func ():
Pass
Print (Callable (func)) #判断传入的对象是否可调用
Print (CHR (98)) #打印数字对应的ascii
Print (ord (' B ')) #打印字符串对应的ascii码
Print (Dict (a=1,b=2)) #转换字典
Print (dir (' a ')) #打印传入对象的可调用方法
Print (eval (' a=1 '))
Execute Python code, only perform simple, define data types and operations
Print (EXEC (' Def a ():p ') ') #执行python代码
def func (num):
Name = ' 88 '
Print (Locals ())
Print (Globals ())
Return num
Func (11)
Print (List filter (func,[0,1,2,3,4))) #在python3里面这么用是没问题
Print (filter (func,[0,1,2,3,4])) #在python2里面这么用是没问题
Filter (func,[1,2,3,4])
Based on the previous function processing logic, each element in the subsequent iteration of the object can be iterated, returning true to save
Print (List (map (func, [0, 1, 2, 3, 4]))
According to the previous function processing logic, the subsequent iteration can iterate over each element inside the object, saving all the results returned by the previous function </span>
Print (Globals ()) #返回程序内所有的变量, a dictionary is returned, and the local variables inside the function do not return
Print (Locals ()) #返回局部变量
Print (Hex (111)) #数字转成16进制
Print (max (111,12,13,14,16,19)) #取最大值
Print (Oct (111)) #把数字转换成8进制
Print (Round (11.1198,2)) #取几位小数, rounding
Print (sorted ([2,31,34,6,1,23,4],reverse=false)) #排序
Dic={1:2,3:4,5:6,7:8}
Print (sorted (Dic.items ())) #按照字典的key排序
Print (sorted (Dic.items (), Key=lambda x:x[1]) #按照字典的value排序
__import__ (' decorator ') #导入一个模块
The following is necessary.
Print (bool (' s ')) #把一个对象转换成布尔类型
Int () #整形
Float () #小数
STR () #zifuc
Dict () #字典
List () #列表
Set () #集合
Tuple () #元组
Print (Round (11.1198,2)) #取几位小数, rounding
Print (sorted ([2,31,34,6,1,23,4],reverse=false)) #排序
# Print (max (111,12,13,14,16,19)) #取最大值
Print (List filter (func,[0,1,2,3,4))) #在python3里面这么用是没问题
Print (filter (func,[0,1,2,3,4])) #在python2里面这么用是没问题
Filter (func,[1,2,3,4])
Based on the previous function processing logic, each element in the subsequent iteration of the object can be iterated, returning true to save
Print (List (map (func, [0, 1, 2, 3, 4]))
According to the previous function processing logic, the subsequent iteration can iterate over each element inside the object, saving all the results returned by the previous function </span>
four, the common module
1. which module will be used to import which module
eg
Import model
#import的本质就是把这个python从头到尾执行一遍
MODEL.RUN1 ()
Model.run2 ()
Model.run ()
From model import RUN,RUN1
#只导入某个函数的时候
Run ()
RUN1 ()
From model Import *
From MODEL2 Import *
#这种你不要用, import all the functions from a module
Run ()
RUN1 ()
Run2 ()
From model import Name
Import Sys
This is in the other directory.
Sys.path.append (R ' E:\byz_code ')
From Day4.set1 import HHH
HHH ()
2, Package and folder is the difference between the package is a __init__.py, in Python2, if you want to import other folders under the Python file, then must be a package, python3 do not need, just the folder on the line
3, environment variables are used to let you in any directory can use this command
4, the Import module, Python first in the current directory down to find this module, if in the current
5, the directory does not find the file, then go to the directory inside the environment variable to find
eg
Import Sys
Print (Sys.path) #看系统环境变量
Import model
Model.run ()
Vi.import of random
# Print (Random.random ()) # Random floating-point number, default 0-1, cannot specify range
# Print (Random.randint (1)) # Random integer
# Print (Random.randrange (1)) # randomly generates a range
# Print (Random.choice ([1,2,3,4,5]) # randomly take an element
# Print (Random.sample ([1,2,3,4, ' 6 '], 3) # Randomly takes a few elements from a sequence and returns a list
# Print (Random.uniform (1, 88888)) # Random floating point number, can specify range
x = [1, 2, 3, 4, 5, 6]
Random.shuffle (x) # Shuffle, scramble order, will change the value of the original list
Seven, import string
# print (string.ascii_letters + string.digits) # All the numbers and letters
# Print (Random.randint (1)) # Random integer
#print (Random.choice ([1,2,3,4,5]) # randomly take an element
#print (random.sample (' Hello ', 3)) # Randomly takes several elements from a sequence and returns a list
#print (Random.uniform (1, 88888)) # Random floating point number, can specify range
# x = [1, 2, 3, 4, 5, 6]
# random.shuffle (x) # Shuffle, scramble order, will change the value of the original list
# Print (x)
Eight, import JSON
1.json and Python dictionary types, but JSON can only be double quotes, not single quotes
2.json strings are actually a string
Json_str = "" "
{
"username": "Niuhanyang",
"passwd": 123456,
"Flag": True
}
"""
# fr = Open (' users ')
# json_dic = json.loads (JSON_STR)
3.json Strings (string) into a dictionary, the loads method is to turn JSON into a dictionary
# json_dic_file = Json.load (FR)
4.json Strings (strings) into a dictionary, the load method is to pass in a file object, and then the load method automatically reads the contents of the file and then turns into a dictionary
# Print (json_dic_file)
# Print (Type (json_dic_file))
D = {
"HHH": {
"Price": "90000",
"Password": "123456"
},
"Admin": {
"Password": "123456",
"Money": 8000
}
}
# FW = open (' Users.json ', ' W ')
# dic_str = Json.dumps (d)
#把字典变成json串 (String)
# Json.dump (D,FW)
# Print (DIC_STR)
# Print (Type (DIC_STR))
5.json can be used in dictionaries and lists
6.dump and dumps dictionary to JSON string
7.load and loads are JSON string -to-dictionary
8. With S and strings, without s and file objects
V. Python functions, adorners, built-in functions, JSON, and modules