Named code blocks used to complete specific tasks.
The function code block starts with the def keyword, followed by the function identifier name and parentheses (). Any incoming parameters and arguments must be placed between parentheses. The parentheses can be used to define parameters. The first line of the function can optionally use a docstring—used to store the function description. The function content starts with a colon and is indented. return ends the function, optionally returning a value to the caller. Return without expression is equivalent to returning None.
Create a simple hello function
>>> def hello():...print('hello,world')...>>>hello()
hello,world
When defining a function, the parameters in () are formal parameters, and the input values are actual parameters. In the example below, hello(x) is the formal parameter and 7 is the actual parameter.
>>> def hello(x):...return x
>>> hello(7)7
We can define our own default values in the parameters
>>> def hello(x,y):...return x-y
...>>> hello(3,7)-4
The value returned by the function is the return value
>>> def hello(x):...return x*3...>>>hello(3)9
If the incoming object is not an unmodifiable object, such as an integer or floating-point number, although the value is modified in the function, the original object will not be changed.
If ten lists are passed in, the list is still referenced in the function. If the function changes, the original variables will also change
>>> def hello(x):... x=2...>>> x=3>>>print(x)3>>>hello(x)>>>print(x)3
We can find that x has not become 2
>>> def hello(x):... x[1]=2>>> x=[2,4,6]>>>hello(x)>>>print(x)[2,2,6]
You can see that x changed the value after executing this function
Back to dictionary
>>> def person(name,score):
person={'name':name,'score':score}return person
>>> person("Tom",90){'name':'Tom','score':90}
Nested functions inside functions
The following example is a nested function in a function. The return value returns a function, and the x in it is the parameter x of the fun function.
>>> def fun(x)
def fun2(y):return x+y
return fun2
>>> a=fun(3) ######When we set a=fun(3)When we are equivalent to passing in the parameter x=3,The returned a is a function of fun2.
>>> type(a)<class'function'>>>>a(8) ######If we pass in the parameter again, it is equivalent to passing in the y value.
11
>>> def person(name,score):
person={'name':name,'score':score}return person
while True:print('please tell me your name and score:')
name=input('name:')if name =='q':break
score=input('score:')if score =='q':break
people=person(name,score)print(people)
please tell me your name and score:
name:Tom
score:80{'name':'Tom','score':'80'}
please tell me your name and score:
name:q
We can add the contents of the loop to pass the list in the function
>>> def hello(x):...for name in x:...print('hello'+name+'!')...>>> t=['tom','mary','hh']>>>hello(t)
hellotom!
hellomary!
hellohh!
Add * to the formal parameter, which means that more than one actual parameter can be passed in
>>> def vegetable(*x):...print(x)...>>>vegetable('spinage')('spinage',)>>>vegetable('spinage','chinese leaf')('spinage','chinese leaf')
It is to use functions to express the program, and use the combination of functions to express the way of thinking of program combination
Python allows the use of lambda keywords to create anonymous functions, the following examples will explain what lambda functions are
#### First simply define a function
>>>>>> def ds(x):...return2*x+1...>>>ds(5)11
#### Expressed in lambda can be abbreviated as
>>> lambda x:2*x+1<function<lambda> at 0x0000012236894EE8>>>> g=lambda x:2*x+1>>>g(5)11
##### The formation of closures write lambda functions
>>> def fun(x):...return lambda y:x+y
...>>> tem=fun(4)>>>tem(6)10
Filter is a filter. Its function is to extract useful information from a large amount of data. There are two parameters in the filter. One parameter can be a function or None. If it is a function, the second Each element in the iterable object is calculated as a parameter of the function, and the value that returns TRUE is calculated, and only the value of TRUE is returned.
>>> temp =filter(None,[1,0,False,True])>>>list(temp)[1, True]
#### Add a function below
>>> def odd(x):...return x%2...>>> temp=filter(odd,range(10))>>>list(temp)[1,3,5,7,9]
map is a mapping function. One parameter is still a function and the other is an iterable object. It supports multiple iterable objects and returns the result of the calculation.
>>> def odd(x):...return x*2...>>> temp=map(odd,range(10))>>>list(temp)[0,2,4,6,8,10,12,14,16,18]>>>list(map(lambda x,y: x+y,[1,3,5],[10,20,30]))[11,23,35]
In python, a dictionary is a series of key-value pairs. Each key is associated with a value. The key can be used to access the corresponding value. The key can be a number, a string, a list or even a dictionary.
If you want to save the names and grades of classmates in a class in a list, you can use the list plus tuples
data=[('tom',89),('mary',90),('haha',100)]
data
[(' tom',89),('mary',90),('haha',100)]
For the above list, if we want to query whether there is tom in the list, we need to compare everything in the list, which will be slower, so we want to query the corresponding value according to a certain feature, which is in the form of a dictionary. A key-value pair composed of key_value, the data structure is called map, and python is a dictionary
Let's create a dictionary
scores={'tom':90,'mary':80,'mike':70,'jak':100}
scores
{' tom':90,'mary':80,'mike':70,'jak':100}
len(scores)###See how many key-value pairs there are
4
scores['tom'] ###Get the corresponding value 90 according to the key tom
90
scores.get('tom')
90
scores['bob']=88 ###Add key-value pairs to the dictionary
scores
{' tom':90,'mary':80,'mike':70,'jak':100,'bob':88}
scores['tom']='toom' ###Modify the value in the dictionary
scores
{' tom':'toom','mary':80,'mike':70,'jak':100,'bob':88}
del scores['tom'] ####Delete key-value pair
scores
{' mary':80,'mike':70,'jak':100,'bob':88}
scores
{' mary':80,'mike':70,'jak':100,'bob':88}
for key,value in scores.items(): ###Traverse all key-value pairs
print(key)print(value)
mary
80
mike
70
jak
100
bob
88
for name in scores.keys(): #####Loop through all keys
print(name)
mary
mike
jak
bob
for score in scores.values(): ####Iterate over all values
print(score)
807010088
scoresheet={'mike':(60,80,90),'tom':(80,70,99),'mary':(78,90,57)}for key in scoresheet.keys():print(key,scoresheet[key])
mike(60,80,90)tom(80,70,99)mary(78,90,57)
Include dictionary in list
alion={'hh':1,'hhw':2,'hhh':3}
alion2={'yy':1,'yyy':2,'yyyy':3}
alion3={"uu":1,'uuu':2,"uuuu":3}
alionall=[alion,alion2,alion3]
alionall
[{' hh':1,'hhw':2,'hhh':3},{'yy':1,'yyy':2,'yyyy':3},{'uu':1,'uuu':2,'uuuu':3}]
for alien in alionall:print(alien)
{' hh':1,'hhw':2,'hhh':3}{'yy':1,'yyy':2,'yyyy':3}{'uu':1,'uuu':2,'uuuu':3}
for alien in alionall[:2]:print(alien)
{' hh':1,'hhw':2,'hhh':3}{'yy':1,'yyy':2,'yyyy':3}
Store list in dictionary
apple={'color':['red','yellow'],'shape':['round','square']}
for things in apple.values():print(things)
[' red','yellow']['round','square']
for key in apple.keys():print(key)
color
shape
Include dictionary in dictionary
people={'tom':{'math':80,'english':90},'mary':{'math':90,'english':70}}for name,project in people.items():print(name,project)
tom {'math':80,'english':90}
mary {'math':90,'english':70}
for name,pro in people.items():print(name,pro)
tom {'math':80,'english':90}
mary {'math':90,'english':70}
There are two creation methods, one is to create directly, and the other is to create with set.
>>> name={"tom","yamy","mary","kai"}>>> name2=set(["tom","yamy","mary","kai"])>>> name==name2
True
The elements in the collection are unordered and cannot be accessed in the form of the following table like a sequence, but the data in the collection can be read out one by one in an iterative manner.
>>> for na in name:...print(na)...
kai
tom
mary
yamy
>>> name.add("haha")>>> name
{' tom','haha','kai','mary','yamy'}>>> name.remove('haha')>>> name
{' tom','kai','mary','yamy'}
Use the function frozenset to freeze the collection, then the collection becomes immutable and cannot be modified.
>>> name=frozenset({"tom","yamy","mary","kai"})>>> name.add("hah")Traceback(most recent call last):
File "<stdin>", line 1,in<module>
AttributeError:'frozenset' object has no attribute 'add'
Reference: Rookie tutorial, Python programming entry to practice Python use the open() method to ensure that the file object is closed, that is, call the close() method.
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Parameter description: file: required, file path (relative or absolute path). mode: optional, file opening mode buffering: set buffer encoding: generally use utf8 errors: error level newline: distinguish newline characters closefd: incoming file parameter type opener: set a custom opener, the return value of the opener must be one Open file descriptor. Mode setting: (common mode) r Open the file in read-only mode. The pointer of the file will be placed at the beginning of the file. This is the default mode x writing mode. Create a new file. If the file already exists, an error will be reported. w Open a file only for writing. If the file already exists, open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file a Open a file for appending. If the file already exists, the file pointer will be placed at the end of the file. In other words, the new content will be written after the existing content. If the file does not exist, create a new file for writing
If the input of the file path is Windows, you need to use a backslash\
>>> fo =open("test.txt","r+")>>>print("File name: ", fo.name)
File name: test.txt
>>> line = fo.read()>>>print("String read: %s"%(line))
String read: h
nsuiabcjkc
nsjciuabc
>>> withopen('C:\\Users/lihm/Desktop/vscode/python/python05/test.txt')as file_object:... content = file_object.read()...print(content)...
abcdehcb
bsudiabjs
bcshcuyb
bshcbaknca
When reading a file, if you need to check each line or find information about a specific file, you may need to traverse the contents of the file, you can use a for loop
>>> withopen('test.txt')as file:...for line in file:...print(line)...
abcdehcb
bsudiabjs
bcshcuyb
bshcbaknca
We found that the empty table lines of the file printed line by line have increased because there will be an invisible newline character at the end of the file, and the print statement will also add a newline character, so there will be two newline characters when printed. , You can use rstrip() to eliminate newlines
>>> withopen('test.txt')as file:...for line in file:...print(line.rstrip())...
abcdehcb
bsudiabjs
bcshcuyb
bshcbaknca
If you want to add content to the file instead of overwriting the original content, you can open the file in append mode. Python will not clear the original file content when opening the file in append mode, and the new file content written will be added to the end
>>> file =open("test.txt","r")>>> line = file.read()>>>print("String read: %s"%(line))
String read: hdacjkanckdsnvkl
nsjciuabc
sxnajiscbiab
njsbcjbjsnc
################################ Join the string ttttttt
>>> fo =open("test.txt","a") #####mode changed to a
>>> str ="ttttttt">>> fo.write(str)7>>> fo.close()>>> fo =open("test.txt","r")>>> line = fo.read()>>>print("String read: %s"%(line))
String read: hdacjkanckdsnvkl
nsjciuabc
sxnajiscbiab
njsbcjbjsnc
ttttttt
>>> fo=open("test2.txt","w")>>>fo.write('I love python,I am learning python.')>>> fo.write('I love python,I am learning python.')35>>> fo.close()>>> fo =open('test2.txt','r')>>> fo.read()'I love python,I am learning python.'
>>> withopen('text2.txt','w')as file:
file.write('I love python,\n')
file.write('I am learning.\n')>>>withopen('text2.txt','r')as file:...print(file.read())...
I love python,
I am learning.
################ Can write directly
>>> withopen('text2.txt','w')as file:... file.write('I love python,\nI am learning.\n')...30>>>withopen('text2.txt','r')as file:...print(file.read())...
I love python,
I am learning.
Python provides two very important functions to deal with exceptions and errors in the running of a python program. You can use this function to debug python programs. We will have two types of errors when writing programs: syntax errors and semantic errors. Python syntax errors, or so-called parsing errors, are often encountered by beginners, as shown in the following example
>>> while True print('Hello world')
File "<stdin>", line 1,in?while True print('Hello world')^
SyntaxError: invalid syntax
In this example, the function print()It was checked that there was an error because it was missing a colon before it: 。
The parser pointed out the wrong line, and marked a small arrow where the error was found first.
Python exception: Whenever an overwhelming error occurs to Python, it will create an exception object. If no code is written to handle the exception when writing the code, the program will stop and display a traceback, which contains a report about the exception.
>>>10*(1 /0) #0 cannot be used as a divisor, triggering an exception
Traceback(most recent call last):
File "<stdin>", line 1,in?
ZeroDivisionError: division by zero
>>>4+ spam*3 #spam is undefined, triggers an exception
Traceback(most recent call last):
File "<stdin>", line 1,in?
NameError: name 'spam' is not defined
>>>'2'+2 # int cannot be added to str, triggering an exception
Traceback(most recent call last):
File "<stdin>", line 1,in<module>
TypeError: can only concatenate str(not "int") to str
################ An exception occurred while reading the file
>>> f=open("text2.txt","r")>>> f.read()Traceback(most recent call last):
File "<stdin>", line 1,in<module>
UnicodeDecodeError:'gbk' codec can't decode byte 0x80in position 48: illegal multibyte sequence
################# correct
>>> f=open("text2.txt","r",encoding='UTF-8')>>> f.read()
' The People's Daily publishes 16 pages every day from Monday to Friday. The first to fourth editions are news editions, the fifth to twelfth editions are in-depth report editions, and the thirteenth to sixteenth editions are weekly and special editions. On Saturdays and Sundays, there are 8 editions of the folio every day,\n one to four editions
It is the news edition, and the five to eight editions are special editions. The news edition is divided into editing and editing, highlighting timeliness and news.\n The in-depth report version implements a unified collection and editing, focusing on political, economic, cultural, technological, and international reports
. Weekly and special editions have opened up 5 kinds of weekly and other colorful special editions.'
Use the try-except code block to point out the exception, you can set the code in the place where the exception may occur to remind you what kind of exception occurred, and how to correct it
>>> print(5/0)Traceback(most recent call last):
File "<stdin>", line 1,in<module>
ZeroDivisionError: division by zero
>>> try:...print(5/0)... except ZeroDivisionError:...print("you can not divide by zero")...
you can not divide by zero
>>> try:...'2'+2... except TypeError:...print("str can not add int")...
str can not add int
Using try-else-except, you can improve the executable ability of the code, and output error information incorrectly. Adding the else code block can put the successfully executed code in the else and successfully output the correct result.
>>> for arg in test:...try:... f=6/int(arg)... except ZeroDivisionError:...print("you can not divide by zero")...else:...print(f)...3.0
you can not divide by zero
1.56.0
Recommended Posts