Recursive calls, higher-order functions, function scopes, Python built-in functions, adorners, modules, random, JSON strings, and accumulation
First, recursive call
A recursive call is a function that calls itself, calling itself up to 999 times.
Features: 1. There must be a clear end condition;
2. Each time a deeper level of recursion is reached, the problem size should be reduced compared to the previous recursion;
3. Recursive efficiency is not high, it is recommended to use less recursion
def Test (): N =int (input ( " please input a number: if n%2== 0: return True print ( " The input is not even " ) test () even =test # Test () #函数即变量, Test is the memory address of the function, test () executes the test function even () # Even and test point to the same memory address, so the two of them are the same
Second, higher order function
A higher-order function, which is a function's argument, is a function name (a function is a variable).
def Add (z/y): res=z (x) +Z ( y)return resprint(' 98 ','+ ', int))
Three, function scope
The scope of the function is the nearest principle, looking out from inside. If you have a function, you can use it directly, and if not, you will find it in its parent function. (Note: The function will only be executed if it is called)
defWarpper ():#1Name='Watermelon' defDeco ():#2Name ='Strawberry' defHe ():#3 Print('The innermost fruit is%s'%name)Print('the middle of the fruit is%s'%name) He ()#function is executed only if it is calleddeco ()Print('The outermost fruit is%s'%name) Warpper ()
Iv. python built-in functions
1.print (bool (' s ')) #把一个对象转换成布尔类型
2.int () #整型
3.float () #小数
4.str () #字符串
5.dict () #字典
6.list () #列表
7.set () #集合
8.tuple () #元组
9.print (Round (11.12345,3)) #取小数位数 (example for taking 3 decimal places)
10.print (sorted ([2,12,35,5,4,7,19],reverse=false)) #排序
11.print (Max (111,22,334,4,7,9)) #取最大值
12.print (List (filter (func,[0,1,2,3,4))) #根据前面的函数处理逻辑, processing each element in the subsequent iteration of the object, in turn, returns true to save
13.print (List (map (func,[0,1,2,3,4)))) #根据前面的函数处理逻辑, sequentially processing each element in the subsequent iteration of an object, saving the result returned by the previous function
14.print (dir (' a ')) #打印传入对象的可调用方法
15.print (Callable (func)) #判断传入的对象是否可以调用
16.print (BIN) #十进制转二进制
17.print (Oct) #转八进制
18.print (hex) #转十进制
19.print (Chr (98)) #打印数字对应的ascii码
20.print (Ord (' B ')) #打印字符串对应的ascii码
21.print (eval (' a=1 ')) #执行python代码, can only perform simple, define data types and operations
22.print (EXEC (' Def a ():p ') ') #执行python代码
23.print (Globals ()) #返回程序内所有的变量, a dictionary is returned, and the local variables inside the function do not return
24.print (Locals ()) #返回局部变量
25.print (All ([1,2,3,4])) #判断可迭代的对象里面的值是否都为真
26.print (Any ([1,2,3,0])) #判断可迭代对象里面的值是否有一个为真
Five, decorative device
Features: Nested inside a function defines a function, a higher order function.
Function: Add a new function to the function without changing the calling mode and the entry parameters of the original function.
Import TimedefTimer (func):defDeco (*args,**kwargs):#*args,**kwargs The parameters used to receive incoming functionsStart_time =time.time () Res= Func (*args,**kwargs)#Get return valueEnd_time =time.time ()Print('Runtime', end_time-start_time)returnResreturnDeco@timerdefHello (name):Print('Hello%s'%name) Time.sleep (1)#hello=timer (Hello) #等同于上方的 @timerHello' World')
Six, module
The essence of the module is a python file
#model.pydefrun ():Print('Run ...')defrun1 ():Print('run1***')defrun2 ():Print('run2!!!') name= 5Print('66666')
Three ways to call the module
# Way One: Import modelmodel.run1 () model.run2 () Model.run ( ) # Way Two: from Import run,run1 # When importing only one function , run () run1 ()# method Three: from Import * # Imports all functions from a module, this method is not recommended with run () run1 () run2 ( )
When importing the module, Python first looks for the module in the current directory, and if the current directory does not have the file, it will go to the directory inside the environment variable. If the module needs to be called in a different directory, the following methods are available:
from Import Hello from Import He Import Syssys.path.append (R'E:\byz_code') # Adding environment Variables Print (Sys.path) # look at the system environment variable he ()
Vii. Random
1.print (Random.randint (1,20)) #随机取整数
2.print (Random.choice ([1,2,3,4,5])) #随机取一个元素 (data is an iterative object)
3.print (random.sample (' Hello ', 3)) #从序列中随机取几个值, returns a list
4.print (Random.unform (1,999)) #随机取浮点数, can be specified range
5.x=[1,2,3,4,5]
Random.shuffle (x) #洗牌, break order, change the value of the original list
Print (x)
6.print (Random.random ())
Eight, JSON string
The JSON and Python dictionary types are similar, but the JSON can only be double quotes, not single quotes.
The JSON string is actually a string.
Dump and dumps are dictionary to JSON
Load and loads are JSON to dictionary
jsons='{' name ': ' Python ', ' How ': ' I love '}'Json_d=json.loads (jsons)#JSON string (string) into a dictionary, the loads method is to turn JSON into a dictionaryPrint(Json_d) FR=open ('Users') Json_dict=json.load (FR)#The JSON string (string) turns into a dictionary, the Load method passes in a file object, and the Load method automatically reads the contents of the file and then turns it into a dictionaryPrint(json_dict) d={'Admin': {'Password':'123456',' Money': 80000},'HHH': {'Password':'123456',' Price':'90000'}}d_json=json.dumps (d)#Turn the dictionary into a JSON string (string)Print(D_json) FW=open ('Users.json','W') Json.dump (D,FW)#The dictionary goes to JSON and writes to the file
Nine, accumulate
Import time
Now_time=time.strftime ('%y-%m-%d%h:%m:%s ') #获取当前时间
Print (Now_time)
Python Basics Four