python Parser
IDE: Abbreviation of integration tool
effect : Run the file
- ipython: Is an interactive parser , You can save variables automatically 、 Automatic indentation
- cpython:c Official parser for language development , Widely applied
- Other parsers
Two ways
# Single-line comments
""" Multiline comment ( Three double quotes ) """
''' Multiline comment ( Three single quotes )'''
# Shortcut key :ctrl+/
In the program , Data is temporarily stored in memory , The variable is just the name of the memory address of the current data when storing data .
Variable name = value # It is not said here that the type of variable must be specified
The variable name should conform to the identifier naming rules :
- By digital 、 Letter 、 Underline composition
- Can 't start with a number
- You can't use built-in keywords
- Case sensitive
Naming habits :
- See the name and know the meaning
- Hump
- Little hump
- Underline
character string :String
Metagroup type : Array
List :list class
Dictionary type :map class
aggregate :set
Boolean type :
representative False, The numbers represent 0 Of , All kinds of brackets are empty
, There are only two values here , One is True, One is FalseTest data type :type( data )
a=3+2j
print(a)
b=complex(3,4)
print(b)
(3+2j)
(3+4j)
a=3+2j
print(a)
print(a.real)
print(a.imag)
(3+2j)
3.0
2.0
Here is the normal output , There are three ways to output
x =input(' Please enter an integer ')
print(x)
name='aabbcc'
age=20
str=' My name is {}, I this year {} year '
print(str.format(name,age))
name='aabbcc'
age=20
print(f' My name is {
name}, This year, {
age} year ')
Here we use a format function , Very flexible
s=" In today's {} attend class;class begins , On is {} course "
print(s.format("6 building ","python"))
In today's 6 Dong has classes , On is python course
Comparison operator
==
It means that the characters are the same and the corresponding addresses should also be the same ,equal
It means that the characters are the same .
from string import Template
string =Template(" I wish you ${x} happy ")
string.substitute(x=' Birthday ')
# The advantage of this is that it can be changed at any time x Data type and data
import datetime
name = str(input(" Please enter your name :"))
birthday =int(input(" Please enter your year of birth :"))
age = datetime.date.today().year -birthday
print("%s Hello! ! This year you %d year ."%(name,age))
Here is the formatted output
%s: character string
%d: Decimal integer
%f: Floating point numbers
%c: character
\n: Line break
\t: tabs
Input
x =input(' Please enter an integer ')
print(x)
Common functions for converting data types
int()
float()
str()
list()
tuple() # Tuples
eval() # Convert to the original type
/
Indicates division with decimals //
: To divide or divide in
、not in
It means that in this sequence, it will return true, If not, go back falsefor i in (1,23)
#for(int i=1;i<23;i++)
# Talk about an operational logic
d=10
d*=1+2
print(d)
# The result is 30, First calculate the right side of the assignment , Count the left
if……elif ……else
Execute the process : When a certain code meets the conditions, it can be executed , Other subsequent code will not execute
age=50
if age < 18:
print(f' Your age is {
age}, You are a child laborer ')
elif (age>=18)and (age<=60):
print(f' Your age is {
age}, You are a legal working people ')
else:
print(f' Your age is {
age}, You are a retired worker ')
Simplified writing
elif 18<=age<=60
age=50
if age < 18:
print(f' Your age is {
age}, You are a child laborer ')
elif 18<=age<=60:
print(f' Your age is {
age}, You are a legal working people ')
else:
print(f' Your age is {
age}, You are a retired worker ')
random number
random class
import random
x=random.randint(1,20)
print(x)
Ternary operator
c=a if a>b else b
a=1
b=2
c=a if a>b else b
print(c)
while grammar
i=0;
while True:
if i==9:
break;
print(i)
i+=1 # Here's what's interesting ,i++ It doesn't exist
break: End cycle
continu: Terminate the current execution , Other execution of the loop is not affected
for loop
for a in [1,10]:
print(a)
1
10
for i in range(1,10):# Here's what's interesting , To use range() function
print(i)
while…else
Execute the code after the loop ends normally , Code cannot be executed after abnormal execution
This is because of cycles and else The following content has certain dependencies
# Cases that normally end
i=0
while i<=5:
print(i)
i+=1
else:
print('end')
1
2
3
4
5
end
# break Cases that end in advance
i=1
while i<=5:
if i==3:
print(' An error occurred ')
break
print(i)
i+=1
else:
print('end')
1
2
An error occurred
# continue Cases that end in advance
i=0
while i<=5:
i+=1
if i==5:
print(' An error occurred ')
break
print(i)
else:
print('end')
1
2
3
4
An error occurred
for…else
and while equally , It also needs to be executed at the normal end of the program , If the program does not end normally ,else Later things will not be implemented .
for a in (1,10):
print(a)
else:
print(' The loop ends , Print response ')
name1='cch1'
name2="cch2"
name3='''cch3'''
name=input(' Type in your name :')
print(' My name is '+name)
print(' My name is %s'%name)
print(f' My name is {name}')
[ Subscript ]
name[0]
Sequence [ The following table of starting positions : The following table of ending positions : step ]
Pay attention to is :
str1='0123456'
print(str1[2:5:2])
# The result is 24
# If you don't write the beginning , The default from the 0 Start
str1='0123456'
print(str1[:5:1])
# The result is 01234
# If you don't write the end , Default to the last , And it contains the last
str1='0123456'
print(str1[3:])
# The result is 3456
# If the step size is negative , It means counting in reverse order
str1='0123456'
print(str1[::-1])
# The result is 6543210
# The first two are negative numbers
str1='0123456'
print(str1[-4:-1])
# The result is 345, Because it does not contain -1 The number in position , That is, it does not contain the last number
# All three numbers are negative
str1='0123456'
print(str1[-4:-1:-1])
# Cannot select data , Because the two directions are mutually exclusive , from -4 To -1 It is selected from left to right , however -1 Step size means to select from right to left
# All three numbers are negative
str1='0123456'
print(str1[-1:-4:-1])
# 543, Because the selected direction is consistent
Find the position of the substring in the string or the number of occurrences
find(): Check whether a string is contained in the string , If it exists, return to the following table at the beginning of this string , Otherwise return to -1
Be careful : The start position and end position can be omitted , Means to find... In the whole string sequence
The following is grammar :
String sequence .find( String , Starting position subscript , Subscript of end position )
# The subscripts of the starting and ending positions can be omitted here ,
string='asdffgghfj'
print(string.find('sdf',2))
# return -1, Because from 2 The string at the beginning of position does not contain the string we require ‘sdf’
String sequence .index( String , Starting position subscript , Subscript of end position )
# The subscripts of the starting and ending positions can be omitted here ,
string='asdffgghfj'
print(string.index('sdf',2))
String sequence .count( String , Starting position subscript , Subscript of end position )
# The subscripts of the starting and ending positions can be omitted here ,
string='asdffgghfj'
print(string.count('sdf',2))
# The result here is 0
The following functions are similar to the corresponding functions above , But the search direction is from On the right side Start looking for , The following table starts from left to right
String sequence .replace( Old characters , New character , Number of replacements )
# The number of replacements can be omitted , Not writing means to replace all ; If the number of replacements > Number of string occurrences , Means replace all , But there is no error
string='asdffgghfj'
print(string.replace('f',' False '))
# result :asd False False ggh False j
string.split( Split character ,num)
# num Indicates the number of times the split character appears , That is, the number of returned data is num+1 individual
string='asd False False ggh False j'
print(string.split('False'))
# Output results :['asd ', ' ', ' ggh ', ' j'], Here you can see , It's all divided , and False Itself has been removed
string='asd False False ggh False j'
print(string.split('False',2))
# The result here is :['asd ', ' ', ' ggh False j'], Here you can see , This will return to 2+1 Data , That is, only the front 2 Data
Characters or substrings .join( A sequence of multiple strings )
# Characters or substrings Indicate what method you want to use to connect the contents of this sequence
list=['aa','bb','cc']
string='...'.join(list)
print(string)
# The result is :aa...bb...cc
character string .capitalize()
string='asd False False ggh False j'
print(string.capitalize())
# Asd false false ggh false j
character string .title()
string='asd False False ggh False j'
print(string.title())
# Asd False False Ggh False J
Here is another time : String functions do not modify the string itself , Instead, there will be a return value , The modified result is in the return value .
Delete the white space character of the string
lstrip(): Delete the white space character on the left
rstrip(): Delete the white space character on the right
strip(): Delete the blank characters on the left and right
string=' asd False False ggh False j '
print(string.rstrip())
# asd False False ggh False j
string.ljust( length , Fill character )
string="aabbcc"
print(string.ljust(10,'*'))
# aabbcc****
string="aabbcc"
print(string.rjust(10,'*'))
# ****aabbcc
string="aabbcc"
print(string.center(10,'*'))
# **aabbcc**
string="aabbcc"
print(string.center(9,'*'))
# **aabbcc*
If the middle is aligned , When the padding character is odd , There is no absolute alignment
The result returned by the judgment function is False Or is it True
Judge the beginning and the end
startswith(): Check whether the string starts with the specified string within the specified range , Is to return True, Otherwise return to False
grammar :
string.startswith( Substring , Starting position subscript , End position subscript )
# The last two parameters can be omitted
string.endswith( Substring , Starting position subscript , End position subscript )
# The last two parameters can be omitted
string='asd False False ggh False'
print(string.endswith('false'))
# False
Here's what's interesting , Here is strictly case sensitive
string1='hello'
string2='hello123'
string3='Hello'
string4='123'
print(string1.isalpha())
print(string2.isalpha())
print(string3.isalpha())
print(string4.isdigit())
# True
# False
# True
# True
This is regardless of case
string1=' '
string2='hello123'
print(string1.isspace())# True
print(string2.isalnum())# True
Store multiple data , And the data that can be modified is the list .
[ data 1, data 2, data 3……]
Lists can store a lot of data , You can also store data of different data types , But in real business , We usually store the same data type in the same list
name=['aaa','bbb','ccc']
print(name[0])
# aaa
list.index()
name=['aaa','bbb','ccc']
print(name.index('bb'))
list.count()
len(list_name)
# Return a number
name=['aaa','bbb','ccc']
print(len(name))
print(type(len(name)))
# 3
# <class 'int'>
Return value bit True perhaps False
data in list_name
shuju1 not in list_name
name=['aaa','bbb','ccc']
print('aaa' in name)
print('aa' in name)
print('aa' not in name)
# True
# False
# True
Add specified data to the list
list.append( data )
name=['aaa','bbb','ccc']
name.append('ddd')
print(name)
# ['aaa', 'bbb', 'ccc', 'ddd']
You can append the list sequence
name=['aaa','bbb','ccc']
name.append([11,22])
print(name)
# ['aaa', 'bbb', 'ccc', [11, 22]]
Pay attention to is , Only one data can be appended at a time , You cannot append multiple data at the same time
list.extend( data )
The difference between here and above is , When adding a sequence here , Will take the sequence apart
name=['aaa','bbb','ccc']
name.extend('ddd')
print(name)
# ['aaa', 'bbb', 'ccc', 'd', 'd', 'd']
# there ‘ddd’ It is also a sequence , So take it apart
name=['aaa','bbb','ccc',12]
name.extend([10,13])
print(name)
# ['aaa', 'bbb', 'ccc', 12, 10, 13]
name=['aaa','bbb','ccc',12]
name.extend(10)
print(name)
# TypeError: 'int' object is not iterable
# int Not an iteratable type , Not directly extend
name=['aaa','bbb','ccc',12]
name.extend(range(1,2))
print(name)
# ['aaa', 'bbb', 'ccc', 12, 1]
list.insert( Subscript , data )
name=['aaa','bbb','ccc',12]
name.insert(2,'ddd')
print(name)
# ['aaa', 'bbb', 'ddd', 'ccc', 12]
Here's what we have to pay attention to , The added part is actually added to the list itself , The data of the list itself has been modified , This and str Different types
del The goal is
del( The goal is )
# Delete data in the specified location
del list[ Subscript ]
name=['aaa','bbb','ccc',12]
del name
print(name)
# NameError: name 'name' is not defined
name=['aaa','bbb','ccc',12]del name[0]print(name)# ['bbb', 'ccc', 12]
list.pop( Subscript )
name=['aaa','bbb','ccc',12]a=name.pop()print(name)print(a)# ['aaa', 'bbb', 'ccc']# 12
This method cannot delete multiple data
list.remove( Specified data )
name=['aaa','bbb','ccc',12]name.remove(12)print(name)# ['aaa', 'bbb', 'ccc']
list.clear()
name=['aaa','bbb','ccc',12]name.clear()print(name)# []
Deleting data is also deleted in the list itself
name=['aaa','bbb','ccc',12]name[0]='gdhhhr'print(name)# ['gdhhhr', 'bbb', 'ccc', 12]
name=['aaa','bbb','ccc',12]name.reverse()print(name)# [12, 'ccc', 'bbb', 'aaa']
list.sort(key=None,reverse=False)# key It is to sort according to a certain value in the dictionary ,reverse=False Expressing ascending order ,reverse=True Representation of descending order
name=[1,2,3,4,6,7,5]name.sort()print(name)# [1, 2, 3, 4, 5, 6, 7]
name=[1,2,3,4,6,7,5]name.sort(reverse=True)print(name)# [7, 6, 5, 4, 3, 2, 1]
copy(): The copy function has a return value , Is the data after replication , It is generally used to retain source data
grammar :
list.copy()
i=0name=[1,2,3,4,6,7,5]while i<len(name): print(name[i] ,end=' ') i+=1# 1 2 3 4 6 7 5
name=[1,2,3,4,6,7,5]for i in name: print(i,end=' ')# 1 2 3 4 6 7 5
name=[[1,2,3],[23,34,45],[234,456,789]]for i in name: print(i,end=' ')# [1, 2, 3] [23, 34, 45] [234, 456, 789]
name=[[1,2,3],[23,34,45],[234,456,789]]for i in name: for j in i: print(j,end=' ')# 1 2 3 23 34 45 234 456 789
Store multiple data , Data cannot be modified , Use parentheses
Get the data of a certain subscript :tuple[i]
Use parentheses
name=(10,20)
What we should pay attention to here is , If the tuple defined has only one data , Add a comma after this data , Otherwise, the data type will be the only data type
name=(10)name1=(10,)print(type(name))print(type(name1))# <class 'int'># <class 'tuple'>
Because tuples do not support modification , Only search operation is supported , So the operations here are all search operations
tuple.index(e,start,end)
a=(11,22,33,44)print(a.index(11))
count()
grammar :
tuple.count()
tuple.len()
modify
Nested lists in tuples , The contents of this list can be modified
a={
'name':'Tom','age':20,'gender':' male '}a=dict()a={
}
Dictionaries are variable types , That is, the modification of the dictionary is based on the data of the dictionary itself , This year and list equally
How to write it :dictName[key]=value
If key Modify as long as it exists value, If it does not exist, add this key value pair
a={
'name':'ccc','age':20}a['name']='cch'print(a)# {'name': 'cch', 'age': 20}
a={
'name':'ccc','age':20}a['id']=1print(a)# {'name': 'ccc', 'age': 20, 'id': 1}
a={
'name':'ccc','age':20}del(a)print(a)# NameError: name 'a' is not defined
a={
'name':'ccc','age':20}del a['name']print(a)# {'age': 20}# If it doesn't exist, it will report an error
a={
'name':'ccc','age':20}a.clear()print(a)# {}
How to write it : Dictionary sequence [key]=value, In fact, it is no different from increasing
a={
'name':'ccc','age':20}a['name']='cch'print(a)# {'name': 'cch', 'age': 20}
a={
'name':'ccc','age':20}print(a['name'])# ccc
Dictionary sequence .get(key, The default value is )
a={
'name':'ccc','age':20}
print(a.get('id',1))
# 1
a={
'name':'ccc','age':20}
print(a.keys())
# dict_keys(['name', 'age'])
a={
'name':'ccc','age':20}
print(a.values())
# dict_values(['ccc', 20])
a={
'name':'ccc','age':20}
print(a.items())
# dict_items([('name', 'ccc'), ('age', 20)])
Here I analyze unpacking
a={
'name':'ccc','age':20}
for key,value in a.items():
print(f'{
key}={
value}')
# name=ccc
# age=20
{}
perhaps set()
, But if you want to create an empty collection, you can only use set()
, because {}
Used to create an empty dictionary set1={
12,10,28,28,28}
print(set1)
# {10, 12, 28}
set2=set()
print(set2)
# set()
set1={
'abcfdhdjfdj'}
print(set1)
# {'abcfdhdjfdj'}
set2=set('qwert')
print(set2)
# {'q', 't', 'w', 'r', 'e'}
# There is no sequential output
set1={
12,23,45,2}
set1.add(10)
print(set1)
# {2, 10, 12, 45, 23}
set1={
12,23,45,2}
set1.add(10,11)
print(set1)
# TypeError: add() takes exactly one argument (2 given)
set1={
12,23,45,2}
set1.update([10,11])
print(set1)
# {2, 10, 11, 12, 45, 23}
set1={
12,23,45,2}
set1.remove(12)
print(set1)
# {2, 45, 23}
set1={
12,23,45,2}
set1.discard(10)
print(set1)
# {2, 12, 45, 23}
set1={
12,23,45,2}
num=set1.pop()
print(set1)
print(num)
# {12, 45, 23}
# 2
set1={
12,23,45,2}
print(10 in set1)
print(10 not in set1)
# False
# True
for i in range(10):
print(i)
# 0 1 2 3 4 5 6 7 8 9
enumerate( Traversable objects ,start=0)
# start Parameter is used to set the subscript starting value of data , The default is 0
list1=[1,2,3,4,5,6]
for i in enumerate(list1):
print(i,end=" ")
# (0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6)
list1=[1,2,3,4,5,6]
for i in enumerate(list1,1):
print(i,end=" ")
# (1, 1) (2, 2) (3, 3) (4, 4) (5, 5) (6, 6)
tuple(): Transform data into meta groups
list(): Turn data into lists
set(): Transform data into collections , You can get rid of it
stay python in , Only list 、 Dictionaries 、 Only set has derivation
Derivation is also called generative
The derivation is used to simplify the code .
= effect : Create a with an expression A regular list Or control a regular list .=
What is particularly noteworthy here is , The rule here is that the content of the list is regular .
List derivation is also called list generation
demand : Generate a regular list
Here is the conventional way of writing
list1=[]
i=0
while i<10:
list1.append(i)
i+=1
print(list1)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Here is a demonstration of the implementation of a derivation
list1=[i for i in range(10)]
print(list1)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
demand : establish 0-10 Even list of
list1=[i for i in range(0,10,2)]
print(list1)
# [0, 2, 4, 6, 8]
list1=[i for i in range(0,10) if i%2==0]
print(list1)
# [0, 2, 4, 6, 8]
demand : Create the following list :
[(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
list2=[]
for i in range(1,3):
for j in range(3):
list2.append((i,j))
print(list2)
list1=[(i,j) for i in range(1,3) for j in range(3)]
print(list1)
The function of dictionary derivation : Quickly merge two lists into one dictionary
dict1={
i:i**2 for i in range(1,5)}
print(dict1)
# {1: 1, 2: 4, 3: 9, 4: 16}
list1=[1,2,3]
list2=[1,4,9]
dict2={
list1[i]:list2[i] for i in range(len(list1))}
print(dict2)
# {1: 1, 2: 4, 3: 9}
list1=[1,2,3]list2=[1,4]dict2={
list1[i]:list2[i] for i in range(len(list1))}print(dict2)
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-14-96a775aca203> in <module>
1 list1=[1,2,3]
2 list2=[1,4]
----> 3 dict2={list1[i]:list2[i] for i in range(len(list1))}
4 print(dict2)
<ipython-input-14-96a775aca203> in <dictcomp>(.0)
1 list1=[1,2,3]
2 list2=[1,4]
----> 3 dict2={list1[i]:list2[i] for i in range(len(list1))}
4 print(dict2)
IndexError: list index out of range
So we should notice here , If the length of two lists is the same , You can take it at will list1 perhaps list2 The length of , The results are the same , But if the length is inconsistent , Take the length of the data in the list with a shorter length , Otherwise, an error will be reported
Normal problem solving ideas :
counts={
'MBP':258,'HP':20,'LENOVO':199}
count1={
}
for key,value in counts.items():
if value>100:
count1[key]=value
print(count1)
The derived type :
counts={
'MBP':258,'HP':20,'LENOVO':199}count1={
key:value for key,value in counts.items() if value>100}print(count1)
result :
{'MBP': 258, 'LENOVO': 199}
demand : Create a collection , Data bit list data 2 Power , What we should pay attention to here is ,set It has the effect of weight removal
list1=[1,1,2]set1={
i**2 for i in list1}print(set1)# {1,4}
python in , Functions must be defined before use
Format
def Function name ( Parameters ):
Code 1
Code 2
...
The return value of the function is in python There is no need to write the return value in front of the function name in , direct return That's all right.
Check the function description document
help( Function name )
Define the documentation : If and only if it can only be indented in the first line of the function and written in the form of multi line comments, it can be regarded as a description document
def delSameListElement(List1,temp):
""" Define a function , It means to delete duplicate data in a list . It uses a temp Come and take list Of non duplicate data . """
for i in List1:
if i in temp:
continue
else:
temp.append(i)
return 0;
temp=[]
List1 = [0, 1, 2, 3, 4, 1,1]
delSameListElement(List1,temp)
print(temp)
help(delSameListElement)
[0, 1, 2, 3, 4]Help on function delSameListElement in module __main__:delSameListElement(List1, temp) Define a function , It means to delete duplicate data in a list . It uses a temp Come and take list Of non duplicate data .
The return value of the function mentioned here is for the case that the function has multiple return values .
If there are more than one return Value , A tuple is returned ,return You can also return to the list 、 Tuples 、 Dictionary, etc
def return_num(): return 1,2num1=return_num()print(num1)# (1, 2)
It is basically no different from our normal parameters , That is, when the function is called , The order of parameters should be consistent with the order of the function itself , Otherwise, it will report a mistake
Function call , adopt ” key = value “ In the form of , It can make the function clearer , And easier to use , also The need to clear the order of parameters
def return_num(name,age,gender): print(f' name :{
name}, Age :{
age}, Gender :{
gender}')return_num('Rose',gender=' Woman ',age=20)# name :Rose, Age :20, Gender : Woman
When the function is called , If there are position parameters , Positional parameters must be in the face of keyword parameters , However, there is no sequence between keyword parameters
Default parameters are also called default parameters , To define a function , Provide default values for functions , You can call a function without passing the value of the default parameter ( Be careful : All position parameters must also appear in front of the default parameter value , Including the definition and call of functions )
def return_num(name,age,gender=' male '): print(f' name :{
name}, Age :{
age}, Gender :{
gender}')return_num('Tom',age=20)return_num('Rose',age=20,gender=' Woman ')
name :Tom, Age :20, Gender : Male name :Rose, Age :20, Gender : Woman
When the function is called , If it defaults, it will call the default value directly
Also called variable parameter , It is used to determine how many parameters need to be passed when calling , It's time to With parcels (packing) Positional arguments , Or package keyword parameters , To pass parameters , It will be very convenient .
*args
def return_num(*args): print(args)return_num('Tom',10)return_num('Rose',20,' Woman ')
('Tom', 10)('Rose', 20, ' Woman ')
The parameters passed in will be args Variable collection , It will be combined into a tuple according to the position of the passed parameters , This is the package location transfer
def return_num(**kwargs):
print(kwargs)
return_num(name='Tom',age=10)
{'name': 'Tom', 'age': 10}
Finally, a dictionary type is returned
Whether it is package bit transfer or package keyword transfer , It's all a packaging process
def return_num():
return 100,200 # What is returned here is a tuple
num1,num2=return_num()
print(num1)
print(num2)
100
200
dict1={
'name':'Tom','age':10}
a,b=dict1 # What comes out is keys
print(a)
print(b)
print(dict1[a])
print(dict1[b])
nameageTom10
a,b=1,20
a,b=b,a
print(a,b)
# 20 1
stay python in , Values are passed by reference
We can use id()
To determine whether two variables are references to the same value , We can talk about id It is understood as the identification of the address of that memory
a=1
b=a
print(id(a))
print(id(b))
a=2
print(b)# explain int Type is immutable data
print(id(a))
print(id(b))
140712497063728
140712497063728
1
140712497063760
140712497063728
We can understand it this way , Every time we define a data , Will open up a memory , A variable is a reference to the address of this data .
int Data of type is immutable
aa=[11,22]bb=aaprint(id(aa))print(id(bb))aa.append(33)print(id(aa))print(id(bb))
2325297783432
2325297783432
2325297783432
2325297783432
It is normal to pass variables to the function call
Learned to omit
and java The same as , When a function has a return value , And there's only one code , have access to lambda
expression
Here's what's interesting :
lambda parameter list : expression
def fn1():
return 200
print(fn1)
print(fn1())
fn2=lambda:100
print(fn2)
print(fn2())
<function fn1 at 0x00000229F25F4280>
200
<function <lambda> at 0x00000229F1A14F70>
100
def fn1(a,b): return a+bprint(fn1(1,2))fn2=lambda a,b:a+bprint(fn2(1,2))
33
def fn1(a,b,c=100): return a+b+cprint(fn1(1,2))fn2=lambda a,b,c=100:a+b+cprint(fn2(1,2))
103103
def fn1(*args):
return args
print(fn1(1,2))
fn2=lambda *args:args
print(fn2(1,2))
(1, 2)
(1, 2)
def func(a,*b):
for item in b:
a += item# unpacking
return a
m = 0
print(func(m,1,1,2,3,5,7,12,21,33))
# 85
def fn1(**kwargs):
return kwargs
dict1=fn1(name='Tom',age=20)
print(dict1)
fn2=lambda **kwargs:kwargs
print(fn2(name='Rose',age=10))
{'name': 'Tom', 'age': 20}{'name': 'Rose', 'age': 10}
fn1=lambda a,b:a if a>b else bprint(fn1(1,290))# 290
students=[{
'name':'Tom','age':10},{
'name':'Rose','age':20},{
'name':'Jack','age':30}]# according to name Sort values in ascending order students.sort(key=lambda x:x['name'])print(students)# according to name null students.sort(key=lambda x:x['name'],reverse=True)print(students)
[{'name': 'Jack', 'age': 30}, {'name': 'Rose', 'age': 20}, {'name': 'Tom', 'age': 10}][{'name': 'Tom', 'age': 10}, {'name': 'Rose', 'age': 20}, {'name': 'Jack', 'age': 30}]
Pass in the function as an argument , Such functions are called higher-order functions , Higher order function is the embodiment of functional programming .
Find the absolute value of the number
Round the function
print(round(1.5))# 2
# The function of this is to change the data in the list into its square value def f(x): return x*xprint(list(map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])))# [1, 4, 9, 10, 25, 36, 49, 64, 81]
Be careful :
- because list The contained elements can be of any type , therefore ,map() It's not just about dealing with numbers list, In fact, it can handle any type of list, Just pass in the function f Can handle this data type .
reduce(func,list)
among func There have to be two parameters , every time func The calculation result of continues to accumulate with the next element of the sequence import functools
list1=[1,2,3,4]
def fun(a,b):
return a+b
result=functools.reduce(fun,list1)
print(result)
# 10
import functools
list1=[1,2,3,4]
def fun(a,b):
return a-b
result=functools.reduce(fun,list1)
print(result)
# -8
filter(func,list)
Function is used to filter out unqualified elements , Return to one filter object , Here objects can be converted to other data types, such as listlist1=[1,2,3,4,5,6,79.7]
def fun(x):
return x%2==0
result=filter(fun,list1)
print(result)
print(list(result))
<filter object at 0x000002011BE270A0>[2, 4, 6]
The function prototype :zip(*iterables)
, Parameters of variable length can be passed
This function takes a series of lists as parameters , Package the corresponding elements in the list into tuples , Then return a list of these tuples .
eval(< character string >)
Be able to Python Parse and execute the string as an expression , And output the returned results .
eval The() function converts an input string to Python sentence , And execute the statement
Use open function , You can open an existing file , Or if the file does not exist, you can create a new file
object =open(name,mode)
name: Is the string of the target file name to open ( It can contain the specific path where the file is located )
mode: Set the mode to open the file ( Access pattern ): read-only 、 write in 、 Supplemental
f=open('test.txt','w')f.write('cch')f.close()
r: read-only , If the file does not exist, an error will be reported ,r Nor does it support writing , because r Read only
w: Write , If the file doesn't exist , Will create a new file ; If the file exists , Will edit from scratch , That is, the original content will be overwritten
a: Additional , If the file exists, append , If the file does not exist, it will be created and written
If the access mode is omitted , Indicates that the file is read-only (r)
with b Of : Represents binary file form
with + Of : Indicates readable and writable mode
Understanding of prefix : The following additions are based on the prefix pattern to expand , Must meet the conditions of prefix requirements
The file pointer :r and w Are at the beginning of the file ,a It's at the end of the file
f=open('test.txt','r')a=f.read()print(a)f.close()
cch
f=open('test.txt','a')f.write('cch')f.close()# cchcch
File object .read(num)# num Indicates the length of data read from the file ( Unit is byte ), If no incoming num, Means to read all the contents
#txt The content in I can't conceivable that the number of suicies has reached 30-year high in American
f=open('test.txt','r')a=f.read(10)print(a)f.close()#I can't co# Here's what's interesting , Spaces also occupy one byte
You can read the contents of the whole file at one time in line , And it returns a list , The data in each row is an element , And return the newline symbol together and print it
f=open('test.txt','r')a=f.readlines()print(a)f.close()
["I can't conceivable that the number of suicies has reached 30-year high in American\n", 'brilliance\n', 'universal\n', 'ultimate']
By default, the first line is read for the first time , Read the second line for the second time , And so on
f=open('test.txt','r')a=f.readline()print(a)a=f.readline()print(a)f.close()
I can't conceivable that the number of suicies has reached 30-year high in Americanbrilliance
effect : Used to move the file pointer
File object .seek( Offset , The starting position )
The starting position :
- 0: Beginning of file
- 1: The current position
- 2: End of file
f=open('test.txt','r')
f.seek(2,0)
a=f.read()
print(a)
f.close()
This example represents , Start at the beginning , The offset 2 Bit, that is, the first two cannot be , Everything else can be read
can't conceivable that the number of suicies has reached 30-year high in American
brilliance
universal
ultimate
f=open('test.txt','r')
f.seek(0,2)
a=f.read()
print(a)
f.close()
Object orientation is to treat programming as a transaction , For the outside world , Transactions are used directly , Don't worry about his internal situation , Programming is to set what a transaction can do
The class name follows the naming habit of the big hump
class Class name :
...
class Class name (object):
...
Object name = Class name ()
# Define a class
class Wahser():
def wash(self):
print(' Wash the clothes ing...')
# Define an object
haier=Wahser()
haier.wash()
# Wash the clothes ing...
self Refers to the object that calls this function
# Define a class
class Wahser():
def wash(self):
print(' Wash the clothes ing...')
print(self)
# Define an object
haier=Wahser()
print(haier)
haier.wash()
<__main__.Wahser object at 0x00000204C2298D00>
Wash the clothes ing...
<__main__.Wahser object at 0x00000204C2298D00>
The properties of the object can be added outside the class , You can also add access to classes
# add to
Object name . Property name = value
# obtain
Object name . Property name
# Define a class
class Wahser():
def wash(s):
print(' Wash the clothes ing...')
# Define an object
haier=Wahser()
haier.width=500
haier.higth=600
print(f' Width {
haier.width}, Height {
haier.higth}')
haier.wash()
Width 500, Height 600
Wash the clothes ing...
The important thing to note here is that , The properties here must be defined before calling
self. Property name
# Define a class
class Wahser():
def wash(self):
print(' Wash the clothes ing...')
print(f' Width {
self.width}, Height {
self.higth}')
# Define an object
haier=Wahser()
haier.width=500
haier.higth=600
haier.wash()
Wash the clothes ing...
Width 500, Height 600
stay python in ,_xx_()
The function of is called magic method , Refers to functions with special functions
—init—()
Method is called by default when creating an object , There is no need to manually call —init—(self)
Medium self Parameters of , No need for developers to deliver ,python The interpreter will automatically pass the current object # Define a class
class Wahser():
def __init__(self) :
self.width=500
self.height=800
def info(self):
print(f' Width {
self.width}, Height {
self.height}')
def wash(self):
print(' Wash the clothes ing...')
# Define an object
haier=Wahser()
haier.info()
haier.wash()
Width 500, Height 800
Wash the clothes ing...
# Define a class
class Wahser():
def __init__(self,width,height) :
self.width=width
self.height=height
def info(self):
print(f' Width {
self.width}, Height {
self.height}')
def wash(self):
print(' Wash the clothes ing...')
# Define an object , Because it has been called when the object is created __init__ Method
haier=Wahser(100,200)
haier.info()
haier.wash()
Width 100, Height 200
Wash the clothes ing...
When print When choosing which one , We will print out the memory address by default , But if the class defines this method, it will print out the contents of this method return The data of
# Define a class
class Wahser():
def __init__(self,width,height) :
self.width=width
self.height=height
def __str__(self) -> str:
return ' Here is the instructions of the mailbox ...'
def info(self):
print(f' Width {
self.width}, Height {
self.height}')
def wash(self):
print(' Wash the clothes ing...')
# Define an object
haier=Wahser(100,200)
print(haier)
haier.info()
haier.wash()
Here is the instructions of the mailbox ...
Width 100, Height 200
Wash the clothes ing...
When deleting objects ,python Call this method automatically
# Define a class
class Wahser():
def __init__(self,width,height) :
self.width=width
self.height=height
def __str__(self) -> str:
return ' Here is the instructions of the mailbox ...'
def __del__(self):
print(' Object has been deleted ')
def info(self):
print(f' Width {
self.width}, Height {
self.height}')
def wash(self):
print(' Wash the clothes ing...')
# Define an object
haier=Wahser(100,200)
print(haier)
haier.info()
haier.wash()
del haier
Here is the instructions of the mailbox ...
Width 100, Height 200
Wash the clothes ing...
Object has been deleted
# Define a parent class animal
class animal():
def __init__(self,name) :
self.name=name# Animals have names
def info(self):
print(f' This is {
self.name}')
# Define a subclass
class dogs(animal):
pass
dog=dogs('dog')
dog.info()
# This is dog
# Define a parent class animal
class Animals():
def __init__(self) :
self.name=' animal '# Animals have names
def info(self):
print(f' This is {
self.name}')
# Define a subclass
class Dogs(Animals):
def __init__(self) :
self.name=' Dog '# Animals have names
def info(self):
print(f' This is {
self.name}')
def make_Dogs(self):
# If you call the parent class properties and methods first , The attribute of the parent class will override the attribute of the child class , So before calling properties , First call your own subclass to initialize
self.__init__()
self.info()
def make_Animals(self):
# Call the superclass method , But in order to ensure that the property called is also the property of the parent class , So you must call the initialization of the parent class before calling the method
Animals.__init__(self)
Animals.info(self)
dog=Dogs()
dog.make_Dogs()
dog.make_Animals()
# This is a dog
# This is an animal
Allow multiple levels of inheritance , As long as there is inheritance , Subclasses can call methods and properties of all parent classes
Class name .__mro__
print(dogs.__mro__)
#(<class '__main__.dogs'>, <class '__main__.animal'>, <class 'object'>)
# With parameters
super( The class name of the current class ,self). Method of the same name
# No parameter
super(). Method of the same name
Here is a demonstration with parameters
# Define a parent class animal
class Animals():
def __init__(self) :
self.name=' animal '# Animals have names
def info(self):
print(f' This is {
self.name}')
# Define a subclass
class Dogs(Animals):
def __init__(self) :
self.name=' Dog '# Animals have names
def info(self):
print(f' This is {
self.name}')
def make_Dogs(self):
super(Dogs,self).__init__()
super(Dogs,self).info()
# def make_Dogs(self):
# # If you call the parent class properties and methods first , The attribute of the parent class will override the attribute of the child class , So before calling properties , First call your own subclass to initialize
# self.__init__()
# self.info()
# def make_Animals(self):
# # Call the superclass method , But in order to ensure that the property called is also the property of the parent class , So you must call the initialization of the parent class before calling the method
# Animals.__init__(self)
# Animals.info(self)
dog=Dogs()
dog.make_Dogs()
# dog.make_Animals()
# This is an animal
What is demonstrated here is parameterless
# Define a parent class animal
class Animals():
def __init__(self) :
self.name=' animal '# Animals have names
def info(self):
print(f' This is {
self.name}')
# Define a subclass
class Dogs(Animals):
def __init__(self) :
self.name=' Dog '# Animals have names
def info(self):
print(f' This is {
self.name}')
def make_Dogs(self):
super().__init__()
super().info()
# def make_Dogs(self):
# # If you call the parent class properties and methods first , The attribute of the parent class will override the attribute of the child class , So before calling properties , First call your own subclass to initialize
# self.__init__()
# self.info()
# def make_Animals(self):
# # Call the superclass method , But in order to ensure that the property called is also the property of the parent class , So you must call the initialization of the parent class before calling the method
# Animals.__init__(self)
# Animals.info(self)
dog=Dogs()
dog.make_Dogs()
# dog.make_Animals()
Set some properties or methods so that they are not inherited by subclasses
How to set private properties : Precede the property name and method name with two underscores
# Define a parent class animal
class Animals():
def __init__(self) :
self.__skin=' Hair '# This is a private property
self.name=' animal '# Animals have names
def info(self):
print(f' This is {
self.name}')
# Define a subclass
class Dogs(Animals):
def __init__(self) :
self.name=' Dog '# Animals have names
def info(self):
print(f' This is {
self.name}')
def make_Dogs(self):
super().__init__()
super().info()
dog=Dogs()
dog.make_Dogs()
print(dog.__skin)
This is an animal
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-18-ba391c645d4c> in <module>
20 dog=Dogs()
21 dog.make_Dogs()
---> 22 print(dog.__skin)
AttributeError: 'Dogs' object has no attribute '__skin'
Private attributes cannot be inherited , But it can be passed in the class get_xx
( Get private properties ) and set_xx
( Modify private properties )
# Define a parent class animal
class Animals():
def __init__(self) :
self.__skin=' Hair '# This is a private property
self.name=' animal '# Animals have names
def info(self):
print(f' This is {
self.name}')
def get_skin(self):
return self.__skin
def set_skin(self,skin):
self.__skin=skin
# Define a subclass
class Dogs(Animals):
pass
dog=Dogs()
dog.set_skin(' Brown hair ')
print(dog.get_skin())
# Brown hair
stay python in , Polymorphism does not necessarily come from inheritance , But the best source is inheritance
class Dog(object):
def work(self):
pass
class DrugDog(Dog):
def work(self):
print(' Trace drugs ')
class ArmyDog(Dog):
def work(self):
print(' Track down the prisoners ')
class Persion(object):
def work_with_dog(self,dog):
dog.work()
persion =Persion()
dog=ArmyDog()
persion.work_with_dog(dog)
dog=DrugDog()
persion.work_with_dog(dog)
Track down the prisoners
Trace drugs
Class properties are properties owned by class objects , It is public to all instance objects of this class
Class properties can be accessed using class objects or instance objects
# Define a class animal
class Animals():
tooth=10# Class properties
print(Animal.tooth)# Such access
cat=Animals()
print(cat.tooth)# Instance access
dog=Animals()
print(dog.tooth)
#10
#10
#10
Class attributes can only be modified through classes , Cannot be modified by an instance object , If you have heard of instance object modification , This means that an instance attribute is created
# Define a class animal
class Animals():
tooth=10# Class properties
Animals.tooth=14
print(Animals.tooth)
cat=Animals()
print(cat.tooth)
dog=Animals()
dog.tooth=20# Created an instance property tooth=20
print(cat.tooth)
print(dog.tooth)
14
14
14
20
@classmethod
It is class methods that are identified , For class methods , The first parameter must be a class object , General one cls
As the first parameter # Define a class animal
class Animals():
__tooth=10# Class properties
@classmethod
def get_tooth(cls):
return cls.__tooth
cat=Animals()
result=cat.get_tooth()
print(result)
#10
@staticmethod
To decorate , Static methods do not need to pass class objects or 1 Instance object ( No formal parameters self、cls)# Define a class animal
class Animals():
@staticmethod
def get_static():
print(' Static methods ')
cat=Animals()
cat.get_static()
Animals.get_static()
Static methods
Static methods
try:
The code that could have an error
except:
If there is an exception to the execution of the code
try:
f=open('test1.txt','r')
except:
f=open('test1.txt','w')
try:
The code that could have an error
except ( Exception types 1, Exception types 2) as result:
print(result)# Print the information of the captured exception
Be careful :
- If the exception type of the code you are trying to execute is not the same as the type you want to catch , There is no way to catch exceptions
- In general try There is only one line of code below
Exception Is the parent of all program exceptions
try:
The code that could have an error
except Exception as result:
print(result)# Print the information of the captured exception
else Indicates the code to be executed if there is no exception
try:
The code that could have an error
except Exception as result:
print(result)# Print the information of the captured exception
else:
There is no exception code block to execute
finally Indicates the code to be executed regardless of whether it is abnormal or not . For example, closing a file
try:
The code that could have an error
except Exception as result:
print(result)# Print the information of the captured exception
else:
There is no exception code block to execute
finally:
Code block to be executed no matter whether it is abnormal or not
stay python in , The syntax for throwing custom exceptions is raise Exception object
# Customize an exception class , Inheritance Exceptipon
class shortInputError(Exception):
def __init__(self,length,min_len ) :
self.length=length
self.min_len=min_len
def __str__(self) :
return f' The length you entered is {
self.length}, No less than {
self.min_len} Characters '
def main():
try:
con=input(' Please input a password :')
if len(con)<8:
raise shortInputError(len(con),8)
except Exception as result:
print(result)
else:
print(' The password is entered correctly ')
main()
import time
time. function
import time
print(time.time())
from time import time
Direct function call
from time import time
print(time())
from time from *
Direct function call
from time import *
print(time())
from time import time as t
print(t())
When importing a module ,python The order in which the parser searches for modules is :
Be careful :
- It is better not to duplicate your own file name with the existing module name , Otherwise, the existing modules will be unusable ( Because the search path goes from near to far )
- If
from Module name import function
, If the function name is repeated , What is called is the last defined or imported function- Here's what's interesting , Even variables with the same name , It will also cover the module , Because our content is through
quote
To define the , When our names are the same , That is, the reference is the same , It will cause the later things to cover the original things , So when we define the name, we must pay attention not to have the same name as the module
If there is this variable in a module file , When using from xxx import *
When you import it , Only elements in this list can be imported , Here's what's interesting , The name of this module , Only with .py
Name the suffix , It cannot be named after any other suffix
__all__=['testA']
def testA():
print('testA')
def testB():
print('testB')
from module1 import *
testA()
testB()
testA
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-10-5967f3f88564> in <module>
1 from module1 import *
2 testA()
----> 3 testB()
NameError: name 'testB' is not defined
Packages organize linked modules , That is, put it in the same folder , And create a folder named __init__.py
file , Then this folder is called package
mypackage
package __init__.py
、module1.py
、module2.py
file def module1_test():
print(' This is module1 Method ')
def module2_test():
print(' This is module2 Method ')
import Package name . Module name
Package name . Module name . The goal is
import mypackage.module1
mypackage.module1.module1_test()
__init__.py
Add... To the file __all__=[]
, Controls the list of modules that are allowed to be imported , If not set , It means that all modules cannot pass from Package name impor*
Module name . The goal is
# Control the import behavior of the package
__all__=['module1']
from mypackage import*
module1.module1_test()
This is module1 Method
class Dog(object):
a=1
def work(self):
print(' I am working ')
dog=Dog()
print(Dog.__dict__)
{
'__module__': '__main__', 'a': 1, 'work': <function Dog.work at 0x00000270150CA790>, '__dict__': <attribute '__dict__' of 'Dog' objects>, '__weakref__': <attribute '__weakref__' of 'Dog' objects>, '__doc__': None}
time
and calendar
Module can be used to format date and time .time.time()
Used to get the current timestamp ,import time
ticks=time.time()
print (" The current time is :",ticks)
# The current time is : 1634655386.6290803
quite a lot Python Functions are assembled in one element 9 Group digital processing time :
That is struct_time Tuples . This structure has the following properties :
import time
localtime = time.localtime(time.time())
print (" The local time is :", localtime)
The local time is : time.struct_time(tm_year=2021, tm_mon=10, tm_mday=19, tm_hour=23, tm_min=0, tm_sec=35, tm_wday=1, tm_yday=292, tm_isdst=0)
You can choose various formats according to your needs , But the simplest function to get a readable time pattern is asctime()
:
import time
localtime = time.asctime( time.localtime(time.time()) )
print (" The local time is :", localtime)
# The local time is : Tue Oct 19 23:03:06 2021
time.strftime(format[, t])
import time
# Format as 2016-03-20 11:45:39 form
print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) )
# Format as Sat Mar 28 22:24:24 2016 form
print(time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()) )
# Convert format string to timestamp
a = "Sat Mar 28 22:24:24 2016"
print (time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y")))
2021-10-19 23:07:24
Tue Oct 19 23:07:24 2021
1459175064.0
python Medium time date format symbol :
import calendar
cal = calendar.month(2016, 1)
print (" The following output 2016 year 1 Calendar of the month :")
print (cal)
The following output 2016 year 1 Calendar of the month :
January 2016
Mo Tu We Th Fr Sa Su
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Time The module contains the following built-in functions , There is time to deal with , There are also time format conversion :
Time The module contains the following 2 A very important attribute :
The functions of this module are calendar related , For example, print the character calendar of a month .
Monday is the first day of the week by default , Sunday is the last day by default . To change the settings, call calendar.setfirstweekday() function . The module contains the following built-in functions :
>>> import calendar >>> print(calendar.isleap(2000)) True >>> print(calendar.isleap(1900)) False
4calendar.leapdays(y1,y2) Back in the Y1,Y2 The total number of leap years between two years .5calendar.month(year,month,w=2,l=1) Returns the year year month Monthly calendar , Two line headings , A Monday trip . The daily width interval is w character . The length of each line is 7* w+6.l Is the number of lines per week .6calendar.monthcalendar(year,month) Returns a single nested list of integers . Each sublist load represents an integer for a week .Year year month All dates outside the month are set to 0; The days in the range are indicated by the day of the month , from 1 Start .7calendar.monthrange(year,month) Returns two integers . The first is the date code of the day of the week of the month , The second is the date code of the month . Day from 0( Monday ) To 6( Sunday ); Month from 1 To 12.8calendar.prcal(year,w=2,l=1,c=6) amount to print calendar.calendar(year,w=2,l=1,c=6).9calendar.prmonth(year,month,w=2,l=1) amount to print calendar.month(year,month,w=2,l=1) .10calendar.setfirstweekday(weekday) Set the start date code of the week .0( Monday ) To 6( Sunday ).11calendar.timegm(tupletime) and time.gmtime contrary : Accept a time tuple form , Returns the timestamp of the time (1970 Floating point seconds after the era ).12calendar.weekday(year,month,day) Returns the date code of a given date .0( Monday ) To 6( Sunday ). Month is 1( January ) To 12(12 month ).stay Python in , Other modules that deal with date and time are :