In this article, let's talk about functions and files . Functions play a very important role in programming , We can combine several statements to form a function , It can accept incoming parameters , And generate output after internal relevant calculation , Encapsulating statements into functions is to avoid code clutter caused by repeated use of several statements , Make the code more concise and observable .
File operation mainly introduces some methods of reading and writing files , And the differences of each method and matters needing attention , Finally, I will introduce the use of pickle How modules store complex data .
The function mainly includes two aspects :
• Built in functions
• Custom function
The built-in function is python Some of the functions that come with it , We just need to pass in relevant parameters to the function to call ,print Is the most basic 、 The most typical built-in function ; The custom function needs us to follow our own requirements , Encapsulate several statements to form a new function .
Let's introduce some attribute words by customizing a function to calculate the volume of the box :
In [1]: def vol(length,width,height): ...: volume = length*width*height ...: return volume
In the above three lines of code, you need to know :
•def: Define keywords for functions
•length,width,height: The formal parameter of the function
•return: The return value of the function
After building a custom function , You can use the function name ( Actual parameters ) Call function in the way of :
In [2]: vol(2,2,3) Out[2]: 12
When passing in parameters, you should pay attention to , Arguments and formal parameters must correspond exactly , For example, location 、 Number and so on , Otherwise, an error will be reported .
In [4]: vol(2,2) TypeError: vol() missing 1 required positional argument: 'height'
If you want to change the order of parameters , Then you need to specify which parameter to pass the value for :
In [8]: vol(width=3,length=4,height=5) Out[8]: 60
Function parameters can also specify default values , If we put the above vol Function height The default value of the parameter is set to 2:
In [6]: def vol(length,width,height=2): ...: volume = length*width*height ...: return volume ...: In [7]: vol(2,2) Out[7]: 8
At this time, only to vol Pass in two arguments in the function , It can be found that there is no error reported , And the return value is 8. That is, if a formal parameter has a default value , When calling the function, no value is passed for this formal parameter , Then this parameter takes the default value .
For the formal parameters of a function, we can also set it to be changeable :
In [9]: def test(*params): ...: print(' The length of the parameter is %d'%len(params)) ...: print(' The third parameter is zero %s'%params[2]) ...: In [10]: test(1,2,'mao',3.14,'pp') The length of the parameter is 5 The third parameter is zero mao
Use the formal parameter here * identification , Then, when calling parameters, you can pass in several arguments .
Constants defined in functions are called local variables , That is, only in this function can you call , Use of... Outside a function is not acceptable :
In [12]: def test(a,b): ...: c = 2 ...: return a*b*c In [13]: test(2,2) Out[13]: 8 In [14]: print(c) NameError: name 'c' is not defined
If the statement inside a function is not very complex , Very little code , We can use anonymous functions , For example, the function of calculating the volume above :
In [20]: vol = lambda a,b,c:a*b*c In [21]: vol(2,2,3) Out[21]: 12
lambda Expressions are often nested in statements , It will be easy to use in combination with correlation functions , Examples will be given later .
Several function nesting is also supported when defining functions , But when you use it, you need to pay attention to the logical relationship :
In [24]: def fun1(a): ...: b = 2 ...: def fun2(): ...: return a*b ...: return fun2() ...: In [25]: fun1(4) Out[25]: 8
Built in functions have been covered in the first two articles , For example, common len、sorted、reversed、sum wait , In addition, several basic built-in functions are introduced .
Find the maximum and minimum values in a sequence : In [28]: min(1,2,3) Out[28]: 1 In [29]: max(1,2,3) Out[29]: 3
Find the absolute value of a number :
In [31]: abs(-1) Out[31]: 1
Round to several decimal places :
In [32]: round(3.555,2) Out[32]: 3.56
Calculate the power of a number , Or take the rest :
In [33]: pow(2,3)#2*2*2 Out[33]: 8 In [34]: pow(2,3,3)#(2*2*2)%3 Out[34]: 2
Calculate the quotient and remainder of a number :
In [36]: divmod(10,3) Out[36]: (3, 1)
The help document used to query a function :
In [37]: help(abs) Help on built-in function abs in module builtins: abs(x, /) Return the absolute value of the argument.
filter() Function takes two parameters , The first argument can be a function or None, The second parameter is the sequence . The function is to judge each element , return True or False,filter() According to the judgment result, automatically filter out False The elements of , Stay as True The elements of , Can combine lambda Expressions use :
In [38]: list(filter(lambda x:x%2,range(10))) Out[38]: [1, 3, 5, 7, 9]
map() Function takes two parameters , One is a function , One is the sequence . The function is to apply the function to each element in the sequence , It can also be combined with lambda Expressions use :
In [42]: list(map(lambda x: x*2,range(10))) Out[42]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
About file reading and writing operations ,open() Functions must be encountered , If the file already exists, the file will be opened , If it does not exist, a file will be created , The usual usage requires two parameters :open(filename,mode).
The first parameter is the file name , The second parameter specifies how the file will be used , Optional modes are commonly used in the following :
•'r': Open the file read-only ( Default )
•'w': Open file in write mode , The existing file will be overwritten
•'a': Open file in write mode , If the file exists , Write... At the end
•'b': Open the file in binary mode , Then there will be rb、wb Equal pattern combination
read() Method can pass in a parameter size, That is, the length of the read content .size Is an optional parameter , If you don't pass in or pass in a negative number , Then all the contents of the file will be read :
In [52]: fb = open('E:/Python Basics /test.txt','r') In [53]: fb.read(10) Out[53]: 'nai\nniatan' In [54]: fb.read() Out[54]: 'g\nnaitangmao' In [55]: fb.read() Out[55]: ''
There are three points to note :
•1、 The newline in the original file is read with a newline character '\n' Express , It also occupies a unit length
•2、 What has been read cannot be read repeatedly
•3、 If the read content returns an empty string , Indicates that the end of the file has been reached
readline() The method is to read a single line from the file , There will be a newline at the end of the line '\n', If there is no data in one row , Only one... Will be returned '\n', Similarly, when an empty string is returned, it indicates that the end of the file is reached .
In [59]: fb1 = open('E:/Python Basics /test.txt','r') In [60]: fb1.readline() Out[60]: 'nai\n'
readlines() Method is also used to read all files , And read() The difference is that the former reads by line , And the final return is a list , Each row of data acts as a list element :
In [72]: fb3 = open('E:/Python Basics /test.txt','r') In [73]: fb3.readlines() Out[73]: ['nai\n', 'niatang\n', 'naitangmao']
The content read out in this way will look more standardized :
In [81]: for i in fb4: ...: print(i,end = '') ...: nai niatang naitangmao
When writing , Two points we need to pay attention to :
• If the written data is non string content , Need to be converted to a string
• The writing method should pay attention to whether to overwrite or append
In [85]: fb5 = open('E:/Python Basics /test1.txt','w') In [89]: list1 = [1,2] In [91]: fb5.write(str(list1)) Out[91]: 6
use write After writing, the length of the written string will be returned .
Remember to remember to remember ! If you use open() To open a file , Be sure to use... After the operation is completed close() Method to close the file .
In [92]: fb5.close()
If you feel you have a bad memory , Always forget to use close() Method to close the file , Then get used to using with Processing file objects , It can automatically close files after they are used up .
In [93]: with open('E:/Python Basics /test.txt','r') as fb: ...: data = fb.read() In [95]: fb.closed Out[95]: True
As mentioned above, writing a non string to a file is not allowed , If there is no way to save a dictionary or list of data ?pickle Module can realize the storage and reading of this serialization :
In [96]: import pickle In [97]: list1 = ['nai','tang','mao',1,2,3] In [98]: pic_f = open('E:/Python Basics /list.pkl','wb') In [99]: pickle.dump(list1,pic_f) In [100]: pic_f.close()
dump() Method accepts two parameters , The first is what you want to store , The second is the stored file object , After the operation, you also need to use close() Close file object , After storage, you can use load() Method to load the contents of the file .
In [102]: pic_f = open('E:/Python Basics /list.pkl','rb') In [103]: list2 = pickle.load(pic_f) In [104]: list2 Out[104]: ['nai', 'tang', 'mao', 1, 2, 3] In [105]: pic_f.close()
utilize pickle When storing or reading, you should pay attention to operating file objects in binary form , That is to say 'wb' and 'rb',pickle It is very suitable for storing data with complex data types and a large amount of data .